问:
Understanding Eloquent One-to-many Relationships
I'm trying to understand Eloquent relationships but it seems I'm missing something in understanding it. I have:

A Meeting produces many Documents.

A specific Document can be produced for one Meeting.

Thus a one to many relationship.  I am trying to display the 'meeting_name' in the Document details table but get this error:

Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)

Here is my code.

Please please explain with code solution:

app\Document.php File:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{
    protected $fillable = [
        'document_name',
        'document_desc',
    ];

    public function meeting(){
        return $this->belongsTo(Meeting::class);
    }
}
</code>```

app\Meeting.php File:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Meeting extends Model
{
    protected $fillable = [
        'document_id',
        'meeting_name',
        'meeting_desc',
        'room_no',
        'no_of_invitees',
        'comments'
    ];

    public function documents(){
        return $this->hasMany(Document::class);
    }
}
</code>```

app\Http\Controllers\DocumentsController.php File:

```<code>namespace App\Http\Controllers;

use App\Document;
use App\Meeting;
use Illuminate\Http\Request;

class DocumentsController extends Controller
{
    public function index()
    {
        $documents =  Document::all();
        $meetings = Meeting::all();

        return view('documents.index', compact('documents', 'meetings'));
    }
}
</code>```

resources\views\documents\index.blade.php File:

```<code>@foreach($documents as $document)
    <tr>
        <td>{{$document->id}}</td>
        <td>{{$document->document_name}}</td>
        <td>{{$document->document_desc}}</td>
        <td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
    </tr>
@endforeach
</code>```

答:
you have many problems in your code:

first: in order to use the relation ... you have to load it first ...

loading relation done by using with('relationName') method ...

in index:

```<code>$documents =  Document::with('meeting')->all();
</code>```

second:

```<code> <td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
</code>```

the relation is named meeting without s .. not meetings ...

third:

it's pest practices to provide foreign key in relation:

in Meeting model

```<code>  public function documents(){
        return $this->hasMany(Document::class,'meeting_id');
    }
</code>```

in Document model:

```<code> public function meeting(){
        return $this->belongsTo(Meeting::class,'meeting_id');
    }
</code>```

please make sure you have a column meeting_id in your documents table referenced as foreign key to id in meetings table

more details about loading relation in:

https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

Body:
I'm trying to understand Eloquent relationships but it seems I'm missing something in understanding it. I have:

A Meeting produces many Documents.

A specific Document can be produced for one Meeting.

Thus a one to many relationship.  I am trying to display the 'meeting_name' in the Document details table but get this error:

Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)

Here is my code.

Please please explain with code solution:

app\Document.php File:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{
    protected $fillable = [
        'document_name',
        'document_desc',
    ];

    public function meeting(){
        return $this->belongsTo(Meeting::class);
    }
}

app\Meeting.php File:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Meeting extends Model
{
    protected $fillable = [
        'document_id',
        'meeting_name',
        'meeting_desc',
        'room_no',
        'no_of_invitees',
        'comments'
    ];

    public function documents(){
        return $this->hasMany(Document::class);
    }
}

app\Http\Controllers\DocumentsController.php File:

namespace App\Http\Controllers;

use App\Document;
use App\Meeting;
use Illuminate\Http\Request;

class DocumentsController extends Controller
{
    public function index()
    {
        $documents =  Document::all();
        $meetings = Meeting::all();

        return view('documents.index', compact('documents', 'meetings'));
    }
}

resources\views\documents\index.blade.php File:

@foreach($documents as $document)

        {{$document->id}}
        {{$document->document_name}}
        {{$document->document_desc}}
        {{$document->meetings->meeting_name}}

@endforeach

Body:
you have many problems in your code:

first: in order to use the relation ... you have to load it first ...

loading relation done by using with('relationName') method ...

in index:

$documents =  Document::with('meeting')->all();

second:

 <td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->

the relation is named meeting without s .. not meetings ...

third:

it's pest practices to provide foreign key in relation:

in Meeting model

  public function documents(){
        return $this->hasMany(Document::class,'meeting_id');
    }

in Document model:

 public function meeting(){
        return $this->belongsTo(Meeting::class,'meeting_id');
    }

please make sure you have a column meeting_id in your documents table referenced as foreign key to id in meetings table

more details about loading relation in:

https://laravel.com/docs/7.x/eloquent-relationships#eager-loading


来源: stackexchange

问:
AddTrust external ca root is expired
We are running healthchecks scripts from our aws servers, these health check scripts call apis written in various langauages and based on result decides whether applications are running fine or not, from 30 May 2020, My healthchecks are failing stating ssl certificate expired. One of the possible reason would be https://www.ssl.com/faqs/i-noticed-that-the-addtrust-external-ca-root-is-expiring-soon-will-i-be-affected/can anyone suggest what action I need to take. We are running amazon linux2 os.</p>

答:
Try using this tool against your server: https://whatsmychaincert.com/

If you have the expired root certificate, your most likely solution will be to change your bundle of intermediate and root certificates to simply OMIT the expired root.

ContentLicense: CC BY-SA 4.0

Title: AddTrust external ca root is expired


问:
CoordinatorLayout and AppBarLayout elevation
I've created an AppBar layout like this

```<code><android.support.design.widget.AppBarLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/appbar_layout"
    android:layout_height="@dimen/app_bar_height"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:elevation="20dp">

    <android.support.design.widget.CollapsingToolbarLayout...>
</android.support.design.widget.AppBarLayout>
</code>```

it works and casts a shadow in the LinearLayout:

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/app_bar_large" />
</LinearLayout>
</code>```

However when I put it into the CoordinatorLayout shadow is gone:

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/app_bar_large" />
</android.support.design.widget.CoordinatorLayout>
</code>```

How can I make appbar to show its shadow again?

答:
setTargetElevation() is now deprecated for AppBarLayout.

The new correct implementation for applying custom elevation to an AppBarLayout based on the state of the layout is to use a StateListAnimator.
material-components uses this as you can see here

I've added an example implementation of always showing AppBarLayout elevation here in this gist.

All you need is to 1. create a custom state list animator under /res/animator and 2. set the AppBarLayout's StateListAnimator like so:

```<code>appBarLayout.stateListAnimator = AnimatorInflater.loadStateListAnimator(context, R.animator.appbar_always_elevated_state_list_animator)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've created an AppBar layout like this

<android.support.design.widget.AppBarLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/appbar_layout"
    android:layout_height="@dimen/app_bar_height"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:elevation="20dp">

    <android.support.design.widget.CollapsingToolbarLayout...>
</android.support.design.widget.AppBarLayout>

it works and casts a shadow in the LinearLayout:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/app_bar_large" />
</LinearLayout>

However when I put it into the CoordinatorLayout shadow is gone:

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/app_bar_large" />
</android.support.design.widget.CoordinatorLayout>

How can I make appbar to show its shadow again?

Body:
setTargetElevation() is now deprecated for AppBarLayout.

The new correct implementation for applying custom elevation to an AppBarLayout based on the state of the layout is to use a StateListAnimator.
material-components uses this as you can see here

I've added an example implementation of always showing AppBarLayout elevation here in this gist.

All you need is to 1. create a custom state list animator under /res/animator and 2. set the AppBarLayout's StateListAnimator like so:

appBarLayout.stateListAnimator = AnimatorInflater.loadStateListAnimator(context, R.animator.appbar_always_elevated_state_list_animator)


问:
Search/replace in Kusto
Use case: Remove a string from Azure Application Insights results

This is a simple question but with minimal examples online and as a new user, and with limited experience (but learning) in Regex, I am struggling.

How do I remove all instances of | Articles in the following table, which is an example of what I am exporting from Azure Application Insights?

This did not work:

```<code>| extend name=replace(@' | Articles', @'', name)
</code>```

I have fiddled quite a bit unsuccessfully with an example in Microsoft's documentation (I know this interpretation is incorrect):

```<code>| extend str=strcat(' | Articles', tostring(name))
| extend replaced=replace(@' | Articles', @'', str)
</code>```

Thank you for any insights.

答:
the reason your initial attempt doesn't work is that the first argument to replace() is a regular expression, and if you have the pipe (|) in is, you'll need to properly escape it, using a backslash (\).

for example:

```<code>datatable(s:string)
[
    "Article 1 | Articles",
    "Article 2",
    "Article 3 | Articles"
]
| extend replaced=replace(@' \| Articles', @'', s)
</code>```

ideally, you'll choose a solution that doesn't require using a regular expression, if possible.

for example:

```<code>datatable(s:string)
[
    "Article 1 | Articles",
    "Article 2",
    "Article 3 | Articles"
]
| extend i = indexof(s, " | Articles")
| project s = case(i == -1, s, substring(s, 0, i))
</code>```

Title: Search/replace in Kusto

Body:
Use case: Remove a string from Azure Application Insights results

This is a simple question but with minimal examples online and as a new user, and with limited experience (but learning) in Regex, I am struggling.

How do I remove all instances of | Articles in the following table, which is an example of what I am exporting from Azure Application Insights?

This did not work:

| extend name=replace(@' | Articles', @'', name)

I have fiddled quite a bit unsuccessfully with an example in Microsoft's documentation (I know this interpretation is incorrect):

| extend str=strcat(' | Articles', tostring(name))
| extend replaced=replace(@' | Articles', @'', str)

Thank you for any insights.

Body:
the reason your initial attempt doesn't work is that the first argument to replace() is a regular expression, and if you have the pipe (|) in is, you'll need to properly escape it, using a backslash (\).

for example:

datatable(s:string)
[
    "Article 1 | Articles",
    "Article 2",
    "Article 3 | Articles"
]
| extend replaced=replace(@' \| Articles', @'', s)

ideally, you'll choose a solution that doesn't require using a regular expression, if possible.

for example:

datatable(s:string)
[
    "Article 1 | Articles",
    "Article 2",
    "Article 3 | Articles"
]
| extend i = indexof(s, " | Articles")
| project s = case(i == -1, s, substring(s, 0, i))


问:
How can I format the value shown in a Rails edit field?
I would like to make editing form fields as user-friendly as possible. For example, for numeric values, I would like the field to be displayed with commas (like number_with_precision).

This is easy enough on the display side, but what about editing? Is there a good way to do this?

I am using the Rails FormBuilder. Upon investigation, I found that it uses InstanceTag, which gets the values for fields by using <attribute>_value_before_type_cast which means overriding <attribute> won't get called.

答:
You can use the number_format plugin.  By specifying a number_format for an existing numeric attribute inside your model, the attribute will now appear as formatted to Rails in all forms and views.  It will also be parsed back from that format (when assigned via forms) prior to insertion into the database.  (The plugin also creates purely numeric unformatted_<attribute-name> accessors which can continue to be used for arithmetic, or for direct numerical assignment or retrieval by you for seamless integration.)

```<code>class MyModel < ActiveRecord::Base
  # this model has the balance attribute, which we
  #  want to display using formatting in views,
  #  although it is stored as a numeric in the database
  number_format :balance,
                :precision => 2,
                :delimiter => ',',
                :strip_trailing_zeros => false

  def increment_balance
    unformatted_balance += 10
  end
</code>```

You can also combine the above with a Javascript solution, which can force the user to maintain the decimal point and thousands separators in place while editing, although this is really not necessary.

OwnerDisplayName: Luke Francl

ContentLicense: CC BY-SA 2.5

Body:
You can use the number_format plugin.  By specifying a number_format for an existing numeric attribute inside your model, the attribute will now appear as formatted to Rails in all forms and views.  It will also be parsed back from that format (when assigned via forms) prior to insertion into the database.  (The plugin also creates purely numeric unformatted_<attribute-name> accessors which can continue to be used for arithmetic, or for direct numerical assignment or retrieval by you for seamless integration.)

class MyModel < ActiveRecord::Base
  # this model has the balance attribute, which we
  #  want to display using formatting in views,
  #  although it is stored as a numeric in the database
  number_format :balance,
                :precision => 2,
                :delimiter => ',',
                :strip_trailing_zeros => false

  def increment_balance
    unformatted_balance += 10
  end

You can also combine the above with a Javascript solution, which can force the user to maintain the decimal point and thousands separators in place while editing, although this is really not necessary.

OwnerDisplayName: Vlad Romascanu

LastEditorDisplayName: Vlad Romascanu


问:
Could not execute JDBC batch update
When i am going to save multiple record at that time i am getting this error. so Please give me a solution of this error.</p>

```<code>6/2/11 5:06:13 PM (S) ActionListenerImpl.processAction : javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:387)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:324)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:299)
    at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:256)
    at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:469)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83)
    at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:56)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:662)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:307)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at org.hibernate.search.jpa.impl.FullTextEntityManagerImpl.flush(FullTextEntityManagerImpl.java:113)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at icici.waiver.controller.imp.LimitMasterController.createLimitRecord(LimitMasterController.java:256)
    at icici.waiver.framework.LimitHome.persist(LimitHome.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
    at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56)
    at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.transaction.TransactionInterceptor$1.work(TransactionInterceptor.java:97)
    at org.jboss.seam.util.Work.workInTransaction(Work.java:47)
    at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
    at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185)
    at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103)
    at icici.waiver.framework.LimitHome_$$_javassist_seam_7.persist(LimitHome_$$_javassist_seam_7.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348)
    at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
    at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
    at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 45 more
Caused by: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:100)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:304)
    ... 82 more
Caused by: java.sql.BatchUpdateException: ORA-01438: value larger than specified precision allowed for this column

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:602)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:9350)
    at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:210)
    at org.enhydra.jdbc.core.CorePreparedStatement.executeBatch(CorePreparedStatement.java:410)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
    ... 88 more
6/2/11 5:06:13 PM (W) InvokeApplicationPhase.execute : #{limitHome.persist}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
javax.faces.FacesException: #{limitHome.persist}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:387)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:324)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:299)
    at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:256)
    at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:469)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83)
    at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:56)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:662)
Caused by: javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 44 more
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:307)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at org.hibernate.search.jpa.impl.FullTextEntityManagerImpl.flush(FullTextEntityManagerImpl.java:113)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at icici.waiver.controller.imp.LimitMasterController.createLimitRecord(LimitMasterController.java:256)
    at icici.waiver.framework.LimitHome.persist(LimitHome.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
    at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56)
    at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.transaction.TransactionInterceptor$1.work(TransactionInterceptor.java:97)
    at org.jboss.seam.util.Work.workInTransaction(Work.java:47)
    at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
    at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185)
    at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103)
    at icici.waiver.framework.LimitHome_$$_javassist_seam_7.persist(LimitHome_$$_javassist_seam_7.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348)
    at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
    at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
    at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 45 more
Caused by: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:100)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:304)
    ... 82 more
Caused by: java.sql.BatchUpdateException: ORA-01438: value larger than specified precision allowed for this column

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:602)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:9350)
    at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:210)
    at org.enhydra.jdbc.core.CorePreparedStatement.executeBatch(CorePreparedStatement.java:410)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
</code>```

答:
```<code>value larger than specified precision allowed for this column
</code>```

Something like a String is too long for the column - eg "XXXXXX" saved into varchar(4) or a decimal with too many places, eg 1234.5678 saved into decimal(4,2) etc

EDITED: It could also be a java.util.Date (which has a time component) saved into a DATE column (which has no time component) depending on how you're talking to the db.

Title: Could not execute JDBC batch update

Body:
When i am going to save multiple record at that time i am getting this error. so Please give me a solution of this error.

6/2/11 5:06:13 PM (S) ActionListenerImpl.processAction : javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:387)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:324)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:299)
    at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:256)
    at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:469)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83)
    at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:56)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:662)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:307)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at org.hibernate.search.jpa.impl.FullTextEntityManagerImpl.flush(FullTextEntityManagerImpl.java:113)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at icici.waiver.controller.imp.LimitMasterController.createLimitRecord(LimitMasterController.java:256)
    at icici.waiver.framework.LimitHome.persist(LimitHome.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
    at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56)
    at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.transaction.TransactionInterceptor$1.work(TransactionInterceptor.java:97)
    at org.jboss.seam.util.Work.workInTransaction(Work.java:47)
    at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
    at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185)
    at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103)
    at icici.waiver.framework.LimitHome_$$_javassist_seam_7.persist(LimitHome_$$_javassist_seam_7.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348)
    at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
    at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
    at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 45 more
Caused by: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:100)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:304)
    ... 82 more
Caused by: java.sql.BatchUpdateException: ORA-01438: value larger than specified precision allowed for this column

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:602)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:9350)
    at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:210)
    at org.enhydra.jdbc.core.CorePreparedStatement.executeBatch(CorePreparedStatement.java:410)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
    ... 88 more
6/2/11 5:06:13 PM (W) InvokeApplicationPhase.execute : #{limitHome.persist}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
javax.faces.FacesException: #{limitHome.persist}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:387)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:324)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:299)
    at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:256)
    at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:469)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83)
    at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:56)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53)
    at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
    at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:662)
Caused by: javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 44 more
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:307)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at org.hibernate.search.jpa.impl.FullTextEntityManagerImpl.flush(FullTextEntityManagerImpl.java:113)
    at org.jboss.seam.persistence.EntityManagerProxy.flush(EntityManagerProxy.java:92)
    at icici.waiver.controller.imp.LimitMasterController.createLimitRecord(LimitMasterController.java:256)
    at icici.waiver.framework.LimitHome.persist(LimitHome.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
    at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56)
    at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.transaction.TransactionInterceptor$1.work(TransactionInterceptor.java:97)
    at org.jboss.seam.util.Work.workInTransaction(Work.java:47)
    at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
    at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185)
    at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103)
    at icici.waiver.framework.LimitHome_$$_javassist_seam_7.persist(LimitHome_$$_javassist_seam_7.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335)
    at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348)
    at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
    at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
    at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 45 more
Caused by: org.hibernate.exception.DataException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:100)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:304)
    ... 82 more
Caused by: java.sql.BatchUpdateException: ORA-01438: value larger than specified precision allowed for this column

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:602)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:9350)
    at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:210)
    at org.enhydra.jdbc.core.CorePreparedStatement.executeBatch(CorePreparedStatement.java:410)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)

Body:
value larger than specified precision allowed for this column

Something like a String is too long for the column - eg "XXXXXX" saved into varchar(4) or a decimal with too many places, eg 1234.5678 saved into decimal(4,2) etc

EDITED: It could also be a java.util.Date (which has a time component) saved into a DATE column (which has no time component) depending on how you're talking to the db.


问:
Error when trying to pass a variable to a second view
In the following code I have a struct that has different values.

```<code>struct Workout: Codable {
let exercise: [Exercise]

enum CodingKeys: String, CodingKey {
    case exercise = "exercise"
 }
}

struct Exercise: Codable {
   let exercise, set: Int
}

class WorkoutViewModel: ObservableObject {
    @Published var workout: Workout
   init(_ workout: Workout) {
     self.workout = workout
   }
}
</code>```

In my main view I call initialise the value as this:

```<code>struct CreateWorkoutView: View {
    @ObservedObject var myExercises = WorkoutViewModel(Workout(exercise: [Exercise(exercise: 1, set: 1)]))

var body: some View {
        NavigationView {
    NavigationLink(
        destination: View2(exerciseList: self.$myExercises.workout.exercise)
    ){
        Text("Add Exercises")
    }
}

struct View2: View {
    @ObservedObject var excersices = getExercisesData()
    @Binding var exerciseList: [Exercise]

    var body: some View {
        VStack {
            List(excersices.datas){i in
                HStack{
                    VStack(alignment: .leading){
                        Text(i.name)
                    }
                    Spacer()
                    VStack(alignment: .leading){
                        Image(systemName: "info.circle")
                    }

                }.onTapGesture {
                    self.exerciseList.append(Exercise(exercise: i.exerciseId, set: 1))
                }
            }
        }

    }
}
</code>```

There is a problem with the line where I set self.$myExercises.workout.exercise. The XCode error shows a different location (a HStack) and gives the following error as it seems unrelated:
Generic parameter 'C0' could not be inferred Info: 1. In call to function 'buildBlock' (SwiftUI.ViewBuilder)

I want to move this the exercise array to the next view to add items to it.

any idea why the above part of the cone is not allowed?

Thanks

答:
The error message was unrelated. The problem was that the let exercise, set: Int was a constant and not a var. changing that solved the issue.
Commenting the part the error raised sometimes help to understand what the compiler  is really complaining about.

Body:
In the following code I have a struct that has different values.

struct Workout: Codable {
let exercise: [Exercise]

enum CodingKeys: String, CodingKey {
    case exercise = "exercise"
 }
}

struct Exercise: Codable {
   let exercise, set: Int
}

class WorkoutViewModel: ObservableObject {
    @Published var workout: Workout
   init(_ workout: Workout) {
     self.workout = workout
   }
}

In my main view I call initialise the value as this:

struct CreateWorkoutView: View {
    @ObservedObject var myExercises = WorkoutViewModel(Workout(exercise: [Exercise(exercise: 1, set: 1)]))

var body: some View {
        NavigationView {
    NavigationLink(
        destination: View2(exerciseList: self.$myExercises.workout.exercise)
    ){
        Text("Add Exercises")
    }
}

struct View2: View {
    @ObservedObject var excersices = getExercisesData()
    @Binding var exerciseList: [Exercise]

    var body: some View {
        VStack {
            List(excersices.datas){i in
                HStack{
                    VStack(alignment: .leading){
                        Text(i.name)
                    }
                    Spacer()
                    VStack(alignment: .leading){
                        Image(systemName: "info.circle")
                    }

                }.onTapGesture {
                    self.exerciseList.append(Exercise(exercise: i.exerciseId, set: 1))
                }
            }
        }

    }
}

There is a problem with the line where I set self.$myExercises.workout.exercise. The XCode error shows a different location (a HStack) and gives the following error as it seems unrelated:
Generic parameter 'C0' could not be inferred Info: 1. In call to function 'buildBlock' (SwiftUI.ViewBuilder)

I want to move this the exercise array to the next view to add items to it.

any idea why the above part of the cone is not allowed?

Thanks


问:
parse a PEM certificate into JSON
I've got a PEM certificate and I'm using openssl to view its content. Is it possible to parse the output into a JSON format? Maybe there's a Java library or Bash script that can do this?

command: $ openssl x509 -in sample.cer -noout -text

output:

```<code>Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            af:69:46:11:10:bd:82:88
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=US, ST=Texas, L=Plano, O=2xoffice, OU=Architecture, CN=Joshua Davies/emailAddress=joshua.davies.tx@gmail.com
        Validity
            Not Before: May 21 21:49:10 2014 GMT
            Not After : Jun 20 21:49:10 2014 GMT
        Subject: C=US, ST=Texas, L=Plano, O=2xoffice, OU=Architecture, CN=Joshua Davies/emailAddress=joshua.davies.tx@gmail.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (512 bit)
                Modulus (512 bit):
                    00:b7:38:0d:e0:ab:37:18:a7:26:95:9d:9e:6f:a2:
                    69:b1:b9:ee:b3:7f:29:04:fb:f0:94:b3:d0:d5:55:
                    c0:d8:6b:14:7f:94:13:3c:d9:a2:61:bf:ba:3f:0a:
                    44:37:dc:18:b5:23:c7:ee:96:2d:7c:d8:92:04:48:
                    74:f8:c6:46:a5
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                1A:A5:C9:C8:36:EA:7D:FA:B4:DF:A4:9C:11:F9:C1:BE:78:C4:42:DD
            X509v3 Authority Key Identifier:
                keyid:1A:A5:C9:C8:36:EA:7D:FA:B4:DF:A4:9C:11:F9:C1:BE:78:C4:42:DD
                DirName:/C=US/ST=Texas/L=Plano/O=2xoffice/OU=Architecture/CN=Joshua Davies/emailAddress=joshua.davies.tx@gmail.com
                serial:AF:69:46:11:10:BD:82:88

            X509v3 Basic Constraints:
                CA:TRUE
    Signature Algorithm: sha1WithRSAEncryption
        56:32:44:76:86:8c:08:92:74:71:0e:ac:a6:7d:ba:1d:7c:d3:
        b6:74:ef:27:7a:5e:53:21:fc:8e:eb:26:58:e0:6e:4f:5c:01:
        f1:40:ca:0a:e9:d2:0e:00:60:ae:1f:f6:a5:a4:4c:47:fb:e0:
        68:7f:25:63:ab:60:38:0f:74:94
</code>```

答:
Here is my own python script (derived from script above)

It can take pems with multiple certs as well.

```<code>#!/usr/bin/env python3

import os, sys
import tempfile
import json

import pem
import ssl

def main():
    cert_file_name = sys.argv[1]
    try:
        pems = pem.parse_file(cert_file_name)
    except Exception as e:
        print(f"Error decoding pem: {e}\n")
        sys.exit(1)

    res = []
    for p in pems:
        f = tempfile.NamedTemporaryFile(mode='w', delete=False)
        f.write(p.as_text())
        f.close()

        try:
            cert = ssl._ssl._test_decode_cert(f.name)
            # remap array mess in subject and issuer into dicts
            for item in ['subject', 'issuer']:
                if item in cert:
                    item_dict = {}
                    for s in cert[item]:
                        for i in s:
                            if i[0] not in item_dict:
                                item_dict[i[0]] = []
                            item_dict[i[0]].append(i[1])
                    # collapse single item arrays into scalars
                    for k,v in item_dict.items():
                        if len(v) == 1:
                            item_dict[k] = v[0]
                    cert[item] = item_dict
            # remap array mess in subjectAltName into a dict
            if 'subjectAltName' in cert:
                item = 'subjectAltName'
                san_dict = {}
                for i in cert[item]:
                    if i[0] not in san_dict:
                        san_dict[i[0]] = []
                    san_dict[i[0]].append(i[1])
                cert[item] = san_dict

            res.append(cert)
        except Exception as e:
            print(f"Error decoding certificate: {e}\n")

        os.unlink(f.name)

    print(json.dumps(res))

if __name__ == "__main__":
    main()
</code>```

Title: parse a PEM certificate into JSON

Body:
I've got a PEM certificate and I'm using openssl to view its content. Is it possible to parse the output into a JSON format? Maybe there's a Java library or Bash script that can do this?

command: $ openssl x509 -in sample.cer -noout -text

output:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            af:69:46:11:10:bd:82:88
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=US, ST=Texas, L=Plano, O=2xoffice, OU=Architecture, CN=Joshua Davies/emailAddress=joshua.davies.tx@gmail.com
        Validity
            Not Before: May 21 21:49:10 2014 GMT
            Not After : Jun 20 21:49:10 2014 GMT
        Subject: C=US, ST=Texas, L=Plano, O=2xoffice, OU=Architecture, CN=Joshua Davies/emailAddress=joshua.davies.tx@gmail.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (512 bit)
                Modulus (512 bit):
                    00:b7:38:0d:e0:ab:37:18:a7:26:95:9d:9e:6f:a2:
                    69:b1:b9:ee:b3:7f:29:04:fb:f0:94:b3:d0:d5:55:
                    c0:d8:6b:14:7f:94:13:3c:d9:a2:61:bf:ba:3f:0a:
                    44:37:dc:18:b5:23:c7:ee:96:2d:7c:d8:92:04:48:
                    74:f8:c6:46:a5
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                1A:A5:C9:C8:36:EA:7D:FA:B4:DF:A4:9C:11:F9:C1:BE:78:C4:42:DD
            X509v3 Authority Key Identifier:
                keyid:1A:A5:C9:C8:36:EA:7D:FA:B4:DF:A4:9C:11:F9:C1:BE:78:C4:42:DD
                DirName:/C=US/ST=Texas/L=Plano/O=2xoffice/OU=Architecture/CN=Joshua Davies/emailAddress=joshua.davies.tx@gmail.com
                serial:AF:69:46:11:10:BD:82:88

            X509v3 Basic Constraints:
                CA:TRUE
    Signature Algorithm: sha1WithRSAEncryption
        56:32:44:76:86:8c:08:92:74:71:0e:ac:a6:7d:ba:1d:7c:d3:
        b6:74:ef:27:7a:5e:53:21:fc:8e:eb:26:58:e0:6e:4f:5c:01:
        f1:40:ca:0a:e9:d2:0e:00:60:ae:1f:f6:a5:a4:4c:47:fb:e0:
        68:7f:25:63:ab:60:38:0f:74:94

Body:
Here is my own python script (derived from script above)

It can take pems with multiple certs as well.

#!/usr/bin/env python3

import os, sys
import tempfile
import json

import pem
import ssl

def main():
    cert_file_name = sys.argv[1]
    try:
        pems = pem.parse_file(cert_file_name)
    except Exception as e:
        print(f"Error decoding pem: {e}\n")
        sys.exit(1)

    res = []
    for p in pems:
        f = tempfile.NamedTemporaryFile(mode='w', delete=False)
        f.write(p.as_text())
        f.close()

        try:
            cert = ssl._ssl._test_decode_cert(f.name)
            # remap array mess in subject and issuer into dicts
            for item in ['subject', 'issuer']:
                if item in cert:
                    item_dict = {}
                    for s in cert[item]:
                        for i in s:
                            if i[0] not in item_dict:
                                item_dict[i[0]] = []
                            item_dict[i[0]].append(i[1])
                    # collapse single item arrays into scalars
                    for k,v in item_dict.items():
                        if len(v) == 1:
                            item_dict[k] = v[0]
                    cert[item] = item_dict
            # remap array mess in subjectAltName into a dict
            if 'subjectAltName' in cert:
                item = 'subjectAltName'
                san_dict = {}
                for i in cert[item]:
                    if i[0] not in san_dict:
                        san_dict[i[0]] = []
                    san_dict[i[0]].append(i[1])
                cert[item] = san_dict

            res.append(cert)
        except Exception as e:
            print(f"Error decoding certificate: {e}\n")

        os.unlink(f.name)

    print(json.dumps(res))

if __name__ == "__main__":
    main()


问:
How to remove an array from a json object with python?
This is the content of my json file:

```<code>{
  "tabID": [
    {
      "dat": [1, "q"],
      "opt": []
    }
  ]
}
</code>```

I'm building a python app that process that json file and I need to remove "opt":[].

I've tried next code:

```<code>data['tabID'][0].remove('data')
</code>```

But it doesn't work.

Could you give me any advice? Thanks.

答:
Make it a dict and pop the key.

Fixed an error in your JSON. Working example is at https://repl.it/repls/FrighteningPungentEquipment or as actual code:

import json

the_json_string = '{"tabID":[{"dat":[1, "q"],"opt":[] }]}'

obj = json.loads(the_json_string)
obj['tabID'][0].pop('opt')

print(json.dumps(obj))
```

Body:
This is the content of my json file:

{
  "tabID": [
    {
      "dat": [1, "q"],
      "opt": []
    }
  ]
}

I'm building a python app that process that json file and I need to remove "opt":[].

I've tried next code:

data['tabID'][0].remove('data')

But it doesn't work.

Could you give me any advice? Thanks.


问:
Trying to make an HP bar for a game using HTML/JavaScript
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}</code>```

      100hp

    Health
    Damage

```

Also, if anyone has any ideas to improve the design I'm all ears!

答:
it's better to use the object to control the limitation.</p>

```<code>  const healthObject = {
      _currentHelth: 100,
      getHealth: function () {
        return this._currentHelth
      },
      increase: function () {
        if (this._currentHelth < 100) {
          this._currentHelth++
        }
      },
      decrease: function () {
        if (this._currentHelth > 0) {
          this._currentHelth--
        }
      },
    }

    function add() {
      let addHealth = document.getElementById('health')
      healthObject.increase()
      if (addHealth) {
        addHealth.style.width = healthObject.getHealth() + '%'
        addHealth.innerHTML = healthObject.getHealth() + 'hp'
      }
    }

function remove() {
  let addHealth = document.getElementById('health')
  healthObject.decrease()
  if (addHealth) {
    addHealth.style.width = healthObject.getHealth() + '%'
    addHealth.innerHTML = healthObject.getHealth() + 'hp'
  }
}
</code>```

Body:
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}

.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

      100hp

    Health
    Damage

Also, if anyone has any ideas to improve the design I'm all ears!

Body:
it's better to use the object to control the limitation.

  const healthObject = {
      _currentHelth: 100,
      getHealth: function () {
        return this._currentHelth
      },
      increase: function () {
        if (this._currentHelth < 100) {
          this._currentHelth++
        }
      },
      decrease: function () {
        if (this._currentHelth > 0) {
          this._currentHelth--
        }
      },
    }

    function add() {
      let addHealth = document.getElementById('health')
      healthObject.increase()
      if (addHealth) {
        addHealth.style.width = healthObject.getHealth() + '%'
        addHealth.innerHTML = healthObject.getHealth() + 'hp'
      }
    }

function remove() {
  let addHealth = document.getElementById('health')
  healthObject.decrease()
  if (addHealth) {
    addHealth.style.width = healthObject.getHealth() + '%'
    addHealth.innerHTML = healthObject.getHealth() + 'hp'
  }
}


问:
Makefile: Rule dependent on directory of target
I am trying to create a Makefile to create object files in a directory based on the source file. For example I have DirA/file.c and DirB/file.c and I want to create a recipe for creating DirA/file.o and DirB/file.o.

```<code>rootdir/
|-- Makefile
|-- DirA
|    |-- source.c
|    +-- source.o
+-- DirB
    |-- file.c
    +-- file.o
</code>```

I would assume the recipe would be similar to the following:

```<code>MAKEFLAGS += --no-builtin-rules
DirA_Files=$(wildcard DirA/*.c)
DirB_Files=$(wildcard DirB/*.c)

.PHONY: all a_files b_files
all: a_files b_files
    @echo Done with all!
    @echo built $(patsubst %.c,%.o,$(DirA_Files)) $(patsubst %.c,%.o,$(DirB_Files))

a_files: $(patsubst %.c,%.o,$(DirA_Files))
b_files: $(patsubst %.c,%.o,$(DirB_Files))

DirA/%.o DirB/%.o : DirA/%.c DirB/%.c
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@
</code>```

But I do not want the object files in DirA to be dependent on the source files of DirB, which is what the above recipe implies.

I have also tried

```<code>DirA/%.o : DirA/%.c
DirB/%.o : DirB/%.c
DirA/%.o DirB/%.o :
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@
</code>```

But then the $? variable is always blank.

How could I create a single recipe that would also allow me to build a_files and b_files independently

答:
related info:</p>

```<code>DirA_Files := $(wildcard DirA/*.c)
DirB_Files := $(wildcard DirB/*.c)

$(info DirA_Files: $(DirA_Files))
$(info DirB_Files: $(DirB_Files))

aobj := $(patsubst %.c,%.o,$(DirA_Files))
bobj := $(patsubst %.c,%.o,$(DirB_Files))

$(info aobj: $(aobj))
$(info bobj: $(bobj))

all: $(aobj) $(bobj)
        @echo Done with all!
</code>```

Body:
I am trying to create a Makefile to create object files in a directory based on the source file. For example I have DirA/file.c and DirB/file.c and I want to create a recipe for creating DirA/file.o and DirB/file.o.

rootdir/
|-- Makefile
|-- DirA
|    |-- source.c
|    +-- source.o
+-- DirB
    |-- file.c
    +-- file.o

I would assume the recipe would be similar to the following:

MAKEFLAGS += --no-builtin-rules
DirA_Files=$(wildcard DirA/*.c)
DirB_Files=$(wildcard DirB/*.c)

.PHONY: all a_files b_files
all: a_files b_files
    @echo Done with all!
    @echo built $(patsubst %.c,%.o,$(DirA_Files)) $(patsubst %.c,%.o,$(DirB_Files))

a_files: $(patsubst %.c,%.o,$(DirA_Files))
b_files: $(patsubst %.c,%.o,$(DirB_Files))

DirA/%.o DirB/%.o : DirA/%.c DirB/%.c
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@

But I do not want the object files in DirA to be dependent on the source files of DirB, which is what the above recipe implies.

I have also tried

DirA/%.o : DirA/%.c
DirB/%.o : DirB/%.c
DirA/%.o DirB/%.o :
    # Complex recipe that I'd rather not state twice in the Makefile
    @echo "Building $@ because $? changed"
    @touch $@

But then the $? variable is always blank.

How could I create a single recipe that would also allow me to build a_files and b_files independently

Body:
related info:

DirA_Files := $(wildcard DirA/*.c)
DirB_Files := $(wildcard DirB/*.c)

$(info DirA_Files: $(DirA_Files))
$(info DirB_Files: $(DirB_Files))

aobj := $(patsubst %.c,%.o,$(DirA_Files))
bobj := $(patsubst %.c,%.o,$(DirB_Files))

$(info aobj: $(aobj))
$(info bobj: $(bobj))

all: $(aobj) $(bobj)
        @echo Done with all!


问:
Handle Resource not found in Rest API
I am developing a Rest API in spring boot. Which of the following is the best way to handle when an instance of resource not found ?

```<code>    @GetMapping(value="/book/{id}")
    public ResponseEntity<Book> getBook(@PathVariable String id){

        Book book = bookService.getBook();

        // Which is best Approach for resource instance not found ?
        if(book == null) {
            // This one
            return new ResponseEntity<>(book, HttpStatus.NO_CONTENT);
            //OR
            return  new ResponseEntity<>(book, HttpStatus.NOT_FOUND);
            //OR
            throw new DataNotFoundException("Book with id " + id + " Does not exist");
        }

        return new ResponseEntity<>(book , HttpStatus.OK);
    }
</code>```

I am clear about that when a collection of resource not found in Db then to pass an empty collection instead of null but I am not clear what to do with an instance of resource.

I have also read on StackOverflow that HttpStatus.NOT_FOUND should be used when a Resource under the criteria cannot exist instead of do not exist in the Db.

What is best approach to handle this ?

答:
If your endpoint gets book by id and the book does not exists, return 400. Do not return 404. 404 is protocol error: it should be reserved for wrong URL. Now URL is correct but id is wrong. Id almost often is not guessed, but returned by previous query. It cannot disappear suddenly: if id is wrong, the request is wrong.

If your endpoint gets book by title and the book does not exists, return 204. That is absolutely normal that book does not exists in such case and client should be prepared to handle 204.

Someone could argue that difference between 400 and 204 is fuzzy and better always return 204. Indeed, difference may be fuzzy, but from monitoring perspective I would like to know when everything is ok (no book found by title) and when something smells (no book found by id).

I know that my answer does not comply REST directives (or maybe does not comply). I don't care it too much. I simply think that 404 should be reserved for application server and should not be used by application. Reason is already explained in other answer here.

Summary:

404: wrong URL

400: wrong id

204: not found and that is OK

Title: Handle Resource not found in Rest API

Body:
I am developing a Rest API in spring boot. Which of the following is the best way to handle when an instance of resource not found ?

    @GetMapping(value="/book/{id}")
    public ResponseEntity<Book> getBook(@PathVariable String id){

        Book book = bookService.getBook();

        // Which is best Approach for resource instance not found ?
        if(book == null) {
            // This one
            return new ResponseEntity<>(book, HttpStatus.NO_CONTENT);
            //OR
            return  new ResponseEntity<>(book, HttpStatus.NOT_FOUND);
            //OR
            throw new DataNotFoundException("Book with id " + id + " Does not exist");
        }

        return new ResponseEntity<>(book , HttpStatus.OK);
    }

I am clear about that when a collection of resource not found in Db then to pass an empty collection instead of null but I am not clear what to do with an instance of resource.

I have also read on StackOverflow that HttpStatus.NOT_FOUND should be used when a Resource under the criteria cannot exist instead of do not exist in the Db.

What is best approach to handle this ?


问:
How to make a rectangle's height the same height of a VStack
I have a swift view that consists of a HStack with a rectangle and a Vstack of text inside. I want to make the height of the rectangle the same as the height of the Vstack. I have already tried looking through many other questions here on StackOverflow but didn't find an answer. Can anyone help me do that?

Here is my code:

```<code>struct TodoView: View {
    @State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
    @State var height: CGFloat = 45
    var body: some View {
                HStack{
                    RoundedRectangle(cornerRadius: 2)
                        .frame(width: 1)
                        .foregroundColor(Color("lightGray"))
                        .padding()
                    VStack{

                        Text("Todo")
                            .font(.title)
                        ForEach(todos, id: \.self){ todo in
                            Text(todo)
                        }
                    }

                    Spacer()
        }
    }
}
</code>```

答:
You can use .frame modifier:

```<code>HStack{
    RoundedRectangle(cornerRadius: 2)
        .frame(width: 1, height: 50)
        .foregroundColor(Color("lightGray"))
        .padding()
    VStack {
        Text("Todo")
            .font(.title)
        ForEach(todos, id: \.self){ todo in
            Text(todo)
        }
        .frame(height: 50)
    }
    Spacer()
}
</code>```

If you want to have them fill the whole View:

```<code>.frame(minWidth: 0, maxWidth: .infinity)
</code>```

Alternatively, you can use GeometryReader as proposed here: Make a grid of buttons of same width and height in SwiftUI.

Body:
I have a swift view that consists of a HStack with a rectangle and a Vstack of text inside. I want to make the height of the rectangle the same as the height of the Vstack. I have already tried looking through many other questions here on StackOverflow but didn't find an answer. Can anyone help me do that?

Here is my code:

struct TodoView: View {
    @State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
    @State var height: CGFloat = 45
    var body: some View {
                HStack{
                    RoundedRectangle(cornerRadius: 2)
                        .frame(width: 1)
                        .foregroundColor(Color("lightGray"))
                        .padding()
                    VStack{

                        Text("Todo")
                            .font(.title)
                        ForEach(todos, id: \.self){ todo in
                            Text(todo)
                        }
                    }

                    Spacer()
        }
    }
}

Body:
You can use .frame modifier:

HStack{
    RoundedRectangle(cornerRadius: 2)
        .frame(width: 1, height: 50)
        .foregroundColor(Color("lightGray"))
        .padding()
    VStack {
        Text("Todo")
            .font(.title)
        ForEach(todos, id: \.self){ todo in
            Text(todo)
        }
        .frame(height: 50)
    }
    Spacer()
}

If you want to have them fill the whole View:

.frame(minWidth: 0, maxWidth: .infinity)

Alternatively, you can use GeometryReader as proposed here: Make a grid of buttons of same width and height in SwiftUI.


问:
Adding X-meli-session-id Header in MercadoPago SDK
My requirement is to add X-meli-session-id Header in the payment request to MercadoPago, but i cant find a way to add a extra header, I'm using mercadopago SKD "dx-java-1.0.33" and the request is done just calling

```<code>payment.save();
</code>```

Anyone knows how to do that?

Thanks

答:
I solved it. I updated the SDK to 1.2.1. This versions has an option to create a payment with an object "MPRequestOptions" in the constructor of save method as follow:

```<code>MPRequestOptions mpRequestOptions = MPRequestOptions.createDefault();
    customHeaders.put("X-meli-session-id",deviceId);
    mpRequestOptions.setCustomHeaders(customHeaders);

    payment.save(mpRequestOptions);
</code>```

Regards

Body:
My requirement is to add X-meli-session-id Header in the payment request to MercadoPago, but i cant find a way to add a extra header, I'm using mercadopago SKD "dx-java-1.0.33" and the request is done just calling

payment.save();

Anyone knows how to do that?

Thanks

Body:
I solved it. I updated the SDK to 1.2.1. This versions has an option to create a payment with an object "MPRequestOptions" in the constructor of save method as follow:

MPRequestOptions mpRequestOptions = MPRequestOptions.createDefault();
    customHeaders.put("X-meli-session-id",deviceId);
    mpRequestOptions.setCustomHeaders(customHeaders);

    payment.save(mpRequestOptions);

Regards


问:
re.search group not working in python regex
I am trying to analyze some logs from a text file containing my ping information.

Here is a small example of the text file output:

```<code>[2020-06-01 21:54:15.924620] 64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.029 ms
[2020-06-01 21:54:16.968341] 64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.078 ms
</code>```

I wrote a small python regex script to extract the time from the time=x.xxx ms part:

```<code>with open("ping_test.txt",'r') as fp:
    for line in fp:
        line = line.strip()
        print(re.search(r'time=(\d.\d*)',line).group(1))
</code>```

Expected output: x.xxx

Actual output: AttributeError: 'NoneType' object has no attribute 'group'

I have attempted debugging by doing the following: print(re.search(r'time=(\d.\d*)',line))
to which an example output would be: <re.Match object; span=(85, 95), match='time=0.032'>

This shows that re.search is indeed finding a match. What I don't understand is why I can't call the .group() method to output my desired group.

Your help would be much appreciated.

答:
Maybe just try to print also the lines that do not have a match. For example:

with open("ping_test.txt",'r') as fp:
    for line in fp:
        res = re.search(r'time=(\d.\d*)',line.strip())
        if res:
            print(res.group(1))
        else:
            print('Error while parsing:', line)

```

Body:
I am trying to analyze some logs from a text file containing my ping information.

Here is a small example of the text file output:

[2020-06-01 21:54:15.924620] 64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.029 ms
[2020-06-01 21:54:16.968341] 64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.078 ms

I wrote a small python regex script to extract the time from the time=x.xxx ms part:

with open("ping_test.txt",'r') as fp:
    for line in fp:
        line = line.strip()
        print(re.search(r'time=(\d.\d*)',line).group(1))

Expected output: x.xxx

Actual output: AttributeError: 'NoneType' object has no attribute 'group'

I have attempted debugging by doing the following: print(re.search(r'time=(\d.\d*)',line))
to which an example output would be: <re.Match object; span=(85, 95), match='time=0.032'>

This shows that re.search is indeed finding a match. What I don't understand is why I can't call the .group() method to output my desired group.

Your help would be much appreciated.


问:
lists of anagrams in python using two for loops
I need to write a function that takes a list of strings , and return a list that have lists of anagrams words. I need to use 2 for loops for that exercise. Words that are not anagrams to anything will be one item list inside the big list

example output:

```<code>>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'],
 ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'],
['smelters', 'termless', 'resmelts']]
</code>```

im getting the items sorted but dont know how to continue... heres my code:

```<code>def sort_anagrams(list_of_strings):
    sorted_list = list()
    temp_list = list()
    temp2_list = list()
    for item in list_of_strings:
        temp_list.append("".join(sorted(item)))
    print(temp_list)
</code>```

答:
```<code>def sort_anagrams(l):
    a,u,x,m=[],[],[],[]
    for i in l:
         i=''.join(sorted(i))
         a.append(i)
    for i in range(len(l)):
         m.append([l[i],a[i]])
    d=list((pair[0],pair[1]) for pair in m)
    def sorting(s):
        return s[1]

    d=sorted(d, key=sorting)
    count=0
    for i in d:
        if i[1] not in x:
            x.append(i[1])
            u.insert(count,list(list([i[0]])))
            count+=1
        else:
            u[count-1].append(i[0])    # grouping anagrams together
    return(u)

l = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']

print(sort_anagrams(l))
</code>```

This program would give the result for the list you pass.
edit: I have replace lambda with a function, and zip with a for loop!

Body:
I need to write a function that takes a list of strings , and return a list that have lists of anagrams words. I need to use 2 for loops for that exercise. Words that are not anagrams to anything will be one item list inside the big list

example output:

>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'],
 ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'],
['smelters', 'termless', 'resmelts']]

im getting the items sorted but dont know how to continue... heres my code:

def sort_anagrams(list_of_strings):
    sorted_list = list()
    temp_list = list()
    temp2_list = list()
    for item in list_of_strings:
        temp_list.append("".join(sorted(item)))
    print(temp_list)

Body:
def sort_anagrams(l):
    a,u,x,m=[],[],[],[]
    for i in l:
         i=''.join(sorted(i))
         a.append(i)
    for i in range(len(l)):
         m.append([l[i],a[i]])
    d=list((pair[0],pair[1]) for pair in m)
    def sorting(s):
        return s[1]

    d=sorted(d, key=sorting)
    count=0
    for i in d:
        if i[1] not in x:
            x.append(i[1])
            u.insert(count,list(list([i[0]])))
            count+=1
        else:
            u[count-1].append(i[0])    # grouping anagrams together
    return(u)

l = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']

print(sort_anagrams(l))

This program would give the result for the list you pass.
edit: I have replace lambda with a function, and zip with a for loop!


问:
How do I merge two dictionaries in a single expression in Python?
I want to merge two dictionaries into a new dictionary.

```<code>x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)

>>> z
{'a': 1, 'b': 3, 'c': 4}
</code>```

Whenever a key k is present in both dictionaries, only the value y[k] should be kept.

答:
New in Python 3.9: Use the union operator (|) to merge dicts similar to sets:

```<code>>>> d = {'a': 1, 'b': 2}
>>> e = {'a': 9, 'c': 3}
>>> d | e
{'a': 9, 'b': 2, 'c': 3}
</code>```

For matching keys, the right dict takes precedence.

This also works for |= to modify a dict in-place:

```<code>>>> e |= d    # e = e | d
>>> e
{'a': 1, 'c': 3, 'b': 2}
</code>```

OwnerDisplayName: Carl Meyer

Body:
I want to merge two dictionaries into a new dictionary.

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)

>>> z
{'a': 1, 'b': 3, 'c': 4}

Whenever a key k is present in both dictionaries, only the value y[k] should be kept.

LastEditorDisplayName: Carl Meyer

Body:
New in Python 3.9: Use the union operator (|) to merge dicts similar to sets:

>>> d = {'a': 1, 'b': 2}
>>> e = {'a': 9, 'c': 3}
>>> d | e
{'a': 9, 'b': 2, 'c': 3}

For matching keys, the right dict takes precedence.

This also works for |= to modify a dict in-place:

>>> e |= d    # e = e | d
>>> e
{'a': 1, 'c': 3, 'b': 2}


问:
Not getting a result with this powershell script
I want to uninstall a package once it finds the right version. irrespective of any version, its uninstallaing it . Its not considering the version here. Can someone kindly help me </p>

```<code>$uninstallDsktp = Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'| Select-Object DisplayVersion | Where-Object { $_.Displayname -match "MicroStrategy Desktop"}
#$tru = 11.1.1.6968

if ($uninstallDsktp -eq 11.1.6968) {
 $Parms= " /Uninstall /norestart --ResponseFile=""$InstDir\response_uninstall.ini"" /s /f1""$InstDir\uninstall.iss"" -f2""C:\Windows\FNMA\Logs\MSTR_Desktop-11.1.1_UnInstall.log"""
 $CMDS = "Setup.exe"
 $Process = Start-Process $CMDS $Parms -PassThru -Wait -WorkingDirectory "C:\Program Files (x86)\InstallShield Installation Information\{CE4E5307-2A7F-4DE2-A66D-9B198829A688}"
 $Extval=$Process.ExitCode
 LogWrite "Uninstalling MicroStrategy Desktop 11.1.0 exit code:$Extval"
}
</code>```

答:
You have a mistake in the pipeline. Try this

```<code>$uninstallDsktp = Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Where-Object { $_.Displayname -match "MicroStrategy Desktop"} | Select-Object DisplayVersion
</code>```

The other error I noticed is that the value you're looking is stored in $uninstallDsktp.DisplayVersion, so the if statement should look like this

```<code>if ([version] $uninstallDsktp.DisplayVersion -eq [version] '11.1.6968') {
</code>```

Body:
I want to uninstall a package once it finds the right version. irrespective of any version, its uninstallaing it . Its not considering the version here. Can someone kindly help me

$uninstallDsktp = Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'| Select-Object DisplayVersion | Where-Object { $_.Displayname -match "MicroStrategy Desktop"}
#$tru = 11.1.1.6968

if ($uninstallDsktp -eq 11.1.6968) {
 $Parms= " /Uninstall /norestart --ResponseFile=""$InstDir\response_uninstall.ini"" /s /f1""$InstDir\uninstall.iss"" -f2""C:\Windows\FNMA\Logs\MSTR_Desktop-11.1.1_UnInstall.log"""
 $CMDS = "Setup.exe"
 $Process = Start-Process $CMDS $Parms -PassThru -Wait -WorkingDirectory "C:\Program Files (x86)\InstallShield Installation Information\{CE4E5307-2A7F-4DE2-A66D-9B198829A688}"
 $Extval=$Process.ExitCode
 LogWrite "Uninstalling MicroStrategy Desktop 11.1.0 exit code:$Extval"
}

Body:
You have a mistake in the pipeline. Try this

$uninstallDsktp = Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Where-Object { $_.Displayname -match "MicroStrategy Desktop"} | Select-Object DisplayVersion

The other error I noticed is that the value you're looking is stored in $uninstallDsktp.DisplayVersion, so the if statement should look like this

if ([version] $uninstallDsktp.DisplayVersion -eq [version] '11.1.6968') {