问:
Laravel get only needed columns from relationship object
I have 2 post types:

Company

Vacancy

Here I'll get only needed columns after fetching post by type:

```<code>$posts = $posts->map(function($post) use ($company, $vacancy) {
    switch ($post->type) {
        case $company:
            return $post->only([
                'id',
                'name',
                'slogan',
                'logo'
            ]);
            break;
        case $vacancy:
            return $post->only([
                'id',
                'title',
                'price',
                'schedule',
                'employment',
                'company'
            ]);
            break;
    }
});
</code>```

As you see vacancy post type need to company column which is relationship object and company post type need only to columns:

'id'

'name'

'slogan'

'logo'

But when I request vacancy post type with company relationship object then company post type returned with all columns instead of needed column only.

How can be solved my problem?

答:
You can define models for Company and Vacancy

```<code>class Company extends Post {
    protected $table = 'posts';

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(function ($query) {
            $query->where('type', 'company');
        });
    }
}

class Vacancy extends Post {
    protected $table = 'posts';

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(function ($query) {
            $query->where('type', 'vacancy');
        });
    }
}
</code>```

In a project I managed this using a pivot table to store the relationships between the two type of models (I used BelongsToMany, but I think you can specify a HasOne as well

Body:
I have 2 post types:

Company

Vacancy

Here I'll get only needed columns after fetching post by type:

$posts = $posts->map(function($post) use ($company, $vacancy) {
    switch ($post->type) {
        case $company:
            return $post->only([
                'id',
                'name',
                'slogan',
                'logo'
            ]);
            break;
        case $vacancy:
            return $post->only([
                'id',
                'title',
                'price',
                'schedule',
                'employment',
                'company'
            ]);
            break;
    }
});

As you see vacancy post type need to company column which is relationship object and company post type need only to columns:

'id'

'name'

'slogan'

'logo'

But when I request vacancy post type with company relationship object then company post type returned with all columns instead of needed column only.

How can be solved my problem?

Body:
You can define models for Company and Vacancy

class Company extends Post {
    protected $table = 'posts';

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(function ($query) {
            $query->where('type', 'company');
        });
    }
}

class Vacancy extends Post {
    protected $table = 'posts';

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(function ($query) {
            $query->where('type', 'vacancy');
        });
    }
}

In a project I managed this using a pivot table to store the relationships between the two type of models (I used BelongsToMany, but I think you can specify a HasOne as well


来源: stackexchange

问:
From a programming point of view, what does it mean when a program is 32 or 64 bit?
I'm a beginner programmer in my first year of Computer Science.
I'm curious about the 32 bit and 64 bit systems, and how it affects developing software.
When I download software I need to choose between the two, while other software only has a 32 bit version.

Are there different ways of programming for a 64 bit system?

Is it compiled in the same way?

What are the main benefits of a separate 64 bit app?

Cheers

答:
Are there different ways of programming for a 64 bit system?

Yes and no. No, in the sense that most of the time you should be able to write platform-independent code, even if you are coding in a language like C. Yes, in the sense that having knowledge of the underlying architecture (not just the word size!) helps to speed up critical parts of your program. For instance, you may be able to use special instructions available.

Is it compiled in the same way?

Again, yes and no. Compilers for systems languages work in similar ways for all architectures, but of course, the details differ a bit. For instance, the compiler will use knowledge about your architecture to generate as efficient code as possible for it, but also has to take care of differences between architectures and other details, like calling conventions.

What are the main benefits of a separate 64 bit app?

I assume you are asking about the usual desktop CPUs, i.e. x86 architecture, but note that there are other architectures with word sizes ranging from 8-bit to 128-bit. Typically, people would compile a program targeting a single architecture (i.e. for a given machine), and that's about it.

However, x86 is a bit special, in that the CPU can operate in different modes, each with a different word size: 16-bit, 32-bit and 64-bit (among other differences). Effectively, they implement several ISAs (Instruction Set Architectures) in a single CPU.

This was done to preserve backwards compatibility, and it is key to their commercial success. Consider that, when people bought the first 64-bit capable CPUs, it was most likely that they were still using 32-bit operating systems and software, so they really needed the compatibility. The other options are emulating it (poor performance) or making sure all the popular customer software has been ported (hard to achieve in ecosystems like Windows with many independent, proprietary vendors).

There are several benefits of 64-bit x86 over 32-bit x86: more addressable memory, more integer registers, twice the XMM registers, a better calling convention, guaranteed SSE2... The only downside is using 64-bit pointers, which implies more memory and cache usage. In practice, many programs can expect to be slightly faster in x64 (e.g. 10%), but pointer-heavy programs may even see a decrease in performance.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Add value to dynamically populated list c#
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

```<code>public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}
</code>```

Extract from the Razor template

```<code><div class="editor-field">
    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))
</div>
</code>```

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

答:
I ended up using

```<code><div class="editor-field">
    @Html.DropDownListFor(model => model.ParentGuid,
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "OrganizationGuid", "Title", Model.ParentGuid), "")
</div>
</code>```

The method serving the template looks like this

```<code>public ActionResult Create()
{
    try
    {
        ViewBag.Organizations = db.Organizations.OrderBy(o => o.Title).ToList();

        var organization = new Organization();
        return View(organization);
    }
    catch (Exception e)
    {
        ViewData["error"] = string.Concat(e.Message, " ", e.StackTrace);
        return RedirectToAction("Index");
    }
}
</code>```

Body:
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}

Extract from the Razor template

    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

Body:
I ended up using

<div class="editor-field">
    @Html.DropDownListFor(model => model.ParentGuid,
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "OrganizationGuid", "Title", Model.ParentGuid), "")
</div>

The method serving the template looks like this

public ActionResult Create()
{
    try
    {
        ViewBag.Organizations = db.Organizations.OrderBy(o => o.Title).ToList();

        var organization = new Organization();
        return View(organization);
    }
    catch (Exception e)
    {
        ViewData["error"] = string.Concat(e.Message, " ", e.StackTrace);
        return RedirectToAction("Index");
    }
}


问:
Why null is being display on the screen in an Angular 5 app?
I have simple template which display a value of a string:

```<code><span class="fax_number">{{company.fax}}</span>
</code>```

When the value empty, the screen display the string "null" instead of
empty string, this happen in many places in the application, is there
a good way to avoid this ?

答:
The comapany data must have been type casted to string which is converting null to "null"

Try like this:

```<code><span class="fax_number"><span *ngIf="company.fax!="null">{{company.fax}}</span>
</code>```

Or you can create a custom pipe to convert "null" to empty string. This can be used through out the project.

Body:
I have simple template which display a value of a string:

{{company.fax}}

When the value empty, the screen display the string "null" instead of
empty string, this happen in many places in the application, is there
a good way to avoid this ?

Body:
The comapany data must have been type casted to string which is converting null to "null"

Try like this:

<span class="fax_number"><span *ngIf="company.fax!="null">{{company.fax}}</span>

