问:
save selected rows from a table in local storage
I am working with a data table with kendo grid and jquery, I need to obtain the values of the selected rows through the checkbox, so I am capturing the event when it changes and returns the values of the rows that are marked, something like this:

function onChange(e) {
    var rows = e.sender.select();
    rows.each(function(e) {
        var grid = $("#grid").data("kendoGrid");
        var dataItem = grid.dataItem(this);

        console.log(dataItem);
    })
};

$(document).ready(function() {
    $("#grid").kendoGrid({
        dataSource: {
            pageSize: 10,
            transport: {
                read: {
                    url: "https://demos.telerik.com/kendo-ui/service/Products",
                    dataType: "jsonp"
                }
            },
            schema: {
                model: {
                    id: "ProductID"
                }
            }
        },
        pageable: true,
        scrollable: false,
        persistSelection: true,
        sortable: true,
        change: onChange,
        columns: [{
                selectable: true,
                width: "50px"
            },
            {
                field: "ProductName",
                title: "Product Name"
            },
            {
                field: "UnitPrice",
                title: "Unit Price",
                format: "{0:c}"
            },
            {
                field: "UnitsInStock",
                title: "Units In Stock"
            },
            {
                field: "Discontinued"
            }
        ]
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Kendo UI Snippet</title>

    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.114/styles/kendo.default-v2.min.css"/>

    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2020.1.114/js/kendo.all.min.js"></script>
</head>
<body>

<div id="example">
    <div id="grid"></div>
</div>
</body>
</html></code>```

What I need now is to be able to store the values that if they are selected, I want to keep them in an array in local storage, but I don't know how to do this, since I need to keep this array updated and eliminate those that are no longer marked, any ideas?

PD: I also attached the original dojo of the example https://dojo.telerik.com/IciMekAn

答:
I would review a localStorage tutorial. Here is a basic example. Be aware that the snippet will throw an error due to the environment.

$(function() {
  function saveLocalData(k, d) {
    if (k == undefined) {
      return false;
    }
    if (d.length) {
      localStorage.setItem(k, JSON.stringify(d));
    } else {
      localStorage.removeItem(k);
    }
    return d.length;
  }

  function getLocalData(k) {
    return JSON.parse(localstorage.getItem(k));
  }

  function getGridData(target, elem) {
    return target.data("kendoGrid").dataItem(elem);
  }

  function onChange(e) {
    var selected = [];
    var rows = e.sender.select();
    rows.each(function(i, el) {
      //selected.push(dataItem);
      selected.push(getGridData($("#grid"), el));
    });
    console.log(selected);
    saveLocalData("selected", selected);
  }

  $("#grid").kendoGrid({
    dataSource: {
      pageSize: 10,
      transport: {
        read: {
          url: "https://demos.telerik.com/kendo-ui/service/Products",
          dataType: "jsonp"
        }
      },
      schema: {
        model: {
          id: "ProductID"
        }
      }
    },
    pageable: true,
    scrollable: false,
    persistSelection: true,
    sortable: true,
    change: onChange,
    columns: [{
        selectable: true,
        width: "50px"
      },
      {
        field: "ProductName",
        title: "Product Name"
      },
      {
        field: "UnitPrice",
        title: "Unit Price",
        format: "{0:c}"
      },
      {
        field: "UnitsInStock",
        title: "Units In Stock"
      },
      {
        field: "Discontinued"
      }
    ]
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.114/styles/kendo.default-v2.min.css" />

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2020.1.114/js/kendo.all.min.js"></script>

<div id="example">
  <div id="grid"></div>
</div></code>```

Body:
I am working with a data table with kendo grid and jquery, I need to obtain the values of the selected rows through the checkbox, so I am capturing the event when it changes and returns the values of the rows that are marked, something like this:

function onChange(e) {
    var rows = e.sender.select();
    rows.each(function(e) {
        var grid = $("#grid").data("kendoGrid");
        var dataItem = grid.dataItem(this);

        console.log(dataItem);
    })
};

$(document).ready(function() {
    $("#grid").kendoGrid({
        dataSource: {
            pageSize: 10,
            transport: {
                read: {
                    url: "https://demos.telerik.com/kendo-ui/service/Products",
                    dataType: "jsonp"
                }
            },
            schema: {
                model: {
                    id: "ProductID"
                }
            }
        },
        pageable: true,
        scrollable: false,
        persistSelection: true,
        sortable: true,
        change: onChange,
        columns: [{
                selectable: true,
                width: "50px"
            },
            {
                field: "ProductName",
                title: "Product Name"
            },
            {
                field: "UnitPrice",
                title: "Unit Price",
                format: "{0:c}"
            },
            {
                field: "UnitsInStock",
                title: "Units In Stock"
            },
            {
                field: "Discontinued"
            }
        ]
    });
});

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Kendo UI Snippet</title>

    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.114/styles/kendo.default-v2.min.css"/>

What I need now is to be able to store the values that if they are selected, I want to keep them in an array in local storage, but I don't know how to do this, since I need to keep this array updated and eliminate those that are no longer marked, any ideas?

PD: I also attached the original dojo of the example https://dojo.telerik.com/IciMekAn

Body:
I would review a localStorage tutorial. Here is a basic example. Be aware that the snippet will throw an error due to the environment.

$(function() {
  function saveLocalData(k, d) {
    if (k == undefined) {
      return false;
    }
    if (d.length) {
      localStorage.setItem(k, JSON.stringify(d));
    } else {
      localStorage.removeItem(k);
    }
    return d.length;
  }

  function getLocalData(k) {
    return JSON.parse(localstorage.getItem(k));
  }

  function getGridData(target, elem) {
    return target.data("kendoGrid").dataItem(elem);
  }

  function onChange(e) {
    var selected = [];
    var rows = e.sender.select();
    rows.each(function(i, el) {
      //selected.push(dataItem);
      selected.push(getGridData($("#grid"), el));
    });
    console.log(selected);
    saveLocalData("selected", selected);
  }

  $("#grid").kendoGrid({
    dataSource: {
      pageSize: 10,
      transport: {
        read: {
          url: "https://demos.telerik.com/kendo-ui/service/Products",
          dataType: "jsonp"
        }
      },
      schema: {
        model: {
          id: "ProductID"
        }
      }
    },
    pageable: true,
    scrollable: false,
    persistSelection: true,
    sortable: true,
    change: onChange,
    columns: [{
        selectable: true,
        width: "50px"
      },
      {
        field: "ProductName",
        title: "Product Name"
      },
      {
        field: "UnitPrice",
        title: "Unit Price",
        format: "{0:c}"
      },
      {
        field: "UnitsInStock",
        title: "Units In Stock"
      },
      {
        field: "Discontinued"
      }
    ]
  });
});

<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.114/styles/kendo.default-v2.min.css" />

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2020.1.114/js/kendo.all.min.js"></script>

<div id="example">
  <div id="grid"></div>
</div>


来源: stackexchange

问:
Add class to form field Django ModelForm
I am trying to write a Bootstrap Form with Django ModelForm. I have read the Django Documentation Django Documentation about Forms, so I have this code:

```<code><div class="form-group">
{{ form.subject.errors }}
<label for="{{ form.subject.id_for_label }}">Email subject:</label>
{{ form.subject }}</div>
</code>```

The {{form.subject}} is rendered by Django, for example in CharField field model, as input tag,

```<code><input type="text"....> etc.
</code>```

I need add "form-control" class to every input in order to get Bootstrap input appearance (without third-party packages). I found this solution Django add class to form <input ..> field. Is there any way to add a class to every field by default without specifying it in every attribute of the class of Form class?

```<code>class ExampleForm(forms.Form):
   name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   address = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   country = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
</code>```

and so on ..

答:
Since it took me more hours, than I would like to (django newbie), to figure this out, I will place my outcome here aswell.

Setting widget to each field just to add one class over and over again is against programming rule of repeating and leads to many unneccessary rows. This especially happens when working with bootstrap forms.

Here is my (working) example for adding not only bootstrap classes:

forms.py

```<code>class CompanyForm(forms.Form):
    name = forms.CharField(label='Jméno')
    shortcut = forms.CharField(label='Zkratka')
    webpage = forms.URLField(label='Webové stránky')
    logo = forms.FileField(label='Logo')
</code>```

templatetags/custom_tags.py

```<code>from django import template
from django.urls import reverse

register = template.Library()

@register.filter('input_type')
def input_type(ob):
    '''
    Extract form field type
    :param ob: form field
    :return: string of form field widget type
    '''
    return ob.field.widget.__class__.__name__

@register.filter(name='add_classes')
def add_classes(value, arg):
    '''
    Add provided classes to form field
    :param value: form field
    :param arg: string of classes seperated by ' '
    :return: edited field
    '''
    css_classes = value.field.widget.attrs.get('class', '')
    # check if class is set or empty and split its content to list (or init list)
    if css_classes:
        css_classes = css_classes.split(' ')
    else:
        css_classes = []
    # prepare new classes to list
    args = arg.split(' ')
    for a in args:
        if a not in css_classes:
            css_classes.append(a)
    # join back to single string
    return value.as_widget(attrs={'class': ' '.join(css_classes)})
</code>```

reusable_form_fields.html (template)

```<code>{% load custom_tags %}

{% csrf_token %}
{% for field in form %}
    <div class="form-group row">
        {% if field|input_type == 'TextInput' %}
            <div for="{{ field.label }}" class="col-sm-2 col-form-label">
                {{ field.label_tag }}
            </div>
            <div class="col-sm-10">
                {{ field|add_classes:'form-control'}}
                {% if field.help_text %}
                    <small class="form-text text-muted">{{ field.help_text }}</small>
                {% endif %}
            </div>
        {% else %}
            ...
        {% endif %}
    </div>
{% endfor %}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a Bootstrap Form with Django ModelForm. I have read the Django Documentation Django Documentation about Forms, so I have this code:

{{ form.subject.errors }}
Email subject:
{{ form.subject }}

The {{form.subject}} is rendered by Django, for example in CharField field model, as input tag,

<input type="text"....> etc.

I need add "form-control" class to every input in order to get Bootstrap input appearance (without third-party packages). I found this solution Django add class to form <input ..> field. Is there any way to add a class to every field by default without specifying it in every attribute of the class of Form class?

class ExampleForm(forms.Form):
   name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   address = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   country = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))

and so on ..

Body:
Since it took me more hours, than I would like to (django newbie), to figure this out, I will place my outcome here aswell.

Setting widget to each field just to add one class over and over again is against programming rule of repeating and leads to many unneccessary rows. This especially happens when working with bootstrap forms.

Here is my (working) example for adding not only bootstrap classes:

forms.py

class CompanyForm(forms.Form):
    name = forms.CharField(label='Jméno')
    shortcut = forms.CharField(label='Zkratka')
    webpage = forms.URLField(label='Webové stránky')
    logo = forms.FileField(label='Logo')

templatetags/custom_tags.py

from django import template
from django.urls import reverse

register = template.Library()

@register.filter('input_type')
def input_type(ob):
    '''
    Extract form field type
    :param ob: form field
    :return: string of form field widget type
    '''
    return ob.field.widget.__class__.__name__

@register.filter(name='add_classes')
def add_classes(value, arg):
    '''
    Add provided classes to form field
    :param value: form field
    :param arg: string of classes seperated by ' '
    :return: edited field
    '''
    css_classes = value.field.widget.attrs.get('class', '')
    # check if class is set or empty and split its content to list (or init list)
    if css_classes:
        css_classes = css_classes.split(' ')
    else:
        css_classes = []
    # prepare new classes to list
    args = arg.split(' ')
    for a in args:
        if a not in css_classes:
            css_classes.append(a)
    # join back to single string
    return value.as_widget(attrs={'class': ' '.join(css_classes)})

reusable_form_fields.html (template)

{% load custom_tags %}

{% csrf_token %}
{% for field in form %}
    <div class="form-group row">
        {% if field|input_type == 'TextInput' %}
            <div for="{{ field.label }}" class="col-sm-2 col-form-label">
                {{ field.label_tag }}
            </div>
            <div class="col-sm-10">
                {{ field|add_classes:'form-control'}}
                {% if field.help_text %}
                    <small class="form-text text-muted">{{ field.help_text }}</small>
                {% endif %}
            </div>
        {% else %}
            ...
        {% endif %}
    </div>
{% endfor %}


问:
Access the id of the Button from Datagrird to out side?
I have a button inside the DataGrid using ItemRenderer I want to access the button id inside the click handler. How can I do this?

```<code><fx:Script>
  public function myButton_clickHandler(event:Event):void
  {
    Alert.show("My button was clicked!");
  }
</fx:Script>

<mx:DataGrid width="100%" height="95%" id="id_variableRefList" >
  <mx:columns>
    <mx:DataGridColumn id="id_name" dataField=""/>
    <mx:DataGridColumn id="id_strip" dataField="">
      <mx:itemRenderer>
       <fx:Component>
        <mx:VBox>
         <mx:Button label="My Button" click="outerDocument.myButton_clickHandler(event);" />
        </mx:VBox>
       </fx:Component>
      </mx:itemRenderer>
    </mx:DataGridColumn>
  </mx:columns>
</mx:DataGrid>
</code>```

I Want to access the My Button id in the click handler.

答:
I suppose you want Button instance, not the id. event.target should be the Button:

```<code>public function myButton_clickHandler(event:Event):void
{
   var button:Button = event.target as Button;
   Alert.show("Button " + button.label + " was clicked!");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a button inside the DataGrid using ItemRenderer I want to access the button id inside the click handler. How can I do this?

<fx:Script>
  public function myButton_clickHandler(event:Event):void
  {
    Alert.show("My button was clicked!");
  }
</fx:Script>

<mx:DataGrid width="100%" height="95%" id="id_variableRefList" >
  <mx:columns>
    <mx:DataGridColumn id="id_name" dataField=""/>
    <mx:DataGridColumn id="id_strip" dataField="">
      <mx:itemRenderer>
       <fx:Component>
        <mx:VBox>
         <mx:Button label="My Button" click="outerDocument.myButton_clickHandler(event);" />
        </mx:VBox>
       </fx:Component>
      </mx:itemRenderer>
    </mx:DataGridColumn>
  </mx:columns>
</mx:DataGrid>

I Want to access the My Button id in the click handler.

Body:
I suppose you want Button instance, not the id. event.target should be the Button:

public function myButton_clickHandler(event:Event):void
{
   var button:Button = event.target as Button;
   Alert.show("Button " + button.label + " was clicked!");
}


问:
Using Index annotation on superclass with Hibernate
I have an abstract superclass which every Entity on my domain is a subclass of it.

Using DB schema generation, I want to create an Index for each Entity, on a field on the superclass, and without using the Table annotation on every subclass.

My superclass

    @MappedSuperclass
    public abstract class BaseEntity {

        @Id
        @GeneratedValue(strategy = SEQUENCE)
        private Long surrogateId;

        @Index(name="id_index") // Every subclass should inherit this index, with its own name
        @Column(unique = true, updatable = false, nullable = false)
        private UUID id = UUID.randomUUID();
```

<p>An example of subclass</p>

<pre class="lang-java prettyprint-override"><code>    @Entity
    public class Customer extends BaseEntity {
        ...
    }
</code>```

I tried so far:

use the Table annotation with @Index on the superclass, but Hibernate
doesn't seem to use that annotation if it is not marked with @Entity.
For example
@Table(indexes = {@Index(name="index_id", columnList = "id")})
No SQL statements are generated.

use the deprecated @Index annotation with a name "id_index", but only one index
is created on startup (the db raises an error that this index already
exists for other entities). Some generated SQL statements:

```<code>    Hibernate: create index id_index on "customer" ("id")

    Hibernate: create index id_index on "user" ("id")

    2020-02-15 17:47:26,620 WARN  o.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl    - GenerationTarget encountered exception accepting command : Error executing DDL "create index id_index on "customer" ("id")" via JDBC Statement
    org.postgresql.util.PSQLException: ERROR: relation "id_index" already exists
</code>```

Any ideas on how to do this without too much code duplication?

Thanks

答:
The only way I can see to do this - and it appears more trouble than it is worth to simply avoid placing an @Table annotation on each Entity  - is to create a custom dialect and override the getIndexExporter() method:

```<code>public class MyPostgreSQLDialect extends PostgreSQLXXDialect{

    @Override
    public Exporter<Index> getIndexExporter() {
            return new MyIndexExporter(this);
        }
    }
</code>```

to return a customized Exporter, most likely extending org.hibernate.tool.schema.internal.StandardIndexExporter

```<code>public class MyIndexExporter extends StandardIndexExporter{

    public MyIndexExporter(Dialect dialect){
        super(dialect);
    }

    @Override
    public String[] getSqlCreateStrings(Index index, Metadata metadata) {
      //looks like you'd need to paste the whole code from superclass method
      //and alter the index name accordingly

      indexNameForCreation = index.getTable().getQualifiedTableName() +
               "_" + index.getName();

      //in the default implementation it is simply index.getName()
    }
}
</code>```

Body:
I have an abstract superclass which every Entity on my domain is a subclass of it.

Using DB schema generation, I want to create an Index for each Entity, on a field on the superclass, and without using the Table annotation on every subclass.

My superclass

    @MappedSuperclass
    public abstract class BaseEntity {

        @Id
        @GeneratedValue(strategy = SEQUENCE)
        private Long surrogateId;

        @Index(name="id_index") // Every subclass should inherit this index, with its own name
        @Column(unique = true, updatable = false, nullable = false)
        private UUID id = UUID.randomUUID();

An example of subclass

    @Entity
    public class Customer extends BaseEntity {
        ...
    }

I tried so far:

use the Table annotation with @Index on the superclass, but Hibernate
doesn't seem to use that annotation if it is not marked with @Entity.
For example
@Table(indexes = {@Index(name="index_id", columnList = "id")})
No SQL statements are generated.

use the deprecated @Index annotation with a name "id_index", but only one index
is created on startup (the db raises an error that this index already
exists for other entities). Some generated SQL statements:

    Hibernate: create index id_index on "customer" ("id")

    Hibernate: create index id_index on "user" ("id")

    2020-02-15 17:47:26,620 WARN  o.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl    - GenerationTarget encountered exception accepting command : Error executing DDL "create index id_index on "customer" ("id")" via JDBC Statement
    org.postgresql.util.PSQLException: ERROR: relation "id_index" already exists

Any ideas on how to do this without too much code duplication?

Thanks

Body:
The only way I can see to do this - and it appears more trouble than it is worth to simply avoid placing an @Table annotation on each Entity  - is to create a custom dialect and override the getIndexExporter() method:

public class MyPostgreSQLDialect extends PostgreSQLXXDialect{

    @Override
    public Exporter<Index> getIndexExporter() {
            return new MyIndexExporter(this);
        }
    }

to return a customized Exporter, most likely extending org.hibernate.tool.schema.internal.StandardIndexExporter

public class MyIndexExporter extends StandardIndexExporter{

    public MyIndexExporter(Dialect dialect){
        super(dialect);
    }

    @Override
    public String[] getSqlCreateStrings(Index index, Metadata metadata) {
      //looks like you'd need to paste the whole code from superclass method
      //and alter the index name accordingly

      indexNameForCreation = index.getTable().getQualifiedTableName() +
               "_" + index.getName();

      //in the default implementation it is simply index.getName()
    }
}


问:
MQ reconnect does not work with Wildfly. How to configure it correctly?
MQ reconnect does not work. Can you suggest ways to fix it?

I use Wildfly 12.0.0.Final

Driver is wmq.jmsra-9.1.2.0.rar

Tried to use this ways to configure reconnect

First

```<code><subsystem xmlns="urn:jboss:domain:resource-adapters:5.0">
            <resource-adapters>
                <resource-adapter id="wmq.jmsra.rar" statistics-enabled="false">
                    <archive>
                        wmq.jmsra-9.1.2.0.rar
                    </archive>
                    <transaction-support>NoTransaction</transaction-support>
                    <config-property name="startupRetryInterval">
                        300
                    </config-property>
                    <config-property name="reconnectionRetryCount">
                        9000
                    </config-property>
                    <config-property name="startupRetryCount">
                        9000
                    </config-property>
                    <config-property name="reconnectionRetryInterval">
                        300
                    </config-property>
                </resource-adapter>
            </resource-adapters>
        </subsystem>
</code>```

Second (two last properties)

```<code>    private JMSContext createJmsContext() throws JMSException {
        JmsConnectionFactory cf;
        JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
        cf = ff.createConnectionFactory();
        cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, props.getProperty(Q_HOST));
        cf.setIntProperty(WMQConstants.WMQ_PORT, Integer.valueOf(props.getProperty(Q_PORT)));
        cf.setStringProperty(WMQConstants.WMQ_CHANNEL, props.getProperty(Q_CHANNEL));
        cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
        cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, props.getProperty(Q_MANAGER));
        cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
        cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
        cf.setIntProperty(WMQConstants.WMQ_CLIENT_RECONNECT_OPTIONS, WMQConstants.WMQ_CLIENT_RECONNECT_Q_MGR);
        cf.setIntProperty(WMQConstants.WMQ_CLIENT_RECONNECT_TIMEOUT, 60000);
        return cf.createContext();
    }
</code>```

答:
The IBM MQ classes for JMS resource adapter does not support support Automatic JMS client reconnection.

See IBM MQ v9.1 Knowledge Center page Developing applications>Developing JMS and Java applications>Using IBM MQ classes for JMS>Writing IBM MQ classes for JMS applications>Accessing IBM MQ features from an IBM MQ classes for JMS application:

The use of this implementation of automatic client reconnection is not supported within Java™ Platform, Enterprise Edition application servers. See Using automatic client reconnection in Java EE environments for an alternative implementation.

As stated above see IBM MQ v9.1 Knowledge Center page Developing applications>Developing JMS and Java applications>Using IBM MQ classes for JMS>Writing IBM MQ classes for JMS applications>Accessing IBM MQ features from an IBM MQ classes for JMS application>Automatic JMS client reconnection>Using automatic client reconnection in Java SE and Java EE environments:

Note

Automatic client reconnection with activation specifications using the functionality provided by IBM MQ classes for JMS is not supported. The IBM MQ resource adapter provides its own mechanism for reconnecting activation specifications if the queue manager that the activation specification was connecting to becomes unavailable.

Body:
MQ reconnect does not work. Can you suggest ways to fix it?

I use Wildfly 12.0.0.Final

Driver is wmq.jmsra-9.1.2.0.rar

Tried to use this ways to configure reconnect

First

<subsystem xmlns="urn:jboss:domain:resource-adapters:5.0">
            <resource-adapters>
                <resource-adapter id="wmq.jmsra.rar" statistics-enabled="false">
                    <archive>
                        wmq.jmsra-9.1.2.0.rar
                    </archive>
                    <transaction-support>NoTransaction</transaction-support>
                    <config-property name="startupRetryInterval">
                        300
                    </config-property>
                    <config-property name="reconnectionRetryCount">
                        9000
                    </config-property>
                    <config-property name="startupRetryCount">
                        9000
                    </config-property>
                    <config-property name="reconnectionRetryInterval">
                        300
                    </config-property>
                </resource-adapter>
            </resource-adapters>
        </subsystem>

Second (two last properties)

    private JMSContext createJmsContext() throws JMSException {
        JmsConnectionFactory cf;
        JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
        cf = ff.createConnectionFactory();
        cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, props.getProperty(Q_HOST));
        cf.setIntProperty(WMQConstants.WMQ_PORT, Integer.valueOf(props.getProperty(Q_PORT)));
        cf.setStringProperty(WMQConstants.WMQ_CHANNEL, props.getProperty(Q_CHANNEL));
        cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
        cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, props.getProperty(Q_MANAGER));
        cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
        cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
        cf.setIntProperty(WMQConstants.WMQ_CLIENT_RECONNECT_OPTIONS, WMQConstants.WMQ_CLIENT_RECONNECT_Q_MGR);
        cf.setIntProperty(WMQConstants.WMQ_CLIENT_RECONNECT_TIMEOUT, 60000);
        return cf.createContext();
    }


问:
How to migrate from SourceGear Vault to TFS?
Is there any easy way of migrate files version from SourceGear Vault to TFS?</p>

答:
MS have created a toolkit for creating import and export tools.

But a quick search doesn't show (in the first few hits) anyone who has done the hard work.

Another option is to import current state (just perform a TF add into an Import branch ad then branch into your working project), and keep Vault around for when you need to look at history.

OwnerDisplayName: Richard

ContentLicense: CC BY-SA 2.5


问:
Configure git secondary repo
For some reason git log repo2/master..master -- . doesn't work for me ("fatal: bad revision 'repo2/master..master'", the same applies to git checkout repo2/master -- .). My config looks like this:

```<code>[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = ssh://me@domain.com/var/git/me/repo.git
[remote "repo2"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = ssh://me@domain.com/var/git/me/repo2.git
</code>```

I have no problem running git checkout origin/master -- ., so the problem only applies to "repo2" for some reason. Thanks!

答:
Shouldn't the fetch for repo2 be:</p>

```<code>fetch = +refs/heads/*:refs/remotes/repo2/*
</code>```

Title: Configure git secondary repo

Body:
For some reason git log repo2/master..master -- . doesn't work for me ("fatal: bad revision 'repo2/master..master'", the same applies to git checkout repo2/master -- .). My config looks like this:

[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = ssh://me@domain.com/var/git/me/repo.git
[remote "repo2"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = ssh://me@domain.com/var/git/me/repo2.git

I have no problem running git checkout origin/master -- ., so the problem only applies to "repo2" for some reason. Thanks!

Body:
Shouldn't the fetch for repo2 be:

fetch = +refs/heads/*:refs/remotes/repo2/*


问:
Always getting blank page on all Laravel routes
I am always getting blank page while accessing my Laravel project given below. Please advise how this problem can be resolved. Thanks!

http://1.231.118.4:9000/

http://1.231.118.4:9000/admin/login

Apache 2.4
PHP 7.2
MySQL 5.7

phpinfo: http://1.231.118.4:9000/info.php

vhost:

```<code><VirtualHost *:9000>
    ServerName 1.231.118.4
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/ico/public
    <Directory /var/www/html/ico/public>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
     </Directory>
    ErrorLog /var/www/html/ico/error.log
</VirtualHost>
</code>```

.htaccess:

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
</code>```

答:
In my case, .env file had an entry with bad format, since spaces are not allowed in values without quotes for all value:

```<code>#BAD
DATETIME_FORMAT=Y-m-d H:i:s
#GOOD
DATETIME_FORMAT="Y-m-d H:i:s"
</code>```

For some reason this error did not output anything nowhere, hope will be useful to someone with the same problem!

Body:
I am always getting blank page while accessing my Laravel project given below. Please advise how this problem can be resolved. Thanks!

http://1.231.118.4:9000/

http://1.231.118.4:9000/admin/login

Apache 2.4
PHP 7.2
MySQL 5.7

phpinfo: http://1.231.118.4:9000/info.php

vhost:

<VirtualHost *:9000>
    ServerName 1.231.118.4
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/ico/public
    <Directory /var/www/html/ico/public>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
     </Directory>
    ErrorLog /var/www/html/ico/error.log
</VirtualHost>

.htaccess:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Body:
In my case, .env file had an entry with bad format, since spaces are not allowed in values without quotes for all value:

#BAD
DATETIME_FORMAT=Y-m-d H:i:s
#GOOD
DATETIME_FORMAT="Y-m-d H:i:s"

For some reason this error did not output anything nowhere, hope will be useful to someone with the same problem!


问:
How to read values of variables in a web page?
I have to web scrape a page, but this page is dynamically loaded with some value. So, when I take the source code, there are js variables and not their values. If I download this page, I see their values.
Is there a way to read these values or to download all files (including scripts) in Java program?</p>

答: You can use Selenium library to load an HTML document and run javascript code inside the webdriver and get anything you want.  </p>


问:
Rotate Camera in Matter.js
I am working on a top-down physics based game set in space.  I would like the rotate to the view to always show the player's ship facing up even though the ship can rotate.
I've searched through the docs, but didn't find anything about rotating the world or renderer, but it's possible that I don't know the right terminology to look for.
Is this even possible with matter.js?</p>

答:
Alternatively, add code to the Render.startViewTransform method:

```<code>// OVERLOAD THIS METHOD
Matter.Render.startViewTransform = function(render) {
    var boundsWidth = render.bounds.max.x - render.bounds.min.x,
        boundsHeight = render.bounds.max.y - render.bounds.min.y,
        boundsScaleX = boundsWidth / render.options.width,
        boundsScaleY = boundsHeight / render.options.height;

    // add lines:
    var w2 = render.canvas.width / 2;
    var h2 = render.canvas.height / 2;
    render.context.translate(w2, h2);
    render.context.rotate(angle_target);
    render.context.translate(-w2, -h2);
    // /add lines.

    render.context.scale(1 / boundsScaleX, 1 / boundsScaleY);
    render.context.translate(-render.bounds.min.x, -render.bounds.min.y);
};
</code>```

But you still need to override the calculation of render.bounds, which now always considers a rectangular area for angle = 0!

Title: Rotate Camera in Matter.js

Body:
Alternatively, add code to the Render.startViewTransform method:

// OVERLOAD THIS METHOD
Matter.Render.startViewTransform = function(render) {
    var boundsWidth = render.bounds.max.x - render.bounds.min.x,
        boundsHeight = render.bounds.max.y - render.bounds.min.y,
        boundsScaleX = boundsWidth / render.options.width,
        boundsScaleY = boundsHeight / render.options.height;

    // add lines:
    var w2 = render.canvas.width / 2;
    var h2 = render.canvas.height / 2;
    render.context.translate(w2, h2);
    render.context.rotate(angle_target);
    render.context.translate(-w2, -h2);
    // /add lines.

    render.context.scale(1 / boundsScaleX, 1 / boundsScaleY);
    render.context.translate(-render.bounds.min.x, -render.bounds.min.y);
};

But you still need to override the calculation of render.bounds, which now always considers a rectangular area for angle = 0!


问:
how to access apn service
i am new to the field, i dontkno0w what exactly is apn service in iphone. How can we access it. what code we have to write in server to connect with the device. please help me out
thanks in advance</p>

答:
I would check out Urban Airship as a starting point:

http://www.urbanairship.com/

OR

http://www.xtify.com/

Title: how to access apn service


问:
Splitting a string that is converted to a list with a single item into multiple items
I have a string that is converted to a list using the split() function, and I want to split my single item into multiple items each containing one character.

Here's my code:

```<code>string = "ABCDEFG"
x = string.split()
print(x)
</code>```

Thank you for your time!:D

答:
str.split(separator, maxsplit) method returns a list of strings after breaking the given string by the specified separator.

separator: The is a delimiter. The string splits at this specified separator. It is not provided then any white space is a separator.

maxsplit: It is a number, which tells us to split the string into a maximum of the provided number of times. If it is not provided then there is no limit.

You can do this if you want to split it into a list of single characters.

```<code>x='ABCDEFG'
char_list=list(x)
#['A', 'B', 'C', 'D', 'E', 'F', 'G']
</code>```

If you want to split it into single characters avoiding any spaces then try this.

```<code>x='abcde fgh   i'
out=[char for string in x.split() for char in string]
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
</code>```

And .split() doesn't convert your string to a list. In your, it returned ['ABCDEFG] because the string contains no spaces.

Body:
I have a string that is converted to a list using the split() function, and I want to split my single item into multiple items each containing one character.

Here's my code:

string = "ABCDEFG"
x = string.split()
print(x)

Thank you for your time!:D

Body:
str.split(separator, maxsplit) method returns a list of strings after breaking the given string by the specified separator.

separator: The is a delimiter. The string splits at this specified separator. It is not provided then any white space is a separator.

maxsplit: It is a number, which tells us to split the string into a maximum of the provided number of times. If it is not provided then there is no limit.

You can do this if you want to split it into a list of single characters.

x='ABCDEFG'
char_list=list(x)
#['A', 'B', 'C', 'D', 'E', 'F', 'G']

If you want to split it into single characters avoiding any spaces then try this.

x='abcde fgh   i'
out=[char for string in x.split() for char in string]
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

And .split() doesn't convert your string to a list. In your, it returned ['ABCDEFG] because the string contains no spaces.


问:
**How to select specified number of IMG tags from quantity input value**
Image example:

As you can see from clicking the image example link above, “EE” is the row and “8” is the item number.
I would like to select three of the following four IMG tag items located in the same row and echo the result.

```<code><div id="surface" style="width: 4567px; height: 4137px; left: -1850px; top: -1152px; cursor: default;">

<img src="https://media.memories.png" data-items="L:106|EE:5" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2221px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-items="L:106|EE:6" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2237px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-items="L:106|EE:7" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2253px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-items="L:106|EE:8" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2269px; top: 1561px; display: block;">

</div>
</code>```

I figured out how to select one of the above img tags by specified row and item number using the following xpath, but how can select three items in the row “EE” after selecting the number 3 from a drop-down menu?

```<code>Xpath=//img[@data-items = ' L:106|EE:8']
</code>```

Example Drop-down Menu:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Select Quantity

Move the mouse over the button to open the dropdown menu.

  <button class="dropbtn">Item Count</button>

     1
     2
     3

```

答:
If you want to select 3 from the drop-down you can use the below xpath.

```<code>//div[@class='dropdown-content']/a[normalize-space(.)='3']
</code>```

You can click on the //button[.='Item Count'] and then use the xpath to select 3.

Alternatively, you can use js to select 3 without clicking on the button.

```<code>WebElement element = driver.findElement(By.xpath("//div[@class='dropdown-content']/a[normalize-space(.)='3']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();",element);
</code>```

Body:
Image example:

As you can see from clicking the image example link above, “EE” is the row and “8” is the item number.
I would like to select three of the following four IMG tag items located in the same row and echo the result.

I figured out how to select one of the above img tags by specified row and item number using the following xpath, but how can select three items in the row “EE” after selecting the number 3 from a drop-down menu?

Xpath=//img[@data-items = ' L:106|EE:8']

Example Drop-down Menu:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Select Quantity

Move the mouse over the button to open the dropdown menu.

  <button class="dropbtn">Item Count</button>

     1
     2
     3

Body:
If you want to select 3 from the drop-down you can use the below xpath.

//div[@class='dropdown-content']/a[normalize-space(.)='3']

You can click on the //button[.='Item Count'] and then use the xpath to select 3.

Alternatively, you can use js to select 3 without clicking on the button.

WebElement element = driver.findElement(By.xpath("//div[@class='dropdown-content']/a[normalize-space(.)='3']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();",element);


问:
Regex dealing with Kanji characters in Python
so for this web-scraping project i'm working on, I've been trying to separate some results from results.
basically if the title contains 指定されたページが見つかりません , i'll want to copy the url and write it to one fail.csv file. Anything else i'll want to copy the url and write it to sucess.csv

```<code>html = 'www.abc.com'
url = BeautifulSoup(html,'html.parser').title.string
pattern = re.compile(r' 指定されたページが見つかりません')
if pattern.finditer(url):
with open('fail.csv','w') as f:
cw=csv.writer
cw.writerow([url])
else:
move on, run some other codes and write to sucess.csv
</code>```

However it seems that regex isn't recognising 指定されたページが見つかりません

Am i doing something wrong here or missing something here?

Thanks

答:
Try

```<code>sudo pip3 install requests
sudo pip3 install beautifulsoup4
sudo pip3 install re
</code>```

and under python3

```<code>import requests
import re
from bs4 import BeautifulSoup

r = requests.get('https://corp.rakuten.co.jp/careers/life/')
r.encoding='utf-8'
pattern = re.compile(r' 指定されたページが見つかりません')
url = BeautifulSoup(r.text,'html.parser').title.string
pattern.findall(url)
</code>```

Body:
so for this web-scraping project i'm working on, I've been trying to separate some results from results.
basically if the title contains 指定されたページが見つかりません , i'll want to copy the url and write it to one fail.csv file. Anything else i'll want to copy the url and write it to sucess.csv

html = 'www.abc.com'
url = BeautifulSoup(html,'html.parser').title.string
pattern = re.compile(r' 指定されたページが見つかりません')
if pattern.finditer(url):
with open('fail.csv','w') as f:
cw=csv.writer
cw.writerow([url])
else:
move on, run some other codes and write to sucess.csv

However it seems that regex isn't recognising 指定されたページが見つかりません

Am i doing something wrong here or missing something here?

Thanks

Body:
Try

sudo pip3 install requests
sudo pip3 install beautifulsoup4
sudo pip3 install re

and under python3

import requests
import re
from bs4 import BeautifulSoup

r = requests.get('https://corp.rakuten.co.jp/careers/life/')
r.encoding='utf-8'
pattern = re.compile(r' 指定されたページが見つかりません')
url = BeautifulSoup(r.text,'html.parser').title.string
pattern.findall(url)


问:
Prevent ckeditor to fire set callback, when text updated by external source
I am working on a real time Vue project, that uses ckeditor5 as a text editor. Pusher is a realtime API that uses websocket, to broadcast events to other Pusher instances real time.
This is Pusher

In the ckeditor config, I pass a set callback. This set callback, fires on any text change, and I use it to trigger pusher events, broadcasting the text
value to other pusher instances.

The problem emerges when the other pusher instance on their side recieves the event, and after processing it, Vue updates the text value in the DOM reactively, thus fireing the above mentioned set callback, that triggers the event again. In a realtime environment it messes up the value update, and ends in a text flickering.

In the callback, I only get a string value, and I can't find out what initiated the callback, thus can't stop the execution.

Is there a way to prevent ckeditor5 to fire the callback?

This can be a problem existent on every websocket based project.

答:
The problem is that when a change triggers a broadcast and a Pusher client receives and applies it then it becomes broadcasted as the clients change.
When the original broadcaster receives the change it cannot determine whether it is its own change and applies it again.

After I had a few failed attempts to create a ckeditor plugin which filters out the incoming changes which have been initialized be the ckeditor instance itself, I decided to make a workaround to tackle this issue.

I created a cache which before broadcasting the initialized changes it stores them for a few seconds. When a change is getting received from a Pusher client the change only gets applied if it is not present in the cache therefore it is initialized by another client.

This workaround works in most times but there can be still be issues with a very slow internet connection with low response time (it depends on the caching time).


问:
Spark: what options can be passed with DataFrame.saveAsTable or DataFrameWriter.options?
Neither the developer nor the API documentation includes any reference about what options can be passed in DataFrame.saveAsTable or DataFrameWriter.options and they would affect the saving of a Hive table.

My hope is that in the answers to this question we can aggregate information that would be helpful to Spark developers who want more control over how Spark saves tables and, perhaps, provide a foundation for improving Spark's documentation.

答:
Take a look at https://github.com/delta-io/delta/blob/master/src/main/scala/org/apache/spark/sql/delta/DeltaOptions.scala the class "DeltaOptions'

Currently, supported options are:

replaceWhere

mergeSchema

overwriteSchema

maxFilesPerTrigger

excludeRegex

ignoreFileDeletion

ignoreChanges

ignoreDeletes

optimizeWrite

dataChange

queryName

checkpointLocation

path

timestampAsOf

versionAsOf


问:
Convert .objs to .mat in python or a with a program in linux
Can anyone suggest a way, in python or a general tool in linux maybe to convert an obj into a .mat file?

I have some code like:

```<code>import eigen_solver as es
import scipy.io as sio

# load mesh
model = 'sphere4.mat'
mat = sio.loadmat(model)
V, F = mat['V'], mat['F']
</code>```

But the meshes I want to use are in .obj format.
I'm not 100% sure how easy would be to write this from scratch, but I guess should be somehow straightforward, but if there's a tool I'd like to use it.

By obj I mean https://en.wikipedia.org/wiki/Wavefront_.obj_file
By mat I mean the matlab .mat format.

答:
You can simply use meshio to read in the obj file directly.

```<code>pip install meshio
</code>```

import meshio

mesh = meshio.read("foo.obj")
# mesh.points, mesh.cells, etc.
```

Body:
Can anyone suggest a way, in python or a general tool in linux maybe to convert an obj into a .mat file?

I have some code like:

import eigen_solver as es
import scipy.io as sio

# load mesh
model = 'sphere4.mat'
mat = sio.loadmat(model)
V, F = mat['V'], mat['F']

But the meshes I want to use are in .obj format.
I'm not 100% sure how easy would be to write this from scratch, but I guess should be somehow straightforward, but if there's a tool I'd like to use it.

By obj I mean https://en.wikipedia.org/wiki/Wavefront_.obj_file
By mat I mean the matlab .mat format.

Body:
You can simply use meshio to read in the obj file directly.

pip install meshio

import meshio

mesh = meshio.read("foo.obj")
# mesh.points, mesh.cells, etc.


问:
Export Neo4j to GraphML with node/edge labels?
Has anyone been able to export GraphML, readable by Gephi or yEd, which properly displays labels in Gephi/yEd?

I'm using the latest Neo4j community and APOC; I can export GraphML from APOC just fine, and import into Gephi/yEd, but there doesn't seem to be a way to load the attributes/key/data elements, so that useful labels can be displayed.

答:
Add this line to the top of the graphml-file, along with the other keys.

```<code><key id="labels" for="node" attr.name="labels"/>
</code>```

You can then copy the "labels" property to the Label column in Gephi.

Body:
Add this line to the top of the graphml-file, along with the other keys.

<key id="labels" for="node" attr.name="labels"/>

You can then copy the "labels" property to the Label column in Gephi.


问:
What technology stack to choose for drag and drop page builder
We have different templates built in angular 8 which contain sliders, product listing, and some blocks with images, text etc. I need to create a drag n drop page builder, where user can select a template, add or remove any element and edit elements (styles) e.g product box with image, title, price, button etc. I don't know how to proceed with technology stack which will finally save templates to be served into angular. mostly all components show dynamic data loaded from API

canvas is no option

do I need to create a json object for components' / elements' position on page ?

dynamically creating components with 'ComponentFactoryResolver' can help ? but how to bind data while live editing and after saving when it's served with angular build

when a component is created in dropable area, how I would detect that it contains an image or text and I have to open editable options with respect to the element chosen

Any help will be much much appreciated and I'm open for any discussion

答:
From your description it sounds like you are trying to build a dashboard system or HTML WYSIWYG editor. this is a fairly broad architectural question, and the approaches will very depending on your project's requirements/timeframe etc... My first recommendation would be to do a search to see if there are any tools out there that already do what you want. i.e. does Ck Editor with customization give you want you need? ...

failing to find one, if you need to roll your own, here are a few lessons learned from my experience with this.

either create a custom directive that uses native HTML drag and drop, or use one of the angular libraries out there that provides you with drag and drop (i.e. material drag & drop etc...)

Define what your page model will look like.

Make use of Observables to ensure individual components remain isolated from each other. yet can use shared services/observables to communicate between each other

group as many common 'properties' together and make them part of your base class.

Define what your page model will look like

how will you store the representation of what the user does? in HTML, JSON?

we had a debate between using HTML over JSON internally, but we ended up with JSON as the team felt it was better suited for them. but you could just as well use HTML as your model.
for example:

export interface Widget {
  name: string;
  type: string;
  style: CSSProperties;
  widgets?: Widget[];
}

export interface Text extends Widget {
  textContent: string;
}

export interface Image extends Widget {
  url: string;
}

export interface Table extends Widget {
  source: string;
}```

you can always augment your interfaces, but at least spend sufficient time understanding what structure will look like. if done property, adding new components with their own interfaces becomes a breeze. in some ways, this is where using HTML as the model may make more sense.

but with this model in place, you "TextComponent" can expect a data to be provided to it that conforms to the "Text" interface. same for image, table etc...

with this you can tag your component's html with the specific property you wish to use. i.e. in the case of a TextComponent, you would simply use "{{textContent}} in your HTML since it is a property of the interface for this Component.

Drag and Drop

Understand if you need to support nested dragging and dropping?

depending on the requirements of your project, find a library that has the drop and drop functionality you can use (material drag and drop etc...)

OR create an directive that implements that native Drag and Drop functionality of HTML 5

whichever approach you take, all drag and drop have a 'drop' event. this event is triggered when the user stops dragging. most drag and drops tools also allow you to pass data during the 'drag' even so that the 'drop' event handler can process it.

Once you have defined your models, you could pass the model for the current component in the drag event. and on "Drop" you can check the widget.type of the data passed. this will allow you to determine what type of component you are dealing with.

Make use of Observables to ensure individual components remain isolated from each other

it will be tempting at the start, when you have only a handful of components, to allow your various components to interact with each other directly. potentially even modifying each other's states and/or data.

However, as your list of component grows, and you start to have the need for component interactions, you will start finding problems very quickly. i.e. choosing the date range in Component A needs to also update the data displayed in Component B

we ended up going with a state management solution (NgRX), to help separate state from layout. Since we did it midway through, it was a pain initially, but once done, adding new components became much faster. FYI: You don't need to use NgRx, a service or shared observable that will keep track of your various component's data will do just as well. Using RxJS BehaviorSubject to allow late subscribers to get the current value for example

this allowed for handling scenarios such as

Component B has a dependency on Component A

When a change is made to Component A, rather than Component A looping through all component to find dependencies, Component B subscribes to the store and changes itself a property of Component A Changes

this allowed us to separate the layout logic from the business logic in the application. i.e. whenever the store is updated by Company A, if there is business logic to be applied, then it is handled outside the display component. this helped as our list of components continued to grow.

this allowed us to handle multi component event. i.e. if a user holds shift and selects more then one component, and wants to change the background color on all selected components. the selected Components css property for background color are updated in the store (NgRX), and the component (through subscriptions and change detection) automatically get updated on the screen.

ultimately this approach allowed us to decouple the presentation logic of our components from the data logic.

this can get very complicated depending on how complex you need it to be. if this is a project that you simply need to get something up quick and dirty, then of course do what you must. however, if you have the time to dedicate to this, I would suggest spending some quality time with understanding your model as well as what the component interaction will be.

I hope some of this was helpful. best of luck.

Body:
From your description it sounds like you are trying to build a dashboard system or HTML WYSIWYG editor. this is a fairly broad architectural question, and the approaches will very depending on your project's requirements/timeframe etc... My first recommendation would be to do a search to see if there are any tools out there that already do what you want. i.e. does Ck Editor with customization give you want you need? ...

failing to find one, if you need to roll your own, here are a few lessons learned from my experience with this.

either create a custom directive that uses native HTML drag and drop, or use one of the angular libraries out there that provides you with drag and drop (i.e. material drag & drop etc...)

Define what your page model will look like.

Make use of Observables to ensure individual components remain isolated from each other. yet can use shared services/observables to communicate between each other

group as many common 'properties' together and make them part of your base class.

Define what your page model will look like

how will you store the representation of what the user does? in HTML, JSON?

we had a debate between using HTML over JSON internally, but we ended up with JSON as the team felt it was better suited for them. but you could just as well use HTML as your model.
for example:

export interface Widget {
  name: string;
  type: string;
  style: CSSProperties;
  widgets?: Widget[];
}

export interface Text extends Widget {
  textContent: string;
}

export interface Image extends Widget {
  url: string;
}

export interface Table extends Widget {
  source: string;
}

you can always augment your interfaces, but at least spend sufficient time understanding what structure will look like. if done property, adding new components with their own interfaces becomes a breeze. in some ways, this is where using HTML as the model may make more sense.

but with this model in place, you "TextComponent" can expect a data to be provided to it that conforms to the "Text" interface. same for image, table etc...

with this you can tag your component's html with the specific property you wish to use. i.e. in the case of a TextComponent, you would simply use "{{textContent}} in your HTML since it is a property of the interface for this Component.

Drag and Drop

Understand if you need to support nested dragging and dropping?

depending on the requirements of your project, find a library that has the drop and drop functionality you can use (material drag and drop etc...)

OR create an directive that implements that native Drag and Drop functionality of HTML 5

whichever approach you take, all drag and drop have a 'drop' event. this event is triggered when the user stops dragging. most drag and drops tools also allow you to pass data during the 'drag' even so that the 'drop' event handler can process it.

Once you have defined your models, you could pass the model for the current component in the drag event. and on "Drop" you can check the widget.type of the data passed. this will allow you to determine what type of component you are dealing with.

Make use of Observables to ensure individual components remain isolated from each other

it will be tempting at the start, when you have only a handful of components, to allow your various components to interact with each other directly. potentially even modifying each other's states and/or data.

However, as your list of component grows, and you start to have the need for component interactions, you will start finding problems very quickly. i.e. choosing the date range in Component A needs to also update the data displayed in Component B

we ended up going with a state management solution (NgRX), to help separate state from layout. Since we did it midway through, it was a pain initially, but once done, adding new components became much faster. FYI: You don't need to use NgRx, a service or shared observable that will keep track of your various component's data will do just as well. Using RxJS BehaviorSubject to allow late subscribers to get the current value for example

this allowed for handling scenarios such as

Component B has a dependency on Component A

When a change is made to Component A, rather than Component A looping through all component to find dependencies, Component B subscribes to the store and changes itself a property of Component A Changes

this allowed us to separate the layout logic from the business logic in the application. i.e. whenever the store is updated by Company A, if there is business logic to be applied, then it is handled outside the display component. this helped as our list of components continued to grow.

this allowed us to handle multi component event. i.e. if a user holds shift and selects more then one component, and wants to change the background color on all selected components. the selected Components css property for background color are updated in the store (NgRX), and the component (through subscriptions and change detection) automatically get updated on the screen.

ultimately this approach allowed us to decouple the presentation logic of our components from the data logic.

this can get very complicated depending on how complex you need it to be. if this is a project that you simply need to get something up quick and dirty, then of course do what you must. however, if you have the time to dedicate to this, I would suggest spending some quality time with understanding your model as well as what the component interaction will be.

I hope some of this was helpful. best of luck.


问:
Nearley at least one
I have a grammar where I want to have some whitespace (including newlines) in between two terms. There should be some whitespace, i.e. it should fail if the two terms are touching, however there can be as much whitespace as desired. The issue I'm coming across is that whitespace and newlines are different tokens. I can't work out how to generally make "at least one" in nearley.</p>

答:
I managed to solve this with EBNF modifiers:</p>

```<code>ws -> %WS | %NL

# At least one whitespace
someWS -> ws:+

# none or some whitespace
manyWS -> ws:*
</code>```

Title: Nearley at least one

Body:
I managed to solve this with EBNF modifiers:

ws -> %WS | %NL

# At least one whitespace
someWS -> ws:+

# none or some whitespace
manyWS -> ws:*


问:
R function to find count of elements before sum is above a threshold
I'm trying to recreate a function from Sum of first n elements of a vector, but where this solution took an argument to sum first n elements of vector, I'd like an argument which is the threshold (including a default) the elements sum up to (or over).

After trying different for and/or while possibilities and searching StackOverflow, I've ended up here: unclear how to implement the threshold and set the n_elements.

I have this logic which returns 0 for the given vector. It doesn't seem the n_elements = x[i] + 1 part is correct.

```<code>theFunc <- function(x, threshold = 5){
  n_elements = 0
  while (sum(head(x)) < threshold){
    n_elements = x[i] + 1
  }
  return(n_elements)
}
</code>```

Call:

```<code>x <- c(0, 0, 1, 1, 2, 3, 6, 7)
theFunc(x)
[1] 0
</code>```

If the input is as above and the threshold is 5, then the function should return 6 (number of elements) because 0+0+1+1+2+3 = 7 and is above the threshold.

答:
A simple function without a loop is as follows:

theFunc <- function(x, threshold = 5){
  sum(cumsum(x) < threshold) + 1
}
```

<pre class="lang-r prettyprint-override"><code>x <- c(0, 0, 1, 1, 2, 3, 6, 7)
theFunc(x)
[1] 6
</code>```

Body:
I'm trying to recreate a function from Sum of first n elements of a vector, but where this solution took an argument to sum first n elements of vector, I'd like an argument which is the threshold (including a default) the elements sum up to (or over).

After trying different for and/or while possibilities and searching StackOverflow, I've ended up here: unclear how to implement the threshold and set the n_elements.

I have this logic which returns 0 for the given vector. It doesn't seem the n_elements = x[i] + 1 part is correct.

theFunc <- function(x, threshold = 5){
  n_elements = 0
  while (sum(head(x)) < threshold){
    n_elements = x[i] + 1
  }
  return(n_elements)
}

Call:

x <- c(0, 0, 1, 1, 2, 3, 6, 7)
theFunc(x)
[1] 0

If the input is as above and the threshold is 5, then the function should return 6 (number of elements) because 0+0+1+1+2+3 = 7 and is above the threshold.

Body:
A simple function without a loop is as follows:

theFunc <- function(x, threshold = 5){
  sum(cumsum(x) < threshold) + 1
}

x <- c(0, 0, 1, 1, 2, 3, 6, 7)
theFunc(x)
[1] 6


问:
Storing list of objects in Flutter
I am making an app, which contains two basic classes let's say Class1 and Class2. And in Class1 I stored List<Class2> as attribute with other attributes. My question is how to store List<Class2> if I store some object of Class1 in sqflite database. Is there a way that I can store a List of Class2 objects in a single column of the database.

答: You can serialize it to json and save the string. Then when you read it you can parse it back to an Object

Title: Storing list of objects in Flutter


问:
Passing variable arguments conditionally
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

```<code>if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];
</code>```

What is the syntax to do this? How should the data type for otherButtonTitles be defined?

答:
```<code>UIActionSheet * mediaActionsSheet;
mediaActionSheet = [[UIActionSheet alloc] initWithTitle: nil
                                               delegate: self
                                      cancelButtonTitle: @"Cancel"
                                 destructiveButtonTitle: nil
                                      otherButtonTitles:nil];

if(condition1){

    [mediaActionsSheet addButtonWithTitle:@"Button1"];
    [mediaActionsSheet addButtonWithTitle:@"Button2"];
}
else {

    [mediaActionsSheet addButtonWithTitle:@"Button3"];
    [mediaActionsSheet addButtonWithTitle:@"Button4"];
}
</code>```

Body:
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];

What is the syntax to do this? How should the data type for otherButtonTitles be defined?


问:
Intermittent Lock Wait Timeout Laravel DB Transaction (with 5 retries)
We've been experiencing intermittent lock timeout errors (roughly 1-2 a day out of ~250).

On checkout, we get all of the users details, save the order, process any payments, and then update the order. I think it may be the secondary update that's causing it.

Example of our code (not exactly the same but close enough):

```<code>DB::transaction(function () use ($paymentMethod, $singleUseTokenId, $requiresPayment, $chargeAccount) {
    // create order locally
    $order = Order::create([
        'blah' => $data['blah'],
    ]);

    // handle payment
    $this->handlePayment();

    // update order with new status (with a secondary transaction for safety)
    DB::transaction(function () use ($order) {
        $order->update([
            'status' => 'new status',
        ]);
    }, 5);

}, 5); // Retry transaction 5 times - this reduced the lock timeout errors a lot
</code>```

And the intermittent error we get back is (actual values removed):

```<code>SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction (SQL: insert into `orders` (`user_id`, `customer_uuid`, `type_uuid`, `status_uuid`, `po_number`, `order_details`, `cart_identifier`, `cart_content`, `cart_sub_total`, `cart_tax`, `cart_grand_total`, `payment_type_uuid`, `shipping_address`, `uuid`, `updated_at`, `created_at`)
</code>```

I've read lots up on it and some people say increase timeout (seems like a workaround), optimistic locking (I thought transactions already do that), and other things.

From what I can tell from database breadcrumbs, the order create sometimes takes a long time (eg saw one at 3s, another at 23s for some reason as it's usually 50ms insert), and then the other things happen and it tries to update the order but the row is still locked from the create().

Notes:

We have 4 foreign keys on the orders table (customer uuid, user uuid, order type uuid, order status uuid) - I feel that these may be causing issues.

Some eloquent creates take 3s, others 23s (only checked issue ones). On most orders, request is 500ms max, so these are outliers.

Any suggestions?

Solution: No primary key on orders uuid. Very silly mistake. Caused InnoDB to basically create a 6 byte key for index. And lock up from consecutive insert, then update..

答:
If you see "lock wait timeout" errors look at other transactions. Particularly harmful are long running transactions. You can spot those in SHOW ENGINE INNODB STATUS\G. Climbing InnoDB history list indicates there are ones, too. Currently running long transactions will be listed in information_schema.INNODB_TRX.

Note if a transaction grabbed an exclusive lock it's not released until the end of the transaction, not the end of a query.

First, rule out long running queries. For example, slow UPDATE will hold a lock for its execution time.

After all queries are made reasonably fast, review your transactions. Make them as short as possible. Quite often clients open a transaction, execute a query or two then go to third-party API calls or do other heavy lifting and keep the transaction open. Other transactions meanwhile will be getting "Lock wait timeout".

Body:
We've been experiencing intermittent lock timeout errors (roughly 1-2 a day out of ~250).

On checkout, we get all of the users details, save the order, process any payments, and then update the order. I think it may be the secondary update that's causing it.

Example of our code (not exactly the same but close enough):

DB::transaction(function () use ($paymentMethod, $singleUseTokenId, $requiresPayment, $chargeAccount) {
    // create order locally
    $order = Order::create([
        'blah' => $data['blah'],
    ]);

    // handle payment
    $this->handlePayment();

    // update order with new status (with a secondary transaction for safety)
    DB::transaction(function () use ($order) {
        $order->update([
            'status' => 'new status',
        ]);
    }, 5);

}, 5); // Retry transaction 5 times - this reduced the lock timeout errors a lot

And the intermittent error we get back is (actual values removed):

SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction (SQL: insert into `orders` (`user_id`, `customer_uuid`, `type_uuid`, `status_uuid`, `po_number`, `order_details`, `cart_identifier`, `cart_content`, `cart_sub_total`, `cart_tax`, `cart_grand_total`, `payment_type_uuid`, `shipping_address`, `uuid`, `updated_at`, `created_at`)

I've read lots up on it and some people say increase timeout (seems like a workaround), optimistic locking (I thought transactions already do that), and other things.

From what I can tell from database breadcrumbs, the order create sometimes takes a long time (eg saw one at 3s, another at 23s for some reason as it's usually 50ms insert), and then the other things happen and it tries to update the order but the row is still locked from the create().

Notes:

We have 4 foreign keys on the orders table (customer uuid, user uuid, order type uuid, order status uuid) - I feel that these may be causing issues.

Some eloquent creates take 3s, others 23s (only checked issue ones). On most orders, request is 500ms max, so these are outliers.

Any suggestions?

Solution: No primary key on orders uuid. Very silly mistake. Caused InnoDB to basically create a 6 byte key for index. And lock up from consecutive insert, then update..


问:
Java/Spring: initMocks a class which got @Value from yml file
I am writing unit tests on a Service class like below :

```<code>@Component
@Profile({"default", "dev"})
public class MyService {
    @Value("${my.property}")
    private String property;

    private OtherService otherService;

    public void MyMethod() {
        String myVar = otherService.method();

        return String.format("MyVar %s & MyProperty %s", myVar, property);
    }
}
</code>```

My current test class for this test is like this:

```<code>@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {
    @Mock
    private OtherService otherService;

    @InjectMocks
    private MyService myService;

    @BeforeEach()
    public void init() {
        MockitoAnnotations.initMocks(this);

        when(otherService.method()).thenReturn("a string");
    }

    @Test
    public void shouldReturnException() {
        final Exception exception = assertThrows(ApiErrorException.class,
        () -> myService.myMethod(var));

    assertThat(exception).hasMessage("here the message");

    verify(otherService, never()).method();
    }
}
</code>```

With this two classes, I have an application.yml & application-dev.yml to set my.property.
I want to get the property from the application-dev file during my tests execution.
But, with @InjectMocks, property is null. Whereas, using @Autowired in place of/with @InjectMocks, the property variable is set with the value present in file.

Problem, using Autowired with/in place of InjectMock results in the otherService variable being initialized, so no mock is created.

How can I still use Mockito, while having the property variable set with the value in the file?
I saw about ReflectionTestUtils.setField, but using it mean having no use of a yml file (which i am not fan).

Have a nice day

With the help of @Deadpool, the tests can use the values written in the application.yml file.
But, using @MockBean and @Autowired, the tests get a behavior I do not understand.

Example:
I test that a method return an Exception, and I verify that others methods are not called after the exception was catch: verify(otherService, never()).otherMethod();
Writing this line returns the following error org.mockito.exceptions.verification.NeverWantedButInvoked.

The initial exception is correctly caught, but the test does not seem to acknowledge that no other services must be called.

答:
I suggest you change your MyService class to accept the OtherService either via the constructor or via setter. Something like this:

@Component
@Profile({"default", "dev"})
public class MyService {
    @Value("${my.property}")
    private String property;

    private OtherService otherService;

    public MyService(OtherService otherService) {
        this.otherService = otherService
    }

    public void MyMethod() {
        String myVar = otherService.method();

        return String.format("MyVar %s & MyProperty %s", myVar, property);
    }
}
```

<p>And then you do your test like this:</p>

<pre class="lang-java prettyprint-override"><code>@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {
    @Mock
    private OtherService otherService;

    @InjectMocks
    @Autowired
    private MyService myService;

    @BeforeEach()
    public void init() {
        MockitoAnnotations.initMocks(this);

        when(otherService.method()).thenReturn("a string");
    }
}
</code>```

Body:
I am writing unit tests on a Service class like below :

@Component
@Profile({"default", "dev"})
public class MyService {
    @Value("${my.property}")
    private String property;

    private OtherService otherService;

    public void MyMethod() {
        String myVar = otherService.method();

        return String.format("MyVar %s & MyProperty %s", myVar, property);
    }
}

My current test class for this test is like this:

@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {
    @Mock
    private OtherService otherService;

    @InjectMocks
    private MyService myService;

    @BeforeEach()
    public void init() {
        MockitoAnnotations.initMocks(this);

        when(otherService.method()).thenReturn("a string");
    }

    @Test
    public void shouldReturnException() {
        final Exception exception = assertThrows(ApiErrorException.class,
        () -> myService.myMethod(var));

    assertThat(exception).hasMessage("here the message");

    verify(otherService, never()).method();
    }
}

With this two classes, I have an application.yml & application-dev.yml to set my.property.
I want to get the property from the application-dev file during my tests execution.
But, with @InjectMocks, property is null. Whereas, using @Autowired in place of/with @InjectMocks, the property variable is set with the value present in file.

Problem, using Autowired with/in place of InjectMock results in the otherService variable being initialized, so no mock is created.

How can I still use Mockito, while having the property variable set with the value in the file?
I saw about ReflectionTestUtils.setField, but using it mean having no use of a yml file (which i am not fan).

Have a nice day

With the help of @Deadpool, the tests can use the values written in the application.yml file.
But, using @MockBean and @Autowired, the tests get a behavior I do not understand.

Example:
I test that a method return an Exception, and I verify that others methods are not called after the exception was catch: verify(otherService, never()).otherMethod();
Writing this line returns the following error org.mockito.exceptions.verification.NeverWantedButInvoked.

The initial exception is correctly caught, but the test does not seem to acknowledge that no other services must be called.

Body:
I suggest you change your MyService class to accept the OtherService either via the constructor or via setter. Something like this:

@Component
@Profile({"default", "dev"})
public class MyService {
    @Value("${my.property}")
    private String property;

    private OtherService otherService;

    public MyService(OtherService otherService) {
        this.otherService = otherService
    }

    public void MyMethod() {
        String myVar = otherService.method();

        return String.format("MyVar %s & MyProperty %s", myVar, property);
    }
}

And then you do your test like this:

@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {
    @Mock
    private OtherService otherService;

    @InjectMocks
    @Autowired
    private MyService myService;

    @BeforeEach()
    public void init() {
        MockitoAnnotations.initMocks(this);

        when(otherService.method()).thenReturn("a string");
    }
}


问:
How can i take python self class attributes in class's method?
I started with Python's classes and I want to do something like that:

```<code>class First:
    def __init__(self):
        self.value = 1

    @classmethod
    def func(cls):
        print(self.value)

second = First()
second.func()
</code>```

But i can't access self.value of the class. Can anybody help me?

答:
If you just want to create a function in your class and use self parameters just do that : </p>

```<code>class First:
    def __init__(self):
        self.value = 1

    def func(self):
        print(self.value)

second = First()
second.func()
</code>```

Body:
I started with Python's classes and I want to do something like that:

class First:
    def __init__(self):
        self.value = 1

    @classmethod
    def func(cls):
        print(self.value)

second = First()
second.func()

But i can't access self.value of the class. Can anybody help me?

Body:
If you just want to create a function in your class and use self parameters just do that :

class First:
    def __init__(self):
        self.value = 1

    def func(self):
        print(self.value)

second = First()
second.func()


问:
How can I get sqlite working on a shared hosting server?
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

```
-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
<b>ImportError: No module named _sqlite3</b>
```

I think I have everything set up right as far as the directory structure.

```
-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

```

And finally the contents of the sqlite3 directory:

```
-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

```

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !

答: For python 2.4, you need sqlite and bindings, pysqlite 2 or aspw</p>

Body:
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
ImportError: No module named _sqlite3

I think I have everything set up right as far as the directory structure.

-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

And finally the contents of the sqlite3 directory:

-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !


问:
How to Find Recent or Today’s Modified Files in Linux
I have a requirement that will have to find out latest modified files list along with date and time.
mainly we have 2 files that boot.properties and ldap related files as part of beadmin password change activity.

```<code>find /target_directory -type f -name "*boot.properties" -exec ls -ltr {} \;
</code>```

is giving only boot.properties but I need to find other files which is in different location.

答:
find supports multiple path arguments, so you could do something like

```<code>find /target_dir /other -type f \( -name "*boot.properties" -o -name "other*" \) -exec ls -ltr {} +
</code>```

Body:
I have a requirement that will have to find out latest modified files list along with date and time.
mainly we have 2 files that boot.properties and ldap related files as part of beadmin password change activity.

find /target_directory -type f -name "*boot.properties" -exec ls -ltr {} \;

is giving only boot.properties but I need to find other files which is in different location.

Body:
find supports multiple path arguments, so you could do something like

find /target_dir /other -type f \( -name "*boot.properties" -o -name "other*" \) -exec ls -ltr {} +


问:
In R for group id count days since an event but allow for more than one event per day
```<code># small data set for chess players with player id (p_id), days from some starting date (dayo)
# an Elo rating (elo) and a result win or loss (fin1_0)

p_id <-
c(2232,1877,2210,2073,2232,2232,1877,2210,2073,2232,1877,2210,2073,1877,2232,2210,2073,2210,1877)
dayo <- c(750,750,750,750,751,750,750,750,750,751,751,751,751,751,751,751,762,762,762)
elo <-
c(1741,1841,1651,1561,1751,1741,1841,1651,1561,1751,1851,1551,1951,1820,1660,2230,1762,1762,1762)
fin1_0 <- c(0,1,0,0,1,0,0,0,1,1,0,0,0,1,0,0,1,0,0)

my.df <- data.frame(p_id,elo,dayo,fin1_0)
my.df

# for each player I want to determine the number of games played, the number of wins they achieved
# the day of their last win, how many days since they won a game, how many days since they played a
# game
# and how many games played since they won

# what I tried
library(dplyr)

tbl.df <- my.df %>%
 # first arrange the data based on p_id and dayo
 arrange(p_id, dayo) %>%
 group_by(p_id) %>%
 mutate( games = 1:n(),
         wins = cumsum(fin1_0 == 1) ) %>%
 # group by p_id and every win
 group_by(p_id, wins) %>%
 mutate(last_win_day = min(dayo),
 days_since_win = dayo - first(dayo) ) %>%
 group_by(p_id) %>%
 # replace the first value (or NA) in every group with a random value between 1 and 10
 mutate(days_since_win = replace(days_since_win, row_number() == 1, sample(1:10,1) ),
 days_since_game = dayo -lag(dayo),
 days_since_game = replace_na(days_since_game,sample(1:10,1))) %>%
 group_by(p_id, wins) %>%
 mutate(games_since_win = games - first(games))
 # convert back to a data.frame
 my.df <- data.frame(tbl.df)
 my.df[order(my.df$p_id,my.df$dayo),]
 my.df

# truncated output
   p_id  elo dayo fin1_0 games wins last_win_day days_since_win days_since_game games_since_win
1  1877 1841  750      1     1    1          750             10              10               0
2  1877 1841  750      0     2    1          750              0               0               1
3  1877 1851  751      0     3    1          750              1               1               2
4  1877 1820  751      1     4    2          751              0               0               0
5  1877 1762  762      0     5    2          751             11              11               1
6  2073 1561  750      0     1    0          750              3               7               0
7  2073 1561  750      1     2    1          750              0               0               0
8  2073 1951  751      0     3    1          750              1               1               1
9  2073 1762  762      1     4    2          762              0              11               0

# wanted output
   p_id  elo dayo fin1_0 games wins last_win_day days_since_win days_since_game games_since_win
1  1877 1841  750      1     1    1          750             10              10               0
2  1877 1841  750      0     2    1          750              0               0               0
3  1877 1851  751      0     3    1          750              1               1               1
4  1877 1820  751      1     4    2          751              0               1               0
5  1877 1762  762      0     5    2          751             11              11               11
6  2073 1561  750      0     1    0          750              3               7               0
7  2073 1561  750      1     2    1          750              0               0               0
8  2073 1951  751      0     3    1          750              1               1               1
9  2073 1762  762      1     4    2          762              0              11               0
</code>```

Body:
Here's an approach using case_when to track the last win day for each player. It looks like you want to show zero days since win for the first day of each player, even if they haven't won yet.

my.df %>%
  arrange(p_id, dayo) %>%
  group_by(p_id) %>%
  mutate( games = 1:n(),
          wins = cumsum(fin1_0 == 1)) %>%
  mutate(day_of_last_win = case_when(
    row_number() == 1 ~ dayo,
    fin1_0 == 1       ~ dayo,
    TRUE              ~ lag(dayo)),
         days_since_last_win = dayo - day_of_last_win)

.

# A tibble: 19 x 8
# Groups:   p_id [4]
    p_id   elo  dayo fin1_0 games  wins day_of_last_win days_since_last_win
   <dbl> <dbl> <dbl>  <dbl> <int> <int>           <dbl>               <dbl>
 1  1877  1841   750      1     1     1             750                   0
 2  1877  1841   750      0     2     1             750                   0
 3  1877  1851   751      0     3     1             750                   1
 4  1877  1820   751      1     4     2             751                   0
 5  1877  1762   762      0     5     2             751                  11
 6  2073  1561   750      0     1     0             750                   0
 7  2073  1561   750      1     2     1             750                   0
 8  2073  1951   751      0     3     1             750                   1
 9  2073  1762   762      1     4     2             762                   0
10  2210  1651   750      0     1     0             750                   0
11  2210  1651   750      0     2     0             750                   0
12  2210  1551   751      0     3     0             750                   1
13  2210  2230   751      0     4     0             751                   0
14  2210  1762   762      0     5     0             751                  11
15  2232  1741   750      0     1     0             750                   0
16  2232  1741   750      0     2     0             750                   0
17  2232  1751   751      1     3     1             751                   0
18  2232  1751   751      1     4     2             751                   0
19  2232  1660   751      0     5     2             751                   0