Or you can create a custom pipe to convert "null" to empty string. This can be used through out the project.


问:
Code runs when copy/pasted as macro, but not when saved as add-in
As the title suggests, this code fails on the line Sheet.Copy After:=ThisWorkbook.Sheets(1) with runtime error 1004

Why would this run when added as a module but not when saved as an add-in?

Here's the code:

Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet

Application.ScreenUpdating = False
FolderPath = GetFolder() & "\"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
 Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
 For Each Sheet In ActiveWorkbook.Sheets
 Sheet.Copy After:=ThisWorkbook.Sheets(1)
 Next Sheet
 Workbooks(Filename).Close
 Filename = Dir()
 Loop

Application.ScreenUpdating = True
End Sub
```

答:
As @BruceWayne suggested is a problem with deciding the correct workbook. As an AddIn, ThisWorkbook will be the AddIn workbook, while ActiveWorkbook (before opening others), will be the workbook you are running your AddIn into.

Simply replacing Thisworkbook with ActiveWorkbook in your scenario won't work, because you would just copy the sheets from the newly open workbook, to the same.

Is a good idea to declare variables to hold this informations, then you can open as many workbooks as you want, and from where you want.

See below:

Application.ScreenUpdating = False

Dim wbDst As Workbook: Set wbDst = ActiveWorkbook 'Can also use Worbooks("book name here")
Dim wbSrc As Workbook
Dim Sht As Worksheet

Dim FolderPath As String: FolderPath = GetFolder() & "\"
Dim FileName As String: FileName = Dir(FolderPath & "*.xls*")

Do While FileName <> ""
    Set wbSrc = Workbooks.Open(FileName:=FolderPath & FileName, ReadOnly:=True)

    For Each Sht In wbSrc.Worksheets
        Sht.Copy After:=wbDst.Sheets(1)
    Next Sht

    wbSrc.Close
    FileName = Dir()
Loop

Application.ScreenUpdating = True
```


问:
Using ssh-agent with docker on macOS
I would like to use ssh-agent to forward my keys into the docker image and pull from a private github repo.

I am using a slightly modified version of https://github.com/phusion/passenger-docker with boot2docker on Yosemite.

```<code>ssh-add -l
...key details
boot2docker up
</code>```

Then I use the command which I have seen in a number of places (i.e. https://gist.github.com/d11wtq/8699521):

```<code>docker run --rm -t -i -v $SSH_AUTH_SOCK:/ssh-agent -e SSH_AUTH_SOCK=/ssh-agent my_image /bin/bash
</code>```

However it doesn't seem to work:

```<code>root@299212f6fee3:/# ssh-add -l
Could not open a connection to your authentication agent.

root@299212f6fee3:/# eval `ssh-agent -s`
Agent pid 19

root@299212f6fee3:/# ssh-add -l
The agent has no identities.

root@299212f6fee3:/# ssh git@github.com
Warning: Permanently added the RSA host key for IP address '192.30.252.128' to the list of known hosts.
Permission denied (publickey).
</code>```

答:
Socket forwarding doesn't work on OS X yet.  Here is a variation of @henrjk answer brought into 2019 using Docker for Mac instead of boot2docker which is now obsolete.

First run a ssh server in the container, with /tmp being on the exportable volume.  Like this

```<code> docker run -v tmp:/tmp -v \
 ${HOME}/.ssh/id_rsa.pub:/root/.ssh/authorized_keys:ro \
 -d -p 2222:22 arvindr226/alpine-ssh
</code>```

Then ssh into this container with agent forwarding

```<code> ssh -A -p 2222 root@localhost
</code>```

Inside of that ssh session find out the current socket for ssh-agent

```<code> 3f53fa1f5452:~# echo $SSH_AUTH_SOCK
 /tmp/ssh-9zjJcSa3DM/agent.7
</code>```

Now you can run your real container.  Just make sure to replace the value of SSH_AUTH_SOCK below, with the value you got in the step above

```<code> docker run -it -v tmp:/tmp  \
 -e SSH_AUTH_SOCK=/tmp/ssh-9zjJcSa3DM/agent.7 \
 vladistan/ansible
</code>```

Title: Using ssh-agent with docker on macOS

Body:
I would like to use ssh-agent to forward my keys into the docker image and pull from a private github repo.

I am using a slightly modified version of https://github.com/phusion/passenger-docker with boot2docker on Yosemite.

ssh-add -l
...key details
boot2docker up

Then I use the command which I have seen in a number of places (i.e. https://gist.github.com/d11wtq/8699521):

docker run --rm -t -i -v $SSH_AUTH_SOCK:/ssh-agent -e SSH_AUTH_SOCK=/ssh-agent my_image /bin/bash

However it doesn't seem to work:

root@299212f6fee3:/# ssh-add -l
Could not open a connection to your authentication agent.

root@299212f6fee3:/# eval `ssh-agent -s`
Agent pid 19

root@299212f6fee3:/# ssh-add -l
The agent has no identities.

root@299212f6fee3:/# ssh git@github.com
Warning: Permanently added the RSA host key for IP address '192.30.252.128' to the list of known hosts.
Permission denied (publickey).

Body:
Socket forwarding doesn't work on OS X yet.  Here is a variation of @henrjk answer brought into 2019 using Docker for Mac instead of boot2docker which is now obsolete.

First run a ssh server in the container, with /tmp being on the exportable volume.  Like this

 docker run -v tmp:/tmp -v \
 ${HOME}/.ssh/id_rsa.pub:/root/.ssh/authorized_keys:ro \
 -d -p 2222:22 arvindr226/alpine-ssh

Then ssh into this container with agent forwarding

 ssh -A -p 2222 root@localhost

Inside of that ssh session find out the current socket for ssh-agent

 3f53fa1f5452:~# echo $SSH_AUTH_SOCK
 /tmp/ssh-9zjJcSa3DM/agent.7

Now you can run your real container.  Just make sure to replace the value of SSH_AUTH_SOCK below, with the value you got in the step above

 docker run -it -v tmp:/tmp  \
 -e SSH_AUTH_SOCK=/tmp/ssh-9zjJcSa3DM/agent.7 \
 vladistan/ansible


问:
Ajax - problem with response inside a div
I am trying to show the value of ajax response inside a div.Ajax. Problem arise when I get the response. Response is showing in the div only for split second and hides automatically. I tried changing id to class but the error persist still. The alert displays properly when tested. What do I miss? I have the following code in my view file.

The div:

```<code><div id="result"></div>
</code>```

Ajax:

```<code> $(document).ready(function() {
 $('#submit').click(function() {

 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

if(response == 'success')
{
    alert('success');
}
if(response == 'empty')
{
    alert('empty');

}
if(response == 'bad')
{
     $("#result").html(response);

}
}

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

save.php:

```<code><?php
$co= 'aaa';

if(!empty($_POST['tosave']))
{

    if($_POST['tosave'] == $co)
{
    $foo = fopen("plik.txt","a+");

            flock($foo, 2);
            fwrite($foo,$_POST['tosave']."\r\n");
            flock($foo ,3);
            fclose($foo);
echo "success";
exit();
} else {

    echo 'bad';
    exit;
}

} else {

echo "empty";
exit;

}
?>
</code>```

答:
First of all there is a mistake in your Ajax call code you have write your submit.click() submit function under document.ready().remove document.ready() because submit.click()will run when you submit the form. Second thing is you should add
event.preventDefault() to prevent the default behabiour of your submit form otherwise it will display for short time and then it will disappeared.See my code below it is working.

AJAX WITH HTML FORM:

```<code> <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>

    <form id="action">
        <input type="text" name="tosave" value="bbb">
        <button type="submit">clickme</button>>
    </form>

    <div id="result"></div>
    </body>
    </html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script type="text/javascript">

        $("#action").click(function(event) {
        event.preventDefault();//TO PREVENT THE DEFAULT BEHAVIOUR OF FORM
     $.ajax
     ({
      type:'post',
      cache: false,
      url:'https:save.php',
      data: $("#action").serialize(),
      dataType: "html",

     success: function(response) {

    if(response == 'success')
    {
        alert('success');
    }
    if(response == 'empty')
    {
        alert('empty');

    }
    if(response == 'bad')
    {
         $("#result").html(response);

    }
    }

     });
    });

    </script>
</code>```

PHP:

```<code><?php
$co = 'aaa';

if (!empty($_POST['tosave'])) {

    if ($_POST['tosave'] == $co) {
        $foo = fopen("plik.txt", "a+");

        flock($foo, 2);
        fwrite($foo, $_POST['tosave'] . "\r\n");
        flock($foo, 3);
        fclose($foo);
        echo "success";
        exit();
    } else {

        echo 'bad';
        exit;
    }

} else {

    echo "empty";
    exit;

}
?>
**OUTPUT DISPLAY IN DIV: bad**
</code>```

Body:
I am trying to show the value of ajax response inside a div.Ajax. Problem arise when I get the response. Response is showing in the div only for split second and hides automatically. I tried changing id to class but the error persist still. The alert displays properly when tested. What do I miss? I have the following code in my view file.

The div:

Ajax:

 $(document).ready(function() {
 $('#submit').click(function() {

 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

if(response == 'success')
{
    alert('success');
}
if(response == 'empty')
{
    alert('empty');

}
if(response == 'bad')
{
     $("#result").html(response);

}
}

 });
});
});

save.php:

<?php
$co= 'aaa';

if(!empty($_POST['tosave']))
{

    if($_POST['tosave'] == $co)
{
    $foo = fopen("plik.txt","a+");

            flock($foo, 2);
            fwrite($foo,$_POST['tosave']."\r\n");
            flock($foo ,3);
            fclose($foo);
echo "success";
exit();
} else {

    echo 'bad';
    exit;
}

} else {

echo "empty";
exit;

}
?>

Body:
First of all there is a mistake in your Ajax call code you have write your submit.click() submit function under document.ready().remove document.ready() because submit.click()will run when you submit the form. Second thing is you should add
event.preventDefault() to prevent the default behabiour of your submit form otherwise it will display for short time and then it will disappeared.See my code below it is working.

AJAX WITH HTML FORM:

 <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>

    <form id="action">
        <input type="text" name="tosave" value="bbb">
        <button type="submit">clickme</button>>
    </form>

    <div id="result"></div>
    </body>
    </html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script type="text/javascript">

        $("#action").click(function(event) {
        event.preventDefault();//TO PREVENT THE DEFAULT BEHAVIOUR OF FORM
     $.ajax
     ({
      type:'post',
      cache: false,
      url:'https:save.php',
      data: $("#action").serialize(),
      dataType: "html",

     success: function(response) {

    if(response == 'success')
    {
        alert('success');
    }
    if(response == 'empty')
    {
        alert('empty');

    }
    if(response == 'bad')
    {
         $("#result").html(response);

    }
    }

     });
    });

    </script>

PHP:

<?php
$co = 'aaa';

if (!empty($_POST['tosave'])) {

    if ($_POST['tosave'] == $co) {
        $foo = fopen("plik.txt", "a+");

        flock($foo, 2);
        fwrite($foo, $_POST['tosave'] . "\r\n");
        flock($foo, 3);
        fclose($foo);
        echo "success";
        exit();
    } else {

        echo 'bad';
        exit;
    }

} else {

    echo "empty";
    exit;

}
?>
**OUTPUT DISPLAY IN DIV: bad**


问:
Change button style inside paypal i frame using jquery not working
i have following iframe in my website

<iframe class="zoid-component-frame zoid-visible" frameborder="0" allowtransparency="true" name="test" title="ppbutton" scrolling="no" allowpaymentrequest="allowpaymentrequest" src="https://www.paypal.com/webapps/hermes/button?env=production&commit=true&style.label=pay&style.layout=vertical&style.size=responsive&style.shape=rect&style.color=gold&style.tagline=false&locale.x=en_US&funding.disallowed=credit%2Cvenmo&domain=store17204827.ecwid.com&sessionID=93bede67c2_mdy6mzk6mdg&buttonSessionID=c3989cbef7_mdy6mzk6mdg&logLevel=warn&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWxvYmplY3RzLmNvbS9hcGkvY2hlY2tvdXQubWluLmpzIn0%3D&uid=645255e5ef&version=min&xcomponent=1" style="background-color: transparent;">```
</div>
</div>
</p>

<p>If you run the code here you can see there is a button coming . I want to change the yellow button text as "pay with debit or credit card" .i tried things but noting work . I try to hide the button log that also not working . Please see our code </p>

```$(".zoid-component-frame.zoid-visible").bind("load",function(){
        alert();
    $(this).contents().find(".paypal-button-logo-gold").css("display","none");
});
```

Please help to solve this issue .

答:
we cannot change the iframe content getting from other domain
CHeck this link
How to change style of iframe content cross-domain?</p>

Body:
i have following iframe in my website

<iframe class="zoid-component-frame zoid-visible" frameborder="0" allowtransparency="true" name="test" title="ppbutton" scrolling="no" allowpaymentrequest="allowpaymentrequest" src="https://www.paypal.com/webapps/hermes/button?env=production&commit=true&style.label=pay&style.layout=vertical&style.size=responsive&style.shape=rect&style.color=gold&style.tagline=false&locale.x=en_US&funding.disallowed=credit%2Cvenmo&domain=store17204827.ecwid.com&sessionID=93bede67c2_mdy6mzk6mdg&buttonSessionID=c3989cbef7_mdy6mzk6mdg&logLevel=warn&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWxvYmplY3RzLmNvbS9hcGkvY2hlY2tvdXQubWluLmpzIn0%3D&uid=645255e5ef&version=min&xcomponent=1" style="background-color: transparent;">

If you run the code here you can see there is a button coming . I want to change the yellow button text as "pay with debit or credit card" .i tried things but noting work . I try to hide the button log that also not working . Please see our code

$(".zoid-component-frame.zoid-visible").bind("load",function(){
        alert();
    $(this).contents().find(".paypal-button-logo-gold").css("display","none");
});

Please help to solve this issue .


问:
org.hibernate.InstantiationException: Cannot instantiate abstract class or interface
I have the following entity:

```<code>@Entity
@Table(name = "davt_compensation_service")
@Inheritance(strategy = InheritanceType.JOINED)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public abstract class Compensation<C extends Compensation> extends AutoIdBasedEntity {
    //properties, setters and getters, equals and hashcode overrides.
}
</code>```

The rest inherit from it (one of them for example):

```<code>@Entity
@Table(name = "davt_compensation_service_relocation")
public class RelocationCompensation extends Compensation<RelocationCompensation> {
    //properties, setters and getters, equals and hashcode overrides
}
</code>```

A parent entity that contains a collection of Compensations:

```<code>@Entity
@Table(name = "davt_compensation_case")
@EntityListeners({CompensationCaseNumberListener.class})
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class CompensationCase extends AutoIdBasedEntity {

    @Valid
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "compensationCase", orphanRemoval = true)
    @MapKey(name = "conceptType")
    private Map<ConceptType, Compensation> compensationServices = new HashMap<>();
}
</code>```

Last but not least, I have a the main entity CompensationFile which has a collection of CompensationCase entities:

```<code>@Entity
@Table(name = "davt_compensation_file")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class CompensationFile extends AutoIdBasedEntity {

    @Valid
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "compensationFile", orphanRemoval = true)
    private Set<CompensationCase> compensationCases;
}
</code>```

It's strange because this used to work and suddenly it started working up. For some reason it only happens when updating and existing CompensationCase and adding a new Compensation. For example, if I am persisting an entirely new main CompensationCase, it works without a hitch. I use the JpaRepository method save on the main entity CompensationFile to persist the entire thing as shown below (and where it is throwing the exception):

CompensationFileFormService:

```<code>@Service
public class CompensationFileFormService {
    @Autowired
    private CompensationFileRepository compensationFileRepository;

    @Autowired
    private CompensationFileFormConverter compensationFileFormConverter;

    @Autowired
    private CompensationCaseService compensationCaseService;

    public CompensationFileForm saveCompensationFile(CompensationFileForm compensationFileForm) throws TaskNotFoundException, InvalidServiceTypeException, CompensationFileNotFoundException, CompensationCaseNotFoundException {

        CompensationFile compensationFile = compensationFileFormConverter.convertToCompensationFile(compensationFileForm);

        //EXCEPTION IS THROWN HERE
        CompensationFile newCompensationFile = compensationFileRepository.save(compensationFile);

        if (!newCompensationFile.getCompensationCases().isEmpty()) {
            for (CompensationCase compensationCase : newCompensationFile.getCompensationCases()) {
                compensationCaseTaskService.save(compensationCase, compensationCase.getAssignedPersonnel());
            }
        }

        return createCompensationFileForm(newCompensationFile.getId(), newCompensationFile.getControlId(), compensationFileForm.getSelectedCompensationCase().getId());
    }
}
</code>```

CompensationFileRepository:

```<code>public interface CompensationFileRepository extends JpaRepository<CompensationFile, Long>, JpaSpecificationExecutor<CompensationFile> {
}
</code>```

Exception thrown:

```<code>26-Jul-2015 21:45:27.061 SEVERE [http-nio-9090-exec-11] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/nimchip] threw exception [Request processing failed; nested exception is org.springframework.webflow.execution.ActionExecutionException: Exception thrown executing [AnnotatedAction@1b7ee93d targetAction = [EvaluateAction@2902b1e5 expression = compensationFileFormService.saveCompensationFile(compensationFileForm), resultExpression = flowScope.compensationFileForm], attributes = map[[empty]]] in state 'save' of flow 'compensation/file/compensation-file' -- action execution attributes were 'map[[empty]]'] with root cause
 org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: sijc.davt.compensation.model.concepts.Compensation
    at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:114)
    at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:136)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.instantiate(AbstractEntityTuplizer.java:727)
    at org.hibernate.persister.entity.AbstractEntityPersister.instantiate(AbstractEntityPersister.java:4440)
    at org.hibernate.type.EntityType.replace(EntityType.java:285)
    at org.hibernate.type.MapType.replaceElements(MapType.java:83)
    at org.hibernate.type.CollectionType.replace(CollectionType.java:570)
    at org.hibernate.type.TypeHelper.replace(TypeHelper.java:177)
    at org.hibernate.event.internal.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:372)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsPersistent(DefaultMergeEventListener.java:184)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:157)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:914)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:896)
    at org.hibernate.engine.spi.CascadingAction$6.cascade(CascadingAction.java:288)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:380)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:409)
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:350)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:326)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
    at org.hibernate.event.internal.DefaultMergeEventListener.cascadeOnMerge(DefaultMergeEventListener.java:439)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:308)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:151)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:76)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:904)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:888)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:892)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:879)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
    at com.sun.proxy.$Proxy550.merge(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
    at com.sun.proxy.$Proxy550.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:392)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy677.save(Unknown Source)
    at test.nimchip.davt.compensation.ui.service.CompensationFileFormService.saveCompensationFile(CompensationFileFormService.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:112)
    at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:129)
    at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:49)
    at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:342)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:131)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:299)
    at org.springframework.binding.expression.spel.SpringELExpression.getValue(SpringELExpression.java:84)
    at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:75)
    at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
    at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145)
    at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)
    at org.springframework.webflow.engine.ActionState.doEnter(ActionState.java:101)
    at org.springframework.webflow.engine.State.enter(State.java:194)
    at org.springframework.webflow.engine.Transition.execute(Transition.java:228)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.execute(FlowExecutionImpl.java:395)
    at org.springframework.webflow.engine.impl.RequestControlContextImpl.execute(RequestControlContextImpl.java:214)
    at org.springframework.webflow.engine.TransitionableState.handleEvent(TransitionableState.java:116)
    at org.springframework.webflow.engine.Flow.handleEvent(Flow.java:547)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.handleEvent(FlowExecutionImpl.java:390)
    at org.springframework.webflow.engine.impl.RequestControlContextImpl.handleEvent(RequestControlContextImpl.java:210)
    at org.springframework.webflow.engine.ViewState.handleEvent(ViewState.java:231)
    at org.springframework.webflow.engine.ViewState.resume(ViewState.java:195)
    at org.springframework.webflow.engine.Flow.resume(Flow.java:537)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:259)
    at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
    at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:228)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at test.nimchip.filter.LocaleConfigurerFilter.doFilterInternal(LocaleConfigurerFilter.java:35)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Any help at all will be appreciated.

答:
For others that the above solutions might not work, give this a thought and a try afterwards:
When you have you child entities inherit parent entity you will not be able to instantiate the Parent itself but you should instantiate the child that has the parents properties -
For example i had Parent abstract class Profile and i had a child class StudentProfile that extended it. I tried instantiating a list of profiles and it threw the exception(I had data in the profile table in the database but i forgot to add data to the StudentProfile table(and connect them through the for foreign key column - in my case id)
My solution was to add the corresponding data to the StudentProfile table and then i was able to get rid of the exception.
Hope this helps!!</p>

Body:
I have the following entity:

@Entity
@Table(name = "davt_compensation_service")
@Inheritance(strategy = InheritanceType.JOINED)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public abstract class Compensation<C extends Compensation> extends AutoIdBasedEntity {
    //properties, setters and getters, equals and hashcode overrides.
}

The rest inherit from it (one of them for example):

@Entity
@Table(name = "davt_compensation_service_relocation")
public class RelocationCompensation extends Compensation<RelocationCompensation> {
    //properties, setters and getters, equals and hashcode overrides
}

A parent entity that contains a collection of Compensations:

@Entity
@Table(name = "davt_compensation_case")
@EntityListeners({CompensationCaseNumberListener.class})
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class CompensationCase extends AutoIdBasedEntity {

    @Valid
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "compensationCase", orphanRemoval = true)
    @MapKey(name = "conceptType")
    private Map<ConceptType, Compensation> compensationServices = new HashMap<>();
}

Last but not least, I have a the main entity CompensationFile which has a collection of CompensationCase entities:

@Entity
@Table(name = "davt_compensation_file")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class CompensationFile extends AutoIdBasedEntity {

    @Valid
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "compensationFile", orphanRemoval = true)
    private Set<CompensationCase> compensationCases;
}

It's strange because this used to work and suddenly it started working up. For some reason it only happens when updating and existing CompensationCase and adding a new Compensation. For example, if I am persisting an entirely new main CompensationCase, it works without a hitch. I use the JpaRepository method save on the main entity CompensationFile to persist the entire thing as shown below (and where it is throwing the exception):

CompensationFileFormService:

@Service
public class CompensationFileFormService {
    @Autowired
    private CompensationFileRepository compensationFileRepository;

    @Autowired
    private CompensationFileFormConverter compensationFileFormConverter;

    @Autowired
    private CompensationCaseService compensationCaseService;

    public CompensationFileForm saveCompensationFile(CompensationFileForm compensationFileForm) throws TaskNotFoundException, InvalidServiceTypeException, CompensationFileNotFoundException, CompensationCaseNotFoundException {

        CompensationFile compensationFile = compensationFileFormConverter.convertToCompensationFile(compensationFileForm);

        //EXCEPTION IS THROWN HERE
        CompensationFile newCompensationFile = compensationFileRepository.save(compensationFile);

        if (!newCompensationFile.getCompensationCases().isEmpty()) {
            for (CompensationCase compensationCase : newCompensationFile.getCompensationCases()) {
                compensationCaseTaskService.save(compensationCase, compensationCase.getAssignedPersonnel());
            }
        }

        return createCompensationFileForm(newCompensationFile.getId(), newCompensationFile.getControlId(), compensationFileForm.getSelectedCompensationCase().getId());
    }
}

CompensationFileRepository:

public interface CompensationFileRepository extends JpaRepository<CompensationFile, Long>, JpaSpecificationExecutor<CompensationFile> {
}

Exception thrown:

26-Jul-2015 21:45:27.061 SEVERE [http-nio-9090-exec-11] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/nimchip] threw exception [Request processing failed; nested exception is org.springframework.webflow.execution.ActionExecutionException: Exception thrown executing [AnnotatedAction@1b7ee93d targetAction = [EvaluateAction@2902b1e5 expression = compensationFileFormService.saveCompensationFile(compensationFileForm), resultExpression = flowScope.compensationFileForm], attributes = map[[empty]]] in state 'save' of flow 'compensation/file/compensation-file' -- action execution attributes were 'map[[empty]]'] with root cause
 org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: sijc.davt.compensation.model.concepts.Compensation
    at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:114)
    at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:136)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.instantiate(AbstractEntityTuplizer.java:727)
    at org.hibernate.persister.entity.AbstractEntityPersister.instantiate(AbstractEntityPersister.java:4440)
    at org.hibernate.type.EntityType.replace(EntityType.java:285)
    at org.hibernate.type.MapType.replaceElements(MapType.java:83)
    at org.hibernate.type.CollectionType.replace(CollectionType.java:570)
    at org.hibernate.type.TypeHelper.replace(TypeHelper.java:177)
    at org.hibernate.event.internal.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:372)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsPersistent(DefaultMergeEventListener.java:184)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:157)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:914)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:896)
    at org.hibernate.engine.spi.CascadingAction$6.cascade(CascadingAction.java:288)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:380)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:409)
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:350)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:326)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
    at org.hibernate.event.internal.DefaultMergeEventListener.cascadeOnMerge(DefaultMergeEventListener.java:439)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:308)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:151)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:76)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:904)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:888)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:892)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:879)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
    at com.sun.proxy.$Proxy550.merge(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
    at com.sun.proxy.$Proxy550.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:392)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy677.save(Unknown Source)
    at test.nimchip.davt.compensation.ui.service.CompensationFileFormService.saveCompensationFile(CompensationFileFormService.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:112)
    at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:129)
    at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:49)
    at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:342)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:131)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:299)
    at org.springframework.binding.expression.spel.SpringELExpression.getValue(SpringELExpression.java:84)
    at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:75)
    at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
    at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145)
    at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)
    at org.springframework.webflow.engine.ActionState.doEnter(ActionState.java:101)
    at org.springframework.webflow.engine.State.enter(State.java:194)
    at org.springframework.webflow.engine.Transition.execute(Transition.java:228)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.execute(FlowExecutionImpl.java:395)
    at org.springframework.webflow.engine.impl.RequestControlContextImpl.execute(RequestControlContextImpl.java:214)
    at org.springframework.webflow.engine.TransitionableState.handleEvent(TransitionableState.java:116)
    at org.springframework.webflow.engine.Flow.handleEvent(Flow.java:547)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.handleEvent(FlowExecutionImpl.java:390)
    at org.springframework.webflow.engine.impl.RequestControlContextImpl.handleEvent(RequestControlContextImpl.java:210)
    at org.springframework.webflow.engine.ViewState.handleEvent(ViewState.java:231)
    at org.springframework.webflow.engine.ViewState.resume(ViewState.java:195)
    at org.springframework.webflow.engine.Flow.resume(Flow.java:537)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:259)
    at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
    at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:228)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at test.nimchip.filter.LocaleConfigurerFilter.doFilterInternal(LocaleConfigurerFilter.java:35)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Any help at all will be appreciated.


问:
Apache POI: Find out colspan of text overflowing to next column
I'm using Apache POI for converting Excel to HTML. I want the HTML table to be exactly as it appears in Excel. I see that many times there are cases where data in Excel cell overflows to next column. Is there a way to find out how many columns is the data spanning so I can add a colspan attribute to the TD tag? See this screenshot from Excel:

In this case, the data in cell A2 is overflowing to cell B2 (also A3 overflowing to B3). Is there a way to find out that the TD tag corresponding to cell A2 needs colspan="2" attribute?

The cells where the data is overflowing are not merged so I cannot really use functions like sheet.getNumMergedRegions()

I think I can also calculate it if somehow I can find out the "visible" width of columns in Excel. However, sheet.getColumnWidth() only provides the actual width. I don't see a method to find out the "visible" width of a column in Excel. In the screenshot link above the visible width of column A is very small. Is there a way to find that "visible" width?

I'm using Apache POI 3.17

答:
Apache poi is able autosize the columns according to their contents. So it needs to be able calculating what column width a special content would need. This is what SheetUtil.getCellWidth is doing.

Additionally one needs to know the very special measurement units Microsoft has introduced for column widths in Excel. In Excels GUI a column width of 10 for example means that 10 characters of default character width fits into the cell width. But internally the width is calculated in units of 1/256th of a default character width. That's why apache poi decided to get Sheet.getColumnWidth in units of 1/256th of a character width.

So if you have got a Cell cell having cell index c and having a special content, then using

```<code>Workbook workbook...
...
DataFormatter dataFormatter = new DataFormatter();
...
int defaultCharWidth = SheetUtil.getDefaultCharWidth(workbook);
...
double cellValueWidth = SheetUtil.getCellWidth(cell, defaultCharWidth, dataFormatter, false);
int neededColunmnWidth = (int)cellValueWidth*256;
int columnWidth = sheet.getColumnWidth(c);
...
</code>```

you could determine whether the content fits into the cell. It fits if columnWidth >= neededColunmnWidth, else it fits not and colspan must be used.

Lets have a complete example to show the principle:

Sheet:

Code:

```<code>import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.SheetUtil;

import java.io.*;

class ExcelToHTMLColspan {

 public static void main(String[] args) throws Exception{

  Workbook workbook = WorkbookFactory.create(new FileInputStream("Test.xlsx"));

  DataFormatter dataFormatter = new DataFormatter();

  int defaultCharWidth = SheetUtil.getDefaultCharWidth(workbook);

  int lastColumnToExport = 5; // column E

  Sheet sheet = workbook.getSheetAt(0);

  Row row;
  Cell cell;
  String cellValue;

  StringBuilder tableHTML = new StringBuilder();

  tableHTML.append("<TABLE>");
  tableHTML.append("<COLGROUP>");
  for (int c = 0; c < lastColumnToExport; c++) {
   long columnWidthPx = Math.round(sheet.getColumnWidthInPixels(c));
   tableHTML.append("<COL width=\"" + columnWidthPx + "\"/>");
  }
  tableHTML.append("</COLGROUP>");

  for (int r = 0; r <= sheet.getLastRowNum(); r++) {
   row = sheet.getRow(r); if (row == null) row = sheet.createRow(r);
   long rowHeightPx = Math.round(row.getHeightInPoints() * 92f / 72f);
   tableHTML.append("<TR height=\"" + rowHeightPx + "\">");
   int c = 0;
   while(c < lastColumnToExport) {
    tableHTML.append("<TD");
    cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
    cellValue = dataFormatter.formatCellValue(cell);
    double cellValueWidth = SheetUtil.getCellWidth(cell, defaultCharWidth, dataFormatter, false);
    int neededColunmnWidth = (int)cellValueWidth*256;
    int columnWidth = sheet.getColumnWidth(c);
    if (columnWidth < neededColunmnWidth) {
     int colSpan = 1;
     while(columnWidth < neededColunmnWidth) {
      colSpan++;
      c++;
      columnWidth += sheet.getColumnWidth(c);
     }
     tableHTML.append(" colspan=\"" + colSpan + "\""  + ">" + cellValue);
     c++;
    } else {
     tableHTML.append(">" + cellValue);
     c++;
    }
    tableHTML.append("</TD>");
   }
   tableHTML.append("</TR>");
  }

  tableHTML.append("</TABLE>");

  workbook.close();

System.out.println(tableHTML.toString());

  //creating a sample HTML file
  String encoding = "UTF-8";
  FileOutputStream fos = new FileOutputStream("result.html");
  OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
  writer.write("<!DOCTYPE html>\n");
  writer.write("<html lang=\"en\">");
  writer.write("<head>");
  writer.write("<meta charset=\"utf-8\"/>");
  writer.write("<style>");
  writer.write("table {border-collapse: collapse; table-layout: fixed;}");
  writer.write("table, tr, td {border: 1px solid black;}");
  writer.write("td {font: 11pt Calibri, arial, sans-serif;}");
  writer.write("</style>");
  writer.write("</head>");
  writer.write("<body>");

  writer.write(tableHTML.toString());

  writer.write("</body>");
  writer.write("</html>");
  writer.close();

  java.awt.Desktop.getDesktop().browse(new File("result.html").toURI());

 }
}
</code>```

Result:

Body:
Apache poi is able autosize the columns according to their contents. So it needs to be able calculating what column width a special content would need. This is what SheetUtil.getCellWidth is doing.

Additionally one needs to know the very special measurement units Microsoft has introduced for column widths in Excel. In Excels GUI a column width of 10 for example means that 10 characters of default character width fits into the cell width. But internally the width is calculated in units of 1/256th of a default character width. That's why apache poi decided to get Sheet.getColumnWidth in units of 1/256th of a character width.

So if you have got a Cell cell having cell index c and having a special content, then using

Workbook workbook...
...
DataFormatter dataFormatter = new DataFormatter();
...
int defaultCharWidth = SheetUtil.getDefaultCharWidth(workbook);
...
double cellValueWidth = SheetUtil.getCellWidth(cell, defaultCharWidth, dataFormatter, false);
int neededColunmnWidth = (int)cellValueWidth*256;
int columnWidth = sheet.getColumnWidth(c);
...

you could determine whether the content fits into the cell. It fits if columnWidth >= neededColunmnWidth, else it fits not and colspan must be used.

Lets have a complete example to show the principle:

Sheet:

Code:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.SheetUtil;

import java.io.*;

class ExcelToHTMLColspan {

 public static void main(String[] args) throws Exception{

  Workbook workbook = WorkbookFactory.create(new FileInputStream("Test.xlsx"));

  DataFormatter dataFormatter = new DataFormatter();

  int defaultCharWidth = SheetUtil.getDefaultCharWidth(workbook);

  int lastColumnToExport = 5; // column E

  Sheet sheet = workbook.getSheetAt(0);

  Row row;
  Cell cell;
  String cellValue;

  StringBuilder tableHTML = new StringBuilder();

  tableHTML.append("<TABLE>");
  tableHTML.append("<COLGROUP>");
  for (int c = 0; c < lastColumnToExport; c++) {
   long columnWidthPx = Math.round(sheet.getColumnWidthInPixels(c));
   tableHTML.append("<COL width=\"" + columnWidthPx + "\"/>");
  }
  tableHTML.append("</COLGROUP>");

  for (int r = 0; r <= sheet.getLastRowNum(); r++) {
   row = sheet.getRow(r); if (row == null) row = sheet.createRow(r);
   long rowHeightPx = Math.round(row.getHeightInPoints() * 92f / 72f);
   tableHTML.append("<TR height=\"" + rowHeightPx + "\">");
   int c = 0;
   while(c < lastColumnToExport) {
    tableHTML.append("<TD");
    cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
    cellValue = dataFormatter.formatCellValue(cell);
    double cellValueWidth = SheetUtil.getCellWidth(cell, defaultCharWidth, dataFormatter, false);
    int neededColunmnWidth = (int)cellValueWidth*256;
    int columnWidth = sheet.getColumnWidth(c);
    if (columnWidth < neededColunmnWidth) {
     int colSpan = 1;
     while(columnWidth < neededColunmnWidth) {
      colSpan++;
      c++;
      columnWidth += sheet.getColumnWidth(c);
     }
     tableHTML.append(" colspan=\"" + colSpan + "\""  + ">" + cellValue);
     c++;
    } else {
     tableHTML.append(">" + cellValue);
     c++;
    }
    tableHTML.append("</TD>");
   }
   tableHTML.append("</TR>");
  }

  tableHTML.append("</TABLE>");

  workbook.close();

System.out.println(tableHTML.toString());

  //creating a sample HTML file
  String encoding = "UTF-8";
  FileOutputStream fos = new FileOutputStream("result.html");
  OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
  writer.write("<!DOCTYPE html>\n");
  writer.write("<html lang=\"en\">");
  writer.write("<head>");
  writer.write("<meta charset=\"utf-8\"/>");
  writer.write("<style>");
  writer.write("table {border-collapse: collapse; table-layout: fixed;}");
  writer.write("table, tr, td {border: 1px solid black;}");
  writer.write("td {font: 11pt Calibri, arial, sans-serif;}");
  writer.write("</style>");
  writer.write("</head>");
  writer.write("<body>");

  writer.write(tableHTML.toString());

  writer.write("</body>");
  writer.write("</html>");
  writer.close();

  java.awt.Desktop.getDesktop().browse(new File("result.html").toURI());

 }
}

Result:


问:
Executing 2 async functions sequentially with dependent outputs
I have a module of functions:

```<code>module.exports = {
         p3: async function(mongo_db,data, cb){
            mongo_db.collection('release', async function(err,coll){
                for(var i = 0; i <= data.searches.length-1; i++) {
                    var rlsId = data.searches[i].releaseId;
                    //console.log("RELEASE ID " + rlsId);
                    var tdcId = data.searches[i].tdcId;
                    if(rlsId !== null || rlsId !== undefined){
                        result = await  coll.findOne({"_id":ObjectId(rlsId)});
                        if(result){
                            //console.log("this is data searches for index " + i+ " " + JSON.stringify(data.searches[i])
                            //      + " and data.searches " + JSON.stringify(data.searches) + " and this is result " + JSON.stringify(result));
                            data.searches[i].releaseId = "release::" + result.initiativeId + "::" + result.name;
                            data.searches[i].tdcId = "testdachar::" +  tdcId;
                            var reservLst = data.searches[i].reservationIds;

                        }
                    }
                }
                if(err){
                    return cb(err)
                }
                return cb(null,data)
                //data_cb(data);
                //cb()
            })
            //return data
        },      p8: async function(mongo_db, data, cb){
            mongo_db.collection('reservation',async function(err,coll){
                for (var i =0 ; i< data.searches.length; i++){

                    if(data.searches[i].reservationIds){
                        var reservLst = data.searches[i].reservationIds;
                        for (var j=0; j<reservLst.length; j++){
                            var reservDoc = await  coll.findOne({"_id":ObjectId(reservLst[j])});
                            if(reservDoc){
                                data.searches[i].reservationIds[j] = "cardreserve::" + reservDoc.accountId;
                            }
                        }
                    }
                }
                if(err){
                    return cb(err);
                }
                return cb(null,data);
                //data_cb(data)
            })
        },

}
</code>```

I am trying to execute p3 and p8 sequentially as the data output of one is passed onto the other. I am trying to use async.waterfall for this, but am having some difficulty coming up with the correct syntax. Can you please help?

答:
Since the chances to get to the callback hell are quite low, it could be as simple as</p>

```<code>p3(db, data, function(err, result){

    // do something with error or result

    p8(db, data, function(err, result){

        // do something with error or result

    });

});
</code>```

Body:
I have a module of functions:

module.exports = {
         p3: async function(mongo_db,data, cb){
            mongo_db.collection('release', async function(err,coll){
                for(var i = 0; i <= data.searches.length-1; i++) {
                    var rlsId = data.searches[i].releaseId;
                    //console.log("RELEASE ID " + rlsId);
                    var tdcId = data.searches[i].tdcId;
                    if(rlsId !== null || rlsId !== undefined){
                        result = await  coll.findOne({"_id":ObjectId(rlsId)});
                        if(result){
                            //console.log("this is data searches for index " + i+ " " + JSON.stringify(data.searches[i])
                            //      + " and data.searches " + JSON.stringify(data.searches) + " and this is result " + JSON.stringify(result));
                            data.searches[i].releaseId = "release::" + result.initiativeId + "::" + result.name;
                            data.searches[i].tdcId = "testdachar::" +  tdcId;
                            var reservLst = data.searches[i].reservationIds;

                        }
                    }
                }
                if(err){
                    return cb(err)
                }
                return cb(null,data)
                //data_cb(data);
                //cb()
            })
            //return data
        },      p8: async function(mongo_db, data, cb){
            mongo_db.collection('reservation',async function(err,coll){
                for (var i =0 ; i< data.searches.length; i++){

                    if(data.searches[i].reservationIds){
                        var reservLst = data.searches[i].reservationIds;
                        for (var j=0; j<reservLst.length; j++){
                            var reservDoc = await  coll.findOne({"_id":ObjectId(reservLst[j])});
                            if(reservDoc){
                                data.searches[i].reservationIds[j] = "cardreserve::" + reservDoc.accountId;
                            }
                        }
                    }
                }
                if(err){
                    return cb(err);
                }
                return cb(null,data);
                //data_cb(data)
            })
        },

}

I am trying to execute p3 and p8 sequentially as the data output of one is passed onto the other. I am trying to use async.waterfall for this, but am having some difficulty coming up with the correct syntax. Can you please help?

Body:
Since the chances to get to the callback hell are quite low, it could be as simple as

p3(db, data, function(err, result){

    // do something with error or result

    p8(db, data, function(err, result){

        // do something with error or result

    });

});


问:
How to get position from GoogleMapsEvent.MAP_CLICK?
I create an application and I using google maps native, and I want to get position from on click method:

```<code>map.on(GoogleMapsEvent.MAP_CLICK).subscribe(e => {

});
</code>```

How can I get lat and lng from this function?
please help me, Thanks.

My onClick method:

```<code>    map.on(GoogleMapsEvent.MAP_CLICK).subscribe(e => {

    // var latit = '' + e;

    // const latnum = latit.substring(latit.indexOf(' ') + 1, latit.indexOf(','));

    // const lngnum = latit.substring(latit.lastIndexOf(' ') + 1, latit.length - 1);

    console.log(e.latLng.lat());

    const coordinates: LatLng = new LatLng(e.latLng.lat(), e.latLng.lng());

    const position = {
        target: coordinates,
        zoom: 16
    };

    const markerOptions: MarkerOptions = {
        position: coordinates,
        title: 'موقعیت شما'
    };

    const marker = map.addMarker(markerOptions)
        .then((marker: Marker) => {
          marker.showInfoWindow();
      });
    map.animateCamera(position);
    });
  }
</code>```

答:
assuming your event is the e object  then  should be in e.latLng

```<code>    my_lat =  e.latLng.lat();
    my_lng =  e.latLng.lng();

    alert("Lat ' + my_lat );
    alert("Lat ' + my_lng );
</code>```

Body:
I create an application and I using google maps native, and I want to get position from on click method:

map.on(GoogleMapsEvent.MAP_CLICK).subscribe(e => {

});

How can I get lat and lng from this function?
please help me, Thanks.

My onClick method:

    map.on(GoogleMapsEvent.MAP_CLICK).subscribe(e => {

    // var latit = '' + e;

    // const latnum = latit.substring(latit.indexOf(' ') + 1, latit.indexOf(','));

    // const lngnum = latit.substring(latit.lastIndexOf(' ') + 1, latit.length - 1);

    console.log(e.latLng.lat());

    const coordinates: LatLng = new LatLng(e.latLng.lat(), e.latLng.lng());

    const position = {
        target: coordinates,
        zoom: 16
    };

    const markerOptions: MarkerOptions = {
        position: coordinates,
        title: 'موقعیت شما'
    };

    const marker = map.addMarker(markerOptions)
        .then((marker: Marker) => {
          marker.showInfoWindow();
      });
    map.animateCamera(position);
    });
  }

Body:
assuming your event is the e object  then  should be in e.latLng

    my_lat =  e.latLng.lat();
    my_lng =  e.latLng.lng();

    alert("Lat ' + my_lat );
    alert("Lat ' + my_lng );


问:
How to insert a random string into the sed 's//' replace string for each line actioned?
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

```<code>$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590
</code>```

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

答:
No, it is impossible to do this with sed only as sed has no capability to generate random numbers. It's not even sed that's doing it in your posted example, it's the shell generating a random number before sed is called. All sed sees is "s|.*|21590|".

If you want to do this using standard tools in any shell on any UNIX box then you can do this with any awk:

```<code>$ echo "    " | tr ' ' '\n' | awk '{sub(/.*/,rand())}1'
0.924046
0.593909
0.306394
0.578941
0.740133
</code>```

See https://www.gnu.org/software/gawk/manual/gawk.html#Numeric-Functions for more info on rand() and I can provide C&V if you're interested in pursuing an awk solution.

One way to address your comment below:

```<code>$ seq 5 | awk -v seed="$RANDOM" 'BEGIN{srand(seed)} {print rand()}'
0.0873814
0.536876
0.535788
0.881146
0.354652
</code>```

Body:
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

Body:
No, it is impossible to do this with sed only as sed has no capability to generate random numbers. It's not even sed that's doing it in your posted example, it's the shell generating a random number before sed is called. All sed sees is "s|.*|21590|".

If you want to do this using standard tools in any shell on any UNIX box then you can do this with any awk:

$ echo "    " | tr ' ' '\n' | awk '{sub(/.*/,rand())}1'
0.924046
0.593909
0.306394
0.578941
0.740133

See https://www.gnu.org/software/gawk/manual/gawk.html#Numeric-Functions for more info on rand() and I can provide C&V if you're interested in pursuing an awk solution.

One way to address your comment below:

$ seq 5 | awk -v seed="$RANDOM" 'BEGIN{srand(seed)} {print rand()}'
0.0873814
0.536876
0.535788
0.881146
0.354652


问:
Add Event Method Is Adding Cell To Top, Not Bottom
I have the following method which is adding a cell to a tableview.  I want the added cell to be at the bottom, however right now it is adding it at the top.  Any suggestions?

addEvent method:

```<code>-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
     }
</code>```

ViewDidLoad

```<code>- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}
</code>```

答:
0 is the first index. As a rule (there are likely to be a few exceptions somewhere in the world) things that are to do with indexes, start at 0. Whereas things like count start at 1.

So if you have an array with 1 object in it, the array's count will be 1, and the object will be at index 0.

When you are using 0, for you indexPath's row and section your telling it to put it at the top of the tableview.

So make you last 4 lines of code something like this:

```<code>[eventsArray addObject:routine];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

[self.routineTableView reloadData];

NSInteger lastSection = [self.routineTableView numberOfSections] -1;

[self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.routineTableView numberOfRowsInSection:lastSection]-1 inSection:lastSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
</code>```

Body:
I have the following method which is adding a cell to a tableview.  I want the added cell to be at the bottom, however right now it is adding it at the top.  Any suggestions?

addEvent method:

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
     }

ViewDidLoad

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

Body:
0 is the first index. As a rule (there are likely to be a few exceptions somewhere in the world) things that are to do with indexes, start at 0. Whereas things like count start at 1.

So if you have an array with 1 object in it, the array's count will be 1, and the object will be at index 0.

When you are using 0, for you indexPath's row and section your telling it to put it at the top of the tableview.

So make you last 4 lines of code something like this:

[eventsArray addObject:routine];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

[self.routineTableView reloadData];

NSInteger lastSection = [self.routineTableView numberOfSections] -1;

[self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.routineTableView numberOfRowsInSection:lastSection]-1 inSection:lastSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];


问:
How to restore all nuget packages in a solution?
I have a solution with 12 projects. The idea is to avoid all dependencies issues and whoever downloads the latest solution from TFS would just run one command at the solution level which would install all the packages in all the 12 projects.

I have the packages.config file in individual projects and I run the following command to install it at project level

nuget install pathtoproject\packages.config

this works and it installs all the required references from packges.config. But I will have to execute this command 12 times for 12 projects. Is there one command at the solution level  which would install all packages.config?

I tried
 nuget.exe restore solutionname

and nothing happened. Thanks for any pointers.

答:
too late to reply, in case someone lands here..

"All packages listed in packages.config' are already installed"

if you see this message then i think the packages are actually restored, probably visual studio not showing it in the solution explorer view. A simple refresh did the trick for us.