问:
JPA cascade persist - many to one unidirectional
I have a many to one relationship unidirectional and I am trying to persist a child entity i.e. SubscriptionEntity also expect that it should also persist Parent as I am using cascade = CascadeType.PERSIST

Background about relationships : SubscriptionEntity let you know which user is associated with which business and there are few more entity to like state and product which tells us state of subscription and what are the product associated with subscription. Subscription state is one to many bi-directional because subscription can move to many status throughout the membership on-hold, active, deactivate etc.. And similarly Subscription relation with product is one to many bi-directional as user can subscribe for one product or more than one.

We can't do bi-directional association between User and Subscription because user can have association with many businesses.

```<code>    public class SubscriptionEntity implements Domain, Serializable
    {
        @Column(name = "subscription2user")
        @ManyToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
        @JoinColumn(name = "subscription2user")
        private UserEntity user;

        @Column(name = "subscription2biz")
        @ManyToOne(optional = false, fetch = FetchType.LAZY)
        @JoinColumn(name = "subscription2biz")
        private BusinessEntity business;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<ProductSubscriptionEntity> subscribedProducts;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<SubscriptionStateEntity> state;
    }

public class UserEntity implements Domain, Serializable
{
    private static final long serialVersionUID = 755369097357065341L;

    @Id
    @Column(name = "user_id")
    private String id;

    @Column(name = "user_first_name")
    private String firstName;

    @Column(name = "user_last_name")
    private String lastName;

    @Column(name = "user_mobile")
    private BigInteger mobile;

    @Column(name = "user_password")
    private String password;

    @Column(name = "user_create_date")
    private Date createDate;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "user2address")
    @Column(name = "user2address")
    private UserAddressEntity address;
}

public class SubscriptionStateEntity implements Domain, Serializable
{
    @Column(name = "subscription_state2subscription")
    @ManyToOne(optional = false)
    @JoinColumn(name="subscription_state2subscription")
    protected SubscriptionEntity subscription;
}

public class ProductSubscriptionEntity implements Domain, Serializable
{
    @Column(name = "user_product_subscription2subscription")
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "user_product_subscription2subscription")
    private SubscriptionEntity subscription;
}
</code>```

Scenario : Business is already present but User is new, and association between user and subscription is also new. When I am trying to add new subscription getting below error. If User already present in DB then it work smoothly.

```<code>void addSubscription(final UserEntity user, final String businessID)
{
    final UserEntity userTemp = this.userDao.readUserByIdOrMobile(user.getId(), user.getMobile());
    if (null == userTemp)
    {
        user.setId(java.util.UUID.randomUUID().toString());
        user.setCreateDate(DateUtil.getDateTimestamp());
    }
    final BusinessEntity business = getBusinessByID(businessID);
    SubscriptionEntity subscription = new SubscriptionEntity();
    subscription.setUser(user);
    subscription.setBusiness(business);

    super.getEm().persist(subscription);
}
</code>```

Caused by:
  org.apache.openjpa.persistence.EntityExistsException: Cannot add or
  update a child row: a foreign key constraint fails ... ... REFERENCES
  user (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION

Any help much appreciated. Thanks in advance.

答:
You didn't specify any ID for the user entity, since the ID is String, it will create a UserEntity with ID "". Try to add some id generation strategy for the user entity ID, otherwise the newly created user is always the user which will cause this EntityExistsException.

P.s. the bi-directional association just means you can get entities from both sides. It doesn't have anything to do with your business logic.

Body:
I have a many to one relationship unidirectional and I am trying to persist a child entity i.e. SubscriptionEntity also expect that it should also persist Parent as I am using cascade = CascadeType.PERSIST

Background about relationships : SubscriptionEntity let you know which user is associated with which business and there are few more entity to like state and product which tells us state of subscription and what are the product associated with subscription. Subscription state is one to many bi-directional because subscription can move to many status throughout the membership on-hold, active, deactivate etc.. And similarly Subscription relation with product is one to many bi-directional as user can subscribe for one product or more than one.

We can't do bi-directional association between User and Subscription because user can have association with many businesses.

    public class SubscriptionEntity implements Domain, Serializable
    {
        @Column(name = "subscription2user")
        @ManyToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
        @JoinColumn(name = "subscription2user")
        private UserEntity user;

        @Column(name = "subscription2biz")
        @ManyToOne(optional = false, fetch = FetchType.LAZY)
        @JoinColumn(name = "subscription2biz")
        private BusinessEntity business;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<ProductSubscriptionEntity> subscribedProducts;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<SubscriptionStateEntity> state;
    }

public class UserEntity implements Domain, Serializable
{
    private static final long serialVersionUID = 755369097357065341L;

    @Id
    @Column(name = "user_id")
    private String id;

    @Column(name = "user_first_name")
    private String firstName;

    @Column(name = "user_last_name")
    private String lastName;

    @Column(name = "user_mobile")
    private BigInteger mobile;

    @Column(name = "user_password")
    private String password;

    @Column(name = "user_create_date")
    private Date createDate;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "user2address")
    @Column(name = "user2address")
    private UserAddressEntity address;
}

public class SubscriptionStateEntity implements Domain, Serializable
{
    @Column(name = "subscription_state2subscription")
    @ManyToOne(optional = false)
    @JoinColumn(name="subscription_state2subscription")
    protected SubscriptionEntity subscription;
}

public class ProductSubscriptionEntity implements Domain, Serializable
{
    @Column(name = "user_product_subscription2subscription")
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "user_product_subscription2subscription")
    private SubscriptionEntity subscription;
}

Scenario : Business is already present but User is new, and association between user and subscription is also new. When I am trying to add new subscription getting below error. If User already present in DB then it work smoothly.

void addSubscription(final UserEntity user, final String businessID)
{
    final UserEntity userTemp = this.userDao.readUserByIdOrMobile(user.getId(), user.getMobile());
    if (null == userTemp)
    {
        user.setId(java.util.UUID.randomUUID().toString());
        user.setCreateDate(DateUtil.getDateTimestamp());
    }
    final BusinessEntity business = getBusinessByID(businessID);
    SubscriptionEntity subscription = new SubscriptionEntity();
    subscription.setUser(user);
    subscription.setBusiness(business);

    super.getEm().persist(subscription);
}

Caused by:
  org.apache.openjpa.persistence.EntityExistsException: Cannot add or
  update a child row: a foreign key constraint fails ... ... REFERENCES
  user (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION

Any help much appreciated. Thanks in advance.


来源: stackexchange

问:
Passing a Variable from one JS function to another function
I'm using ajax to fetch my data based on some select tags. When I select body part it send a request to sub_parts_ajax() function and does it work perfect and when I select disease type from another select tag which links to disease_name_ajax() where I want the id of last selected in the sub_parts_ajax()

Here is my code:

```<code>    <script type="text/javascript">

 function sub_parts_ajax(id){

    var VAR = {
        myvalue: id
     };

        $.ajax({

            url: 'fetching_parts',
            data: 'id='+id,
            success:function(res){
                //alert(res);
                $("#sub_part").empty();
                $.each(res,function(key,value){
                    $("#sub_part").append('<option value="'+key+'">'+value+'</option>');
                });
            }
        });
    }
</code>```

Second Function

```<code>  function disease_name_ajax(typeid){
</code>```

here I want to alert the value named: myvalue

```<code>alert(VAR.myvalue);

        $.ajax({

            url: 'fetching_names',
            data: 'typeid='+typeid,
            success:function(res){
                //alert(res);
                $("#disease_name").empty();
                $.each(res,function(key,value){
                    $("#disease_name").append('<option value="'+key+'">'+value+'</option>');
                });
            }
        });
    }

</script>
</code>```

答:
Using a Global Variable

```<code>var Myvalue = {};
</code>```

Then Updating it in the function

```<code>function function1(id){
Myvalue.value= id;
}
</code>```

Then you can call it at any function

```<code>function function2(){
alert(Myvalue.value);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using a Global Variable

var Myvalue = {};

Then Updating it in the function

function function1(id){
Myvalue.value= id;
}

Then you can call it at any function

function function2(){
alert(Myvalue.value);
}


问:
Go directly to fragment in Navigation Drawer Android
I have a navigation drawer activity with fragments in it. Now how can I make the app to go directly to a fragment when that activity is opened? I don't want to show the content_main.xml (which is blank):

答:
```<code> @Override
public boolean onNavigationItemSelected(MenuItem item) {

    //calling the method displayselectedscreen and passing the id of selected menu
    displaySelectedScreen(item.getItemId());

    return true;
}
</code>```

private void displaySelectedScreen(int itemId) {

```<code>    //creating fragment object
    Fragment fragment = null;

    //initializing the fragment object which is selected
    switch (itemId) {
        case R.id.nav_menu1:
            fragment = new Menu1();
            break;
        case R.id.nav_menu2:
            fragment = new Menu2();
            break;
        case R.id.nav_menu3:
            fragment = new Menu3();
            break;
    }

    //replacing the fragment
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
}
</code>```

in onCreate()

```<code>DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //add this line to display menu1 when the activity is loaded
    displaySelectedScreen(R.id.nav_menu1);
</code>```

Body:
 @Override
public boolean onNavigationItemSelected(MenuItem item) {

    //calling the method displayselectedscreen and passing the id of selected menu
    displaySelectedScreen(item.getItemId());

    return true;
}

private void displaySelectedScreen(int itemId) {

    //creating fragment object
    Fragment fragment = null;

    //initializing the fragment object which is selected
    switch (itemId) {
        case R.id.nav_menu1:
            fragment = new Menu1();
            break;
        case R.id.nav_menu2:
            fragment = new Menu2();
            break;
        case R.id.nav_menu3:
            fragment = new Menu3();
            break;
    }

    //replacing the fragment
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
}

in onCreate()

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //add this line to display menu1 when the activity is loaded
    displaySelectedScreen(R.id.nav_menu1);


问:
How to install Tomcat 7 as a Windows service using command line install
I need to install Tomcat 7 as a Windows service and to start the service manually.

Referring to How to install Tomcat as a Windows service, I believe I would need to specify the following on the command line:

```<code>tomcat7 //IS//Tomcat7 --DisplayName="Apache Tomcat 7" --Install="C:\Tomcat7\bin\tomcat7.exe
</code>```

Do I also need to specify all or some of the following on the command line like in the example? If only some, please specify which ones. If anything in the example is incorrect, please specify.

```<code>--Jvm=auto
--StartMode=jvm
--StopMode=jvm
--StartClass=org.apache.catalina.startup.Bootstrap
--StartParams=start
--StopClass=org.apache.catalina.startup.Bootstrap
--StopParams=stop
</code>```

What I need for sure is to specify the following because I need to tell Tomcat to use a specific java home and not the java home set by the environment variable JAVA_HOME on the server where this will be installed.

```<code>--JavaHome="C:\Program Files\Java\jdk1.7.0_51
</code>```

The reason: the server already has a different version of Tomcat (5.5) and it uses an older version of the JDK (1.5). I must not change JAVA_HOME on the server. I simply need to ensure Tomcat 7 uses JDK 1.7 and I have tried this line:

```<code>C:\tomcat7\bin>tomcat7 //IS//Tomcat7 --DisplayName="Apache Tomcat 7" --Install="C:\Tomcat7\bin\tomcat7.exe" --JavaHome="C:\Program Files\Java\jdk1.7.0_51"
</code>```

When I attempt to Start the service, the following error message is displayed:

```<code>Windows could not start the Apache Tomcat 7 on Local Computer. For
more information, review the System Event Log. If this is a
non-Microsoft service, contact the service vendor, and refer to
service-specific error code 1.
</code>```

I had a look at the System Event Viewer and it provides the following information:

```<code>The Apache Tomcat 7 service terminated with service-specific error Incorrect function..
</code>```

I need to figure out these steps because I then need to provide the support team with the information to install this service on the production server. So any help would be greatly appreciated!

答:
Use Chocolatey from Powershell command line:

```<code>PS> iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
</code>```

To install Tomcat:

```<code>PS> choco install tomcat
</code>```

To upgrade:

```<code>PS> choco upgrade tomcat
</code>```

Body:
I need to install Tomcat 7 as a Windows service and to start the service manually.

Referring to How to install Tomcat as a Windows service, I believe I would need to specify the following on the command line:

tomcat7 //IS//Tomcat7 --DisplayName="Apache Tomcat 7" --Install="C:\Tomcat7\bin\tomcat7.exe

Do I also need to specify all or some of the following on the command line like in the example? If only some, please specify which ones. If anything in the example is incorrect, please specify.

--Jvm=auto
--StartMode=jvm
--StopMode=jvm
--StartClass=org.apache.catalina.startup.Bootstrap
--StartParams=start
--StopClass=org.apache.catalina.startup.Bootstrap
--StopParams=stop

What I need for sure is to specify the following because I need to tell Tomcat to use a specific java home and not the java home set by the environment variable JAVA_HOME on the server where this will be installed.

--JavaHome="C:\Program Files\Java\jdk1.7.0_51

The reason: the server already has a different version of Tomcat (5.5) and it uses an older version of the JDK (1.5). I must not change JAVA_HOME on the server. I simply need to ensure Tomcat 7 uses JDK 1.7 and I have tried this line:

C:\tomcat7\bin>tomcat7 //IS//Tomcat7 --DisplayName="Apache Tomcat 7" --Install="C:\Tomcat7\bin\tomcat7.exe" --JavaHome="C:\Program Files\Java\jdk1.7.0_51"

When I attempt to Start the service, the following error message is displayed:

Windows could not start the Apache Tomcat 7 on Local Computer. For
more information, review the System Event Log. If this is a
non-Microsoft service, contact the service vendor, and refer to
service-specific error code 1.

I had a look at the System Event Viewer and it provides the following information:

The Apache Tomcat 7 service terminated with service-specific error Incorrect function..

I need to figure out these steps because I then need to provide the support team with the information to install this service on the production server. So any help would be greatly appreciated!

Body:
Use Chocolatey from Powershell command line:

PS> iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))

To install Tomcat:

PS> choco install tomcat

To upgrade:

PS> choco upgrade tomcat


问:
Custom Memory Allocator Example (Need some clarification)
Just running through this example of a custom memory allocator header file and I was just wanting to understand some of the written code better.

```<code>class Allocator
{
public:
    Allocator(size_t size, void* start)
    {
        _start          = start;
        _size           = size;

        _used_memory     = 0;
        _num_allocations = 0;
    }

    virtual ~Allocator()
    {
        ASSERT(_num_allocations == 0 && _used_memory == 0);

        _start = nullptr;
        _size   = 0;
    }

    virtual void* allocate(size_t size, u8 alignment = 4) = 0;

    virtual void deallocate(void* p) = 0;

    void* getStart() const
    {
        return _start;
    }

    size_t getSize() const
    {
        return _size;
    }

    size_t getUsedMemory() const
    {
        return _used_memory;
    }

    size_t getNumAllocations() const
    {
        return _num_allocations;
    }

protected:
    void*         _start;
    size_t        _size;

    size_t        _used_memory;
    size_t        _num_allocations;
};

namespace allocator
{
    template <class T> T* allocateNew(Allocator& allocator)
    {
        return new (allocator.allocate(sizeof(T), __alignof(T))) T;
    }

    template <class T> T* allocateNew(Allocator& allocator, const T& t)
    {
        return new (allocator.allocate(sizeof(T), __alignof(T))) T(t);
    }

    template<class T> void deallocateDelete(Allocator& allocator, T& object)
    {
        object.~T();
        allocator.deallocate(&object);
    }

    template<class T> T* allocateArray(Allocator& allocator, size_t length)
    {
        ASSERT(length != 0);

        u8 headerSize = sizeof(size_t)/sizeof(T);

        if(sizeof(size_t)%sizeof(T) > 0)
            headerSize += 1;

        //Allocate extra space to store array length in the bytes before the array
        T* p = ( (T*) allocator.allocate(sizeof(T)*(length + headerSize), __alignof(T)) ) + headerSize;

        *( ((size_t*)p) - 1 ) = length;

        for(size_t i = 0; i < length; i++)
            new (&p[i]) T;

        return p;
    }

    template<class T> void deallocateArray(Allocator& allocator, T* array)
    {
        ASSERT(array != nullptr);

        size_t length = *( ((size_t*)array) - 1 );

        for(size_t i = 0; i < length; i++)
            array[i].~T();

        //Calculate how much extra memory was allocated to store the length before the array
        u8 headerSize = sizeof(size_t)/sizeof(T);

        if(sizeof(size_t)%sizeof(T) > 0)
            headerSize += 1;

        allocator.deallocate(array - headerSize);
    }
};
</code>```

Why is the start parameter needed/used here? If I wanted to allocate some space don't I just need to specify how much memory I need to allocate?

If I wanted to just create a simple linear custom memory allocater, would I still need to include the first two templates?

For this snippet new (&p[i]) T; why is the template type name at the end?

Thanks!

答:
1) start stores the pointer to a "really" allocated memory that is being allocated by this allocator and later needs to be passed to corresponding free function.

2) i think it would be better to write your allocator from scratch

3) this expression is a placement new operator invocation and &p[i] is an address where an object of type T will be constructed

Body:
Just running through this example of a custom memory allocator header file and I was just wanting to understand some of the written code better.

class Allocator
{
public:
    Allocator(size_t size, void* start)
    {
        _start          = start;
        _size           = size;

        _used_memory     = 0;
        _num_allocations = 0;
    }

    virtual ~Allocator()
    {
        ASSERT(_num_allocations == 0 && _used_memory == 0);

        _start = nullptr;
        _size   = 0;
    }

    virtual void* allocate(size_t size, u8 alignment = 4) = 0;

    virtual void deallocate(void* p) = 0;

    void* getStart() const
    {
        return _start;
    }

    size_t getSize() const
    {
        return _size;
    }

    size_t getUsedMemory() const
    {
        return _used_memory;
    }

    size_t getNumAllocations() const
    {
        return _num_allocations;
    }

protected:
    void*         _start;
    size_t        _size;

    size_t        _used_memory;
    size_t        _num_allocations;
};

namespace allocator
{
    template <class T> T* allocateNew(Allocator& allocator)
    {
        return new (allocator.allocate(sizeof(T), __alignof(T))) T;
    }

    template <class T> T* allocateNew(Allocator& allocator, const T& t)
    {
        return new (allocator.allocate(sizeof(T), __alignof(T))) T(t);
    }

    template<class T> void deallocateDelete(Allocator& allocator, T& object)
    {
        object.~T();
        allocator.deallocate(&object);
    }

    template<class T> T* allocateArray(Allocator& allocator, size_t length)
    {
        ASSERT(length != 0);

        u8 headerSize = sizeof(size_t)/sizeof(T);

        if(sizeof(size_t)%sizeof(T) > 0)
            headerSize += 1;

        //Allocate extra space to store array length in the bytes before the array
        T* p = ( (T*) allocator.allocate(sizeof(T)*(length + headerSize), __alignof(T)) ) + headerSize;

        *( ((size_t*)p) - 1 ) = length;

        for(size_t i = 0; i < length; i++)
            new (&p[i]) T;

        return p;
    }

    template<class T> void deallocateArray(Allocator& allocator, T* array)
    {
        ASSERT(array != nullptr);

        size_t length = *( ((size_t*)array) - 1 );

        for(size_t i = 0; i < length; i++)
            array[i].~T();

        //Calculate how much extra memory was allocated to store the length before the array
        u8 headerSize = sizeof(size_t)/sizeof(T);

        if(sizeof(size_t)%sizeof(T) > 0)
            headerSize += 1;

        allocator.deallocate(array - headerSize);
    }
};

Why is the start parameter needed/used here? If I wanted to allocate some space don't I just need to specify how much memory I need to allocate?

If I wanted to just create a simple linear custom memory allocater, would I still need to include the first two templates?

For this snippet new (&p[i]) T; why is the template type name at the end?

Thanks!


问:
date_diff() expects parameter 2 to be DateTimeInterface, string given
when i am trying to execute this getting error like   date_diff() expects parameter 2 to be DateTimeInterface, string given        </p>

```<code>    $date2=date_create("2017-03-15");
    date_format($date2,"Y/m/d");
    $date1=date('Y/m/d');
    $diff=date_diff($date2,$date1);
    echo $diff;
</code>```

答:
Both variables should be in the same format. Just try this:</p>

```<code>$date2=date_create("2017-03-15");
$date1=date_create(date('Y-m-d'));
$diff=date_diff($date2,$date1);
echo $diff->days;
</code>```

Body:
when i am trying to execute this getting error like   date_diff() expects parameter 2 to be DateTimeInterface, string given

    $date2=date_create("2017-03-15");
    date_format($date2,"Y/m/d");
    $date1=date('Y/m/d');
    $diff=date_diff($date2,$date1);
    echo $diff;

Body:
Both variables should be in the same format. Just try this:

$date2=date_create("2017-03-15");
$date1=date_create(date('Y-m-d'));
$diff=date_diff($date2,$date1);
echo $diff->days;


问:
I am creating the textView Dynamically
I want to set the hello text in center after completion of running the code as  I am creating the text view dynamically. </p>

```<code>TextView textView;
private TextView createNewTextView(String text) {
     textView = new TextView(this)
     textView.setText(" hello ");
     textView.setGravity(Gravity.CENTER_HORIZONTAL);
}
</code>```

答:
Try the below code:</p>

```<code>LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,              LinearLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(LinearLayout.CENTER_IN_PARENT);
textView.setLayoutParams(lp);
</code>```

Title: I am creating the textView Dynamically

Body:
I want to set the hello text in center after completion of running the code as  I am creating the text view dynamically.

TextView textView;
private TextView createNewTextView(String text) {
     textView = new TextView(this)
     textView.setText(" hello ");
     textView.setGravity(Gravity.CENTER_HORIZONTAL);
}

Body:
Try the below code:

LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,              LinearLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(LinearLayout.CENTER_IN_PARENT);
textView.setLayoutParams(lp);


问:
SLF4J+Logback to create a file if doesn't exists/ if deleted
I have been researching for this for a long time and doesn't get a solution at all. My requirement is to create a log file if it is not there at the place.
Below is my logback.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>

<property name="LOG_PATH" value="/home/logs" />

<appender name="FILE-AUDIT"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/debug.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %p\t%d{dd MMM yyyy HH:mm:ss,SSS}\t%r\t%c\t[--%t--]\t%m%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <fileNamePattern>${LOG_PATH}/debug.%d{yyyy-MM-dd}.%i.log
                    </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>

</appender>

<logger name="com.example" level="debug"
    additivity="false">
    <appender-ref ref="FILE-AUDIT" />
</logger>

<root level="debug">
    <appender-ref ref="FILE-AUDIT" />
</root>

</configuration>
</code>```

And I have tried changing the configuration to configuration debug="true", but no luck.
What is the right way to implement this ?

Please don't write to check on file permissions or ask me to use Log4j, I changed my application to use slf4j instead of log4j. If i delete the file also, it should create

答:
You should use ch.qos.logback.core.FileAppender for file appending.

```<code><appender name="File-Appender" class="ch.qos.logback.core.FileAppender">
        <file>${LOG_PATH}/logfile-${timestamp-by-second}.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
</appender>
</code>```

Body:
I have been researching for this for a long time and doesn't get a solution at all. My requirement is to create a log file if it is not there at the place.
Below is my logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

<property name="LOG_PATH" value="/home/logs" />

<appender name="FILE-AUDIT"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/debug.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %p\t%d{dd MMM yyyy HH:mm:ss,SSS}\t%r\t%c\t[--%t--]\t%m%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

        <fileNamePattern>${LOG_PATH}/debug.%d{yyyy-MM-dd}.%i.log
                    </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>

</appender>

<logger name="com.example" level="debug"
    additivity="false">
    <appender-ref ref="FILE-AUDIT" />
</logger>

<root level="debug">
    <appender-ref ref="FILE-AUDIT" />
</root>

</configuration>

And I have tried changing the configuration to configuration debug="true", but no luck.
What is the right way to implement this ?

Please don't write to check on file permissions or ask me to use Log4j, I changed my application to use slf4j instead of log4j. If i delete the file also, it should create

Body:
You should use ch.qos.logback.core.FileAppender for file appending.

<appender name="File-Appender" class="ch.qos.logback.core.FileAppender">
        <file>${LOG_PATH}/logfile-${timestamp-by-second}.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
</appender>


问:
Displaying % in Batch (Windows 10 Command Prompt)
I am writing a batch program that has a loading screen, because it has a lot of files to load,  anyway, I was trying to get it to display:

```<code>0%
</code>```

after runing the program, it only displayed:

```<code>0
</code>```

Any advice or solutions would help,
Thanks!

答:
You should escape this special character by adding %

@echo off
echo 0%%
pause>nul
```

for more info about escaping characters take a look at this link : Escape Characters

Body:
I am writing a batch program that has a loading screen, because it has a lot of files to load,  anyway, I was trying to get it to display:

0%

after runing the program, it only displayed:

0

Any advice or solutions would help,
Thanks!

Body:
You should escape this special character by adding %

@echo off
echo 0%%
pause>nul

for more info about escaping characters take a look at this link : Escape Characters


问:
How to save python Errors (stderr) to a log file ONLY in case errors actually happen?
I have a python script that runs once a minute. For debugging, I want to create text files with errors/exceptions in case they occur. In case errors are absent, I don't want any log files.

EDIT: I can't wrap all my code in a try/except loop, so this doesn't help.

First, I am saving stderr to .txt doing:

```<code>sys.stderr = open('ERRORS_%s.txt' % (infile), 'a')
with open("%s_Error_Messages.txt" % (MSKSN), "a") as myfile:
    myfile.close()
</code>```

Second, I then try to delete empty "%s_Error_Messages.txt" % (MSKSN) files before any raise SystemExit positions since no error was raised (otherwise, the raise SystemExit position would not have been reached).

```<code>if os.path.getsize('ERRORS_%s.txt' % (infile)) == 0:
    os.remove('ERRORS_%s.txt' % (infile))
</code>```

What I get is WindowsError: [Error 32] The process cannot access the file because it is being used by another process. I assume that this is because stderr is always in use by python.exe as long as the script runs.

For the first step, I also tried:

```<code>if sys.stderr != 0:
   sys.stderr = open('ERRORS_%s.txt' % (infile), 'a')
</code>```

Which does not work since sys.stderr is never 0.

How to write sys.stderr to .txt only in case of actual errors?

答:
Unless you have a huge volume of error data to worry about, you can just redirect stderr into a stringIO object and then write it out (or not) depending on contents

```<code>import StringIO
import sys

sys.stderr = StringIO.StringIO()
# do stuff
if sys.stderr.getvalue():
   with open ("path/to/log.txt") as output:
        output.write(sys.stderr.getvalue())
</code>```

This is a great case for a context manager that will set the replacement stderr, run your code, then reset stderr back to sys.__stderr__ when done.

If you can't wrap the code in a try, you could also try setting this functionality using sys.excepthook

Body:
I have a python script that runs once a minute. For debugging, I want to create text files with errors/exceptions in case they occur. In case errors are absent, I don't want any log files.

EDIT: I can't wrap all my code in a try/except loop, so this doesn't help.

First, I am saving stderr to .txt doing:

sys.stderr = open('ERRORS_%s.txt' % (infile), 'a')
with open("%s_Error_Messages.txt" % (MSKSN), "a") as myfile:
    myfile.close()

Second, I then try to delete empty "%s_Error_Messages.txt" % (MSKSN) files before any raise SystemExit positions since no error was raised (otherwise, the raise SystemExit position would not have been reached).

if os.path.getsize('ERRORS_%s.txt' % (infile)) == 0:
    os.remove('ERRORS_%s.txt' % (infile))

What I get is WindowsError: [Error 32] The process cannot access the file because it is being used by another process. I assume that this is because stderr is always in use by python.exe as long as the script runs.

For the first step, I also tried:

if sys.stderr != 0:
   sys.stderr = open('ERRORS_%s.txt' % (infile), 'a')

Which does not work since sys.stderr is never 0.

How to write sys.stderr to .txt only in case of actual errors?

Body:
Unless you have a huge volume of error data to worry about, you can just redirect stderr into a stringIO object and then write it out (or not) depending on contents

import StringIO
import sys

sys.stderr = StringIO.StringIO()
# do stuff
if sys.stderr.getvalue():
   with open ("path/to/log.txt") as output:
        output.write(sys.stderr.getvalue())

This is a great case for a context manager that will set the replacement stderr, run your code, then reset stderr back to sys.__stderr__ when done.

If you can't wrap the code in a try, you could also try setting this functionality using sys.excepthook


问:
How to learn to write idiomatic c++ code
I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually considered non-idiomatic and superseded by an STL way to do it that is safer and easier (well, the book doesn't cover STL and Boost libraries).

So I'd like to ask: what are good sources to learn the patterns of a good C++ program? Where can I learn basic patterns from the "C++ way" to do things and not just repeating C patterns in C++?

I'd be particularly interested in sources that included STL and Boost stuff.

答: Since you have completed the Herbert Schildt book, you can read the book by the Bjarne Stroustrup (The C++ Programming Language) or Bruce Eckel's book (Thinking in C++ Part 1 & Part 2). The Eckel's book is freely available on the internet and Part-2 talks about STL.</p>

ContentLicense: CC BY-SA 2.5


问:
VB.NET - Fill Specific Column DataGridView from Another Column
i have 2 DGV name dataListBarang and dataListTransaksi, i'm trying to fill dataListTransaksi spesific column called nama_barang from specific column in dataListBarang called nm_barang

my code so far

```<code>Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
        If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
            namaBarang = Me.dataListBarang.CurrentRow.Cells(0).Value.ToString
            dataListTransaksi.Columns(1).DataPropertyName = namaBarang
        End If
        dataListBarang.Refresh()
    End Sub
</code>```

when i double click on DGV dataListBarang, column nama_barang (on dataListTransaksi) will filled with value from column nm_barang on DGV dataListBarang, but its not working.

please help.

EDIT
what i'm trying to do is copy cell from current row when user double click on it then fill the first row on second DataGrid (dataGrid has columns with no data in it) in specific column.

note:

see the left dataGrid has data and the right dataGrid is empty

see the number!, when user double click, the value from 1 is copied to number 2

most of column in right dataGrid is manually input (except Nama Barang) and save to database

答:
i modified my code based on answer by @JhonG

```<code> Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
        Dim row As Integer = e.RowIndex
        Dim col As Integer = e.ColumnIndex
        namaBarang = Me.dataListBarang.CurrentRow.Cells(0).Value.ToString
        If (col = 0) Then

            If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
                dataListTransaksi.Rows.Add("", namaBarang)
                'hargaBarang = Me.dataListBarang
                'Me.dataListTransaksi.CurrentRow.Cells(1).Value = namaBarang
            End If
        End If
</code>```

when i double click in firstDataGrid it copy the value to another dataGrid and add new row.

Body:
i have 2 DGV name dataListBarang and dataListTransaksi, i'm trying to fill dataListTransaksi spesific column called nama_barang from specific column in dataListBarang called nm_barang

my code so far

Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
        If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
            namaBarang = Me.dataListBarang.CurrentRow.Cells(0).Value.ToString
            dataListTransaksi.Columns(1).DataPropertyName = namaBarang
        End If
        dataListBarang.Refresh()
    End Sub

when i double click on DGV dataListBarang, column nama_barang (on dataListTransaksi) will filled with value from column nm_barang on DGV dataListBarang, but its not working.

please help.

EDIT
what i'm trying to do is copy cell from current row when user double click on it then fill the first row on second DataGrid (dataGrid has columns with no data in it) in specific column.

note:

see the left dataGrid has data and the right dataGrid is empty

see the number!, when user double click, the value from 1 is copied to number 2

most of column in right dataGrid is manually input (except Nama Barang) and save to database

Body:
i modified my code based on answer by @JhonG

 Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
        Dim row As Integer = e.RowIndex
        Dim col As Integer = e.ColumnIndex
        namaBarang = Me.dataListBarang.CurrentRow.Cells(0).Value.ToString
        If (col = 0) Then

            If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
                dataListTransaksi.Rows.Add("", namaBarang)
                'hargaBarang = Me.dataListBarang
                'Me.dataListTransaksi.CurrentRow.Cells(1).Value = namaBarang
            End If
        End If

when i double click in firstDataGrid it copy the value to another dataGrid and add new row.


问:
JAXB unmarshalling without XmlRootElement annotation?
Is there any way we can un-marshall for a class without @XmlRootElement annotation? Or are we obligated to enter the annotation?

for example:

```<code>public class Customer {

    private String name;
    private int age;
    private int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
</code>```

and let the unmarshalling code for properly annotated class  be like:

```<code>try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
        System.out.println(customer);

      } catch (JAXBException e) {
        e.printStackTrace();
      }
</code>```

leaving out the details.

答:
If you cannot add XmlRootElement to existing bean you can also create a holder class and mark it with annotation as XmlRootElement. Example below:- </p>

```<code>import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerHolder
{
    private Customer cusotmer;

    public Customer getCusotmer() {
        return cusotmer;
}

    public void setCusotmer(Customer cusotmer) {
        this.cusotmer = cusotmer;
    }
}
</code>```

Body:
Is there any way we can un-marshall for a class without @XmlRootElement annotation? Or are we obligated to enter the annotation?

for example:

public class Customer {

    private String name;
    private int age;
    private int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

and let the unmarshalling code for properly annotated class  be like:

try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
        System.out.println(customer);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

leaving out the details.

Body:
If you cannot add XmlRootElement to existing bean you can also create a holder class and mark it with annotation as XmlRootElement. Example below:-

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerHolder
{
    private Customer cusotmer;

    public Customer getCusotmer() {
        return cusotmer;
}

    public void setCusotmer(Customer cusotmer) {
        this.cusotmer = cusotmer;
    }
}


问:
Two Class member mapping into new Final class
Note this is not multi-threading case Old value is saved in cache, new value is getting from server and final value is updated-one which will save again in cache.

Their two object of class name

obj->Old values,

obj1-> New values.

Recquried

obj3-> Final Output.

Old Values

```<code>class A{
 String name="abc";
String email="x@gmail.com";
String phone="123456789";
}
</code>```

New Values

```<code>class A{
 String name="xyz";
String email="";
}
</code>```

Want to update old values with new values only when their is some updated content in new values.

As in above case

name is accepted as it changes

email is not accepted as it is empty.

Phone has no value so rejected.

Final output is:

```<code>class A
{
  String name="xyz";
    String email="x@gmail.com";
    String phone="123456789";
}
</code>```

Is their any easy solution to make it simple

答:
Have you tried by defining a subclass of the BeanUtilsBean of the org.commons.beanutils package? Actually, BeanUtils uses this class.

Checking at the source code of that class, I think you can overwrite the copyProperty method, by checking for null values and doing nothing if the value is null.

Something like this :

```<code>package foo.bar.copy;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtilsBean;

public class NullAwareBeanUtilsBean extends BeanUtilsBean{

    @Override
    public void copyProperty(Object dest, String name, Object value)
            throws IllegalAccessException, InvocationTargetException {
    if(value==null || StringUtils.isEmpty(ObjectUtils.identityToString(value))) {
      return;
     }
        super.copyProperty(dest, name, value);
    }

}
</code>```

Then you can just instantiate a NullAwareBeanUtilsBean and use it to copy your beans, for example:

```<code>BeanUtilsBean checkNullAnd=new NullAwareBeanUtilsBean();
checkNullAnd.copyProperties(dest, orig);
</code>```

So, All this code will do is, it will check for null or Empty objects and not replace them with the old one.

ref : here

Body:
Note this is not multi-threading case Old value is saved in cache, new value is getting from server and final value is updated-one which will save again in cache.

Their two object of class name

obj->Old values,

obj1-> New values.

Recquried

obj3-> Final Output.

Old Values

class A{
 String name="abc";
String email="x@gmail.com";
String phone="123456789";
}

New Values

class A{
 String name="xyz";
String email="";
}

Want to update old values with new values only when their is some updated content in new values.

As in above case

name is accepted as it changes

email is not accepted as it is empty.

Phone has no value so rejected.

Final output is:

class A
{
  String name="xyz";
    String email="x@gmail.com";
    String phone="123456789";
}

Is their any easy solution to make it simple

Body:
Have you tried by defining a subclass of the BeanUtilsBean of the org.commons.beanutils package? Actually, BeanUtils uses this class.

Checking at the source code of that class, I think you can overwrite the copyProperty method, by checking for null values and doing nothing if the value is null.

Something like this :

package foo.bar.copy;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtilsBean;

public class NullAwareBeanUtilsBean extends BeanUtilsBean{

    @Override
    public void copyProperty(Object dest, String name, Object value)
            throws IllegalAccessException, InvocationTargetException {
    if(value==null || StringUtils.isEmpty(ObjectUtils.identityToString(value))) {
      return;
     }
        super.copyProperty(dest, name, value);
    }

}

Then you can just instantiate a NullAwareBeanUtilsBean and use it to copy your beans, for example:

BeanUtilsBean checkNullAnd=new NullAwareBeanUtilsBean();
checkNullAnd.copyProperties(dest, orig);

So, All this code will do is, it will check for null or Empty objects and not replace them with the old one.

ref : here


问:
Take input hours mins secs from user and start a countdown in hh:mm:ss format
I am facing problem in starting timer and how to place data into date.

This is my code:

```<code>Calendar cl = Calendar.getInstance();
cl.set(Calendar.HOUR, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.add(Calendar.HOUR, hr);
cl.add(Calendar.MINUTE, min);
cl.add(Calendar.SECOND, sec);
Date date = cl.getTime();
Timer t =new Timer(1000, new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent ae) {
     SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
     jLabel2.setText(timeFormat.format(date));
  }
});
t.start();
</code>```

Is it correct to use Calendar to place data in date and start timer?

答:
I don’t think you should use a Calendar for this. A Calendar is meant for representing a point in calendar time, not a duration in hours, minutes and seconds. Also, Calendar is old stuff now and replaced by new and more programmer friendly classes in Java 8 (see the java.time package).

I understand from the comments that you want a count-down timer. I suggest:

```<code>    Timer t = new Timer(1000, new ActionListener() {
        Duration time = Duration.ofHours(hr).plusMinutes(min).plusSeconds(sec);
        @Override
        public void actionPerformed(ActionEvent ae) {
            time = time.minusSeconds(1);
            jLabel2.setText(formatDuration(time));
        }
    });
    t.start();
</code>```

I am using the Duration class, one of the classes introduced in Java 8. It is designed for a duration in hours, minutes and seconds, so this is what we need for the job. It doesn’t lend itself well to formatting, though. You may use its toString method, it will give you a string like PT9M52S for 9 minutes 52 seconds, probably not what most users find most intuituve. Instead I am using this auxiliary method for formatting:

```<code>static String formatDuration(Duration dur) {
    long hr = dur.toHours();
    Duration remainder = dur.minusHours(hr);
    long min = remainder.toMinutes();
    long sec = remainder.minusMinutes(min).getSeconds();
    return String.format("%02d:%02d:%02d", hr, min, sec);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am facing problem in starting timer and how to place data into date.

This is my code:

Calendar cl = Calendar.getInstance();
cl.set(Calendar.HOUR, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.add(Calendar.HOUR, hr);
cl.add(Calendar.MINUTE, min);
cl.add(Calendar.SECOND, sec);
Date date = cl.getTime();
Timer t =new Timer(1000, new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent ae) {
     SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
     jLabel2.setText(timeFormat.format(date));
  }
});
t.start();

Is it correct to use Calendar to place data in date and start timer?

Body:
I don’t think you should use a Calendar for this. A Calendar is meant for representing a point in calendar time, not a duration in hours, minutes and seconds. Also, Calendar is old stuff now and replaced by new and more programmer friendly classes in Java 8 (see the java.time package).

I understand from the comments that you want a count-down timer. I suggest:

    Timer t = new Timer(1000, new ActionListener() {
        Duration time = Duration.ofHours(hr).plusMinutes(min).plusSeconds(sec);
        @Override
        public void actionPerformed(ActionEvent ae) {
            time = time.minusSeconds(1);
            jLabel2.setText(formatDuration(time));
        }
    });
    t.start();

I am using the Duration class, one of the classes introduced in Java 8. It is designed for a duration in hours, minutes and seconds, so this is what we need for the job. It doesn’t lend itself well to formatting, though. You may use its toString method, it will give you a string like PT9M52S for 9 minutes 52 seconds, probably not what most users find most intuituve. Instead I am using this auxiliary method for formatting:

static String formatDuration(Duration dur) {
    long hr = dur.toHours();
    Duration remainder = dur.minusHours(hr);
    long min = remainder.toMinutes();
    long sec = remainder.minusMinutes(min).getSeconds();
    return String.format("%02d:%02d:%02d", hr, min, sec);
}


问:
Selenium 3: How to open link in new tab and visible it
Hi
 I want open a link in original page to new tab.

 i used code
 driver.findElement(locator).sendKeys(Keys.chord(Keys.CONTROL,Keys.RETURN));

 I tryed use driver.switchTo() but tab is not visible.
 here code

```<code> ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
if(tabs.size() > 1 ){
    driver.switchTo().window(tabs.get(1));
}
</code>```

I try use

Actions.sendKey(Keys.CONTROL + "1")

  or

  Actions.sendKey(Keys.chord(Keys.CONTROL + Keys.TAB))

But it is not happen

But my problem is when do some actions on pages in new tab. these are throw error. because tab is not visible.

 **How to set new tab is visible **

I use selenium 3 and Java

答:
Try this:</p>

```<code>Iterator<String> popwindow = driver.getWindowHandles().iterator();
while (popwindow.hasNext()) {
    String window = popwindow.next();
    if (!mainwindow.equals(window)) {
        writeConsole(" Switch To Window["+window+"]");
        driver.switchTo().window(window);
    }
}
</code>```

Body:
Hi
 I want open a link in original page to new tab.

 i used code
 driver.findElement(locator).sendKeys(Keys.chord(Keys.CONTROL,Keys.RETURN));

 I tryed use driver.switchTo() but tab is not visible.
 here code

 ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
if(tabs.size() > 1 ){
    driver.switchTo().window(tabs.get(1));
}

I try use

Actions.sendKey(Keys.CONTROL + "1")

  or

  Actions.sendKey(Keys.chord(Keys.CONTROL + Keys.TAB))

But it is not happen

But my problem is when do some actions on pages in new tab. these are throw error. because tab is not visible.

 **How to set new tab is visible **

I use selenium 3 and Java

Body:
Try this:

Iterator<String> popwindow = driver.getWindowHandles().iterator();
while (popwindow.hasNext()) {
    String window = popwindow.next();
    if (!mainwindow.equals(window)) {
        writeConsole(" Switch To Window["+window+"]");
        driver.switchTo().window(window);
    }
}


问:
How wp_mail() is more secure than mail()
I have a plugin in WP which I am going to modify. At some point I have to send an email and I have the option to choose between wp_mail and mail.
I decided for the first one, at least it seems plugged in the WordPress environment. Even if I read the documentation, I can't understand how it could protect me more than mail. But a reason has to be there.

In general, may i consider the script safe if I am sending email by using wp_mail within a plugin with the parameters to, subject, body, header, "-f info@mdomain.com" ?
Are there best practices to make this function safer?
My concern is that for whatever reason the WP installation could be hacked and this script used to send unsolicited emails.

Regards
Fabio

答:
who told you that wp_mail is more secure than mail ?

mail is an internal php function

while wp_mail is often use mail function with more options to make it easier to send an emails using wordpress instead of re-implement new implementation to a mail object.

wp_mail uses PHPMailer class, which is using by default mail function.

```<code>/**
 * Which method to use to send mail.
 * Options: "mail", "sendmail", or "smtp".
 * @var string
 */
public $Mailer = 'mail';
</code>```

however, if you took a quick look in the implementation of wordpress wp_mail function , you will notice a poor implementation , they still using global variables which is considered as a poor practice .

Body:
who told you that wp_mail is more secure than mail ?

mail is an internal php function

while wp_mail is often use mail function with more options to make it easier to send an emails using wordpress instead of re-implement new implementation to a mail object.

wp_mail uses PHPMailer class, which is using by default mail function.

/**
 * Which method to use to send mail.
 * Options: "mail", "sendmail", or "smtp".
 * @var string
 */
public $Mailer = 'mail';

however, if you took a quick look in the implementation of wordpress wp_mail function , you will notice a poor implementation , they still using global variables which is considered as a poor practice .


问:
Linq using how to use order by and group by with left join?
I have written this query in linq using left join and using group by and order by. I have 2 tables, student and course. So i am grouping on student table after I am not getting any columns in course so how can I order by on course table in datetime column.

tablestudent :

id,name,std

tablecourse :

id,userid,datetime

This is my query :

```<code> var res = (from u in db.student
              join c in db.course on u.id equals c.userid into j1
              from j2 in j1.DefaultIfEmpty()
              group j2 by u.id into g
              orderby g.Key.datatime descending    // here i'm getting datetime does not contain.
              select new { id = g.key }).tolist(); // here i just want id not getting any other column.
</code>```

If anyone knows how to do that, please help.

答:
What about this one

```<code>   var query =db.course.GroupBy(c => c.UserId)
             .Select(g => g.OrderByDescending(c => c.datetime).FirstOrDefault());
        var res = (from u in db.student
              join c in query on u.id equals c.userid into j1
              from j2 in j1.DefaultIfEmpty()
              select new {   u.name,j2}).ToList();
</code>```

Working fiddle

Body:
I have written this query in linq using left join and using group by and order by. I have 2 tables, student and course. So i am grouping on student table after I am not getting any columns in course so how can I order by on course table in datetime column.

tablestudent :

id,name,std

tablecourse :

id,userid,datetime

This is my query :

 var res = (from u in db.student
              join c in db.course on u.id equals c.userid into j1
              from j2 in j1.DefaultIfEmpty()
              group j2 by u.id into g
              orderby g.Key.datatime descending    // here i'm getting datetime does not contain.
              select new { id = g.key }).tolist(); // here i just want id not getting any other column.

If anyone knows how to do that, please help.

Body:
What about this one

   var query =db.course.GroupBy(c => c.UserId)
             .Select(g => g.OrderByDescending(c => c.datetime).FirstOrDefault());
        var res = (from u in db.student
              join c in query on u.id equals c.userid into j1
              from j2 in j1.DefaultIfEmpty()
              select new {   u.name,j2}).ToList();

Working fiddle


问:
jquery select2 refresh data
I using select2 to select and ajax to load data, how can I replace old data when the state is changed after initial selection.

My loading code:

```<code>$('.datetimepicker').on("changeDate", function() {
        //refresh selectbox ??
        doctor_id = $(".select2-doctors").val();
        clinic_id = $(".select2-clinics").val();
        date = $('.datetimepicker').datepicker('getFormattedDate');
        $.ajax({
            url: '/admin/appointments/time_slots',
            type: 'GET',
            dataType: 'json',
            data: {doctor_id: doctor_id, clinic_id: clinic_id, date: date}
        })
        .done(function(data) {
            console.log("success");
            console.log(data);
            $('.select2-slot').select2({
                data: data.slots
            });
        })
        .always(function() {
            console.log("complete");
        });
    });
</code>```

答:
```<code>instance && $('.select2').empty();
var instance = $('.select2').select2({
    data: data
});
</code>```

Title: jquery select2 refresh data

Body:
I using select2 to select and ajax to load data, how can I replace old data when the state is changed after initial selection.

My loading code:

$('.datetimepicker').on("changeDate", function() {
        //refresh selectbox ??
        doctor_id = $(".select2-doctors").val();
        clinic_id = $(".select2-clinics").val();
        date = $('.datetimepicker').datepicker('getFormattedDate');
        $.ajax({
            url: '/admin/appointments/time_slots',
            type: 'GET',
            dataType: 'json',
            data: {doctor_id: doctor_id, clinic_id: clinic_id, date: date}
        })
        .done(function(data) {
            console.log("success");
            console.log(data);
            $('.select2-slot').select2({
                data: data.slots
            });
        })
        .always(function() {
            console.log("complete");
        });
    });


问:
Difference between size and length methods?
What is the difference between .size() and .length ? Is .size() only for arraylists and .length only for arrays?

答:
length is constant which is used to find out the array storing capacity not the number of elements in the array

Example:

```<code>int[] a = new int[5]
</code>```

a.length always returns 5, which is called the capacity of an array. But

number of elements in the array is called size

Example:

```<code>int[] a = new int[5]
a[0] = 10
</code>```

Here the size would be 1, but a.length is still 5. Mind that there is no actual property or method called size on an array so you can't just call a.size or a.size() to get the value 1.

The size() method is available for collections, length works with arrays in Java.

Body:
length is constant which is used to find out the array storing capacity not the number of elements in the array

Example:

int[] a = new int[5]

a.length always returns 5, which is called the capacity of an array. But

number of elements in the array is called size

Example:

int[] a = new int[5]
a[0] = 10

Here the size would be 1, but a.length is still 5. Mind that there is no actual property or method called size on an array so you can't just call a.size or a.size() to get the value 1.

The size() method is available for collections, length works with arrays in Java.


问:
Powershell Sort and transpose data based on particular column
I am new to powershell. I have a data which is in columnar format, which needs to be converted into rows by sorting it numerically.

Input data:

```<code>Fruit month amount
1apple jan 10
3blueberry jan 20
4mango jan 30
2banana jan 50
1apple feb 20
3blueberry feb 50
4mango feb 80
2banana feb 95
</code>```

Desired Output:

```<code>Fruit JanAmount FebAmount
1apple 10 20
2banana 50 95
3blueberry 20 50
4mango 30 80
</code>```

Can anyone pls help me with this?

答:
if you delimiter into your file is space, try this:</p>

```<code>import-csv "C:\Temp\yourfile.txt" -Delimiter  ' ' |
    group fruit |
        select Name, @{N="JanAmount";E={($_.Group | where month -eq 'jan').amount}} , @{N="FebAmount";E={($_.Group | where month -eq 'feb').amount}}
</code>```

Body:
I am new to powershell. I have a data which is in columnar format, which needs to be converted into rows by sorting it numerically.

Input data:

Fruit month amount
1apple jan 10
3blueberry jan 20
4mango jan 30
2banana jan 50
1apple feb 20
3blueberry feb 50
4mango feb 80
2banana feb 95

Desired Output:

Fruit JanAmount FebAmount
1apple 10 20
2banana 50 95
3blueberry 20 50
4mango 30 80

Can anyone pls help me with this?

Body:
if you delimiter into your file is space, try this:

import-csv "C:\Temp\yourfile.txt" -Delimiter  ' ' |
    group fruit |
        select Name, @{N="JanAmount";E={($_.Group | where month -eq 'jan').amount}} , @{N="FebAmount";E={($_.Group | where month -eq 'feb').amount}}


问:
Retrieve the two highest item from a list containing 100,000 integers
How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?</p>

答:
I know this topic is old, but here is a simple solution to this problem. Tested against heapq.nlargest and this is a bit faster (no sorting needed):

Works for both positive and negative numbers.

Function below: Max time used: 0.12, max memory used: 29290496
heapq.nlargest: Max time used: 0.14, max memory used: 31088640

```<code>def two_highest_numbers(list_to_work):

    first = None
    second = None

    for number in list_to_work:
        if first is None:
            first = number
        elif number > first:
            second = first
            first = number
        else:
            if second is None:
                second = number
            elif number > second:
                second = number

return [first, second]
</code>```

Body:
I know this topic is old, but here is a simple solution to this problem. Tested against heapq.nlargest and this is a bit faster (no sorting needed):

Works for both positive and negative numbers.

Function below: Max time used: 0.12, max memory used: 29290496
heapq.nlargest: Max time used: 0.14, max memory used: 31088640

def two_highest_numbers(list_to_work):

    first = None
    second = None

    for number in list_to_work:
        if first is None:
            first = number
        elif number > first:
            second = first
            first = number
        else:
            if second is None:
                second = number
            elif number > second:
                second = number

return [first, second]


问:
"Connection error: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)"
I develop a website locally in my laptop in php. In local machine is running fine but when i make it live there it is giving me error that is

Connection error: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)".

I am using correct information for database connectivity I don't know why it is happening.

答:
This is indeed a problem with your database credentials.The database is complaining that you did not pass the password for root user.
Most likely user root of your local database server doesn't have a password.


问:
Zoom onto Qwerty keyboard on ZoomableRelativeLayout
I have a question that is basically the same as this one: Zoom Content in a RelativeLayout

By using dispatchDraw(Canvas canvas) I can scale ZoomableRelativeLayout, but when I click on the zoomed-in view, the childViews are not scaling with their parent(RelativeLayout), so an old OnClickListener (for a character on the keyboard) gets called every time.

In the blog above someone suggested transformation or a matrix will be a better way to go. Could you guys help me?

答:
all you need are following methods

```<code>public float getTranslatedCoordinates(){

    pointTranslatedX =
           // Math.abs(
            (pointSelectedX - mPivotX ) / scaleFactor + mPivotX
            //)
            ;
    // is not important if our scaleFactor is 3
    // pointTranslatedY = (pointSelectedY - mPivotY ) * scaleFactor + mPivotY;

    Log.e("getTranslatedC", this.toString());
    return pointTranslatedX;
}
</code>```

getStartMargin() and getKeySelected().

What this question is also about the design from the beginning. Instead of click to zoom onto a part of the QWERTY-Keyboard right where the keyboard is (on a smartWatch screen), you can also display a row above or below the (main) QWERTY-Keyboard. This will improve the usability enormously!

Body:
all you need are following methods

public float getTranslatedCoordinates(){

    pointTranslatedX =
           // Math.abs(
            (pointSelectedX - mPivotX ) / scaleFactor + mPivotX
            //)
            ;
    // is not important if our scaleFactor is 3
    // pointTranslatedY = (pointSelectedY - mPivotY ) * scaleFactor + mPivotY;

    Log.e("getTranslatedC", this.toString());
    return pointTranslatedX;
}

getStartMargin() and getKeySelected().

What this question is also about the design from the beginning. Instead of click to zoom onto a part of the QWERTY-Keyboard right where the keyboard is (on a smartWatch screen), you can also display a row above or below the (main) QWERTY-Keyboard. This will improve the usability enormously!


问:
UnZip zip file and access the files using JavaScript
How can I unzip a .zip file and store it at a client site for further process using JavaScript without a network call?</p>

答:
This is a Javascript library for Zip and Unzip files.

https://gildas-lormeau.github.io/zip.js/fs-api.html


问:
limit is not working in subquery
I have saved vehicle types in 'vehicle_types_locales', drivers in 'drivers' and driver's current location in 'drivercurrentlocation' table.

Logic : I am trying to get all vehicle types from main query then trying to select 5 drivers for each category from driver's tables which satisfying conditions as implemented. If records are less than 5 for all categories then it's working fine else it returns all driver's exist in category.(seems limit not working)

My query is :

```<code>SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        drv.id,'----', drv.firstname, '----', ifnull(drv.lastname,''), '----',
        dll.latitude, '----', dll.longitude) SEPARATOR '--++--')
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5)
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";
</code>```

Please help me to resolve this limit issue.

Thanks in advance

答:
Note:Limit condition will not work when you use Group_concat.
To achieve limit put a subquery and limit the rows somewhat like this</p>

```<code>SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        newdrv.id,'----', newdrv.firstname, '----', ifnull(newdrv.lastname,''), '----',
        newdrv.latitude, '----', newdrv.longitude) SEPARATOR '--++--') from           (select drv.id, drv.firstname, ifnull(drv.lastname,''),
        dll.latitude,dll.longitude
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5) newdrv )
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";
</code>```

Title: limit is not working in subquery

Body:
I have saved vehicle types in 'vehicle_types_locales', drivers in 'drivers' and driver's current location in 'drivercurrentlocation' table.

Logic : I am trying to get all vehicle types from main query then trying to select 5 drivers for each category from driver's tables which satisfying conditions as implemented. If records are less than 5 for all categories then it's working fine else it returns all driver's exist in category.(seems limit not working)

My query is :

SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        drv.id,'----', drv.firstname, '----', ifnull(drv.lastname,''), '----',
        dll.latitude, '----', dll.longitude) SEPARATOR '--++--')
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5)
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";

Please help me to resolve this limit issue.

Thanks in advance

Body:
Note:Limit condition will not work when you use Group_concat.
To achieve limit put a subquery and limit the rows somewhat like this

SELECT vtl.vehicle_type_id as id ,vtl.name, (
    SELECT GROUP_CONCAT(concat(
        newdrv.id,'----', newdrv.firstname, '----', ifnull(newdrv.lastname,''), '----',
        newdrv.latitude, '----', newdrv.longitude) SEPARATOR '--++--') from           (select drv.id, drv.firstname, ifnull(drv.lastname,''),
        dll.latitude,dll.longitude
    FROM drivercurrentlocation as dll LEFT JOIN drivers as drv ON
    (dll.driverid = drv.id) WHERE drv.active_vehicle_id > 0 AND
    current_duty_status='F' and drv.status='A' and drv.onduty='Y' AND
    drv.vehicle_type_id= vtl.vehicle_type_id AND latitude > '".
    $latLongData['minLat']."' AND latitude < '". $latLongData['maxLat'] ."'
    AND longitude > '". $latLongData['minLng'] ."' AND longitude < '".
    $latLongData['maxLng']."' limit 5) newdrv )
as ddata FROM vehicle_types_locales
WHERE vtl.status  = 'A' AND vtl.language_id = '$languageid'";


问:
Images are not shown in React although the path is right
I have created a little test in react with dynamic content. Within a sidebar there is something like bootstrap collapses, containing lists with icons and names. The problem is that some images within "Natürlich" are not shown. These images are stored together with all the working ones and if I follow the link from the inspector the right images is at the right place.

I have some code going on to take the name of the list item and first remove the umlauts and then put it in between the link of the image as you can see here. This seems to work for all other images except the 3 missing within "Natürlich"

```<code>correctNames: function(warning) {
  if (warning) {
    var warningCorrected = warning.toLowerCase().replace(/\u00f6/g, 'oe').replace(/\u00e4/g, 'ae').replace(/\u00fc/g, 'ue').replace(/\u00df/g, 'ss');
    return warningCorrected
  }
},

render: function() {
    var warnings = this.props.warningName;
    var isActive = this.state.warningState ? 'warning-active' : 'warning-inactive';
    return (
    <li className={'transition ' + isActive} onClick={this.activateWarning}>
    {this.correctNames()}
    <img src={'img/warning/' + this.correctNames(warnings) + '-active.png'} alt="" />
    <p>{warnings + " " + this.correctNames(warnings)}</p>
    </li>
    );
}
</code>```

You can find the page here

UPDATE!
It seems to be a problem with UTF-8 or something. While in my inspector the path is shown right, the error message is
kon%E2%80%8Bser%E2%80%8Bvie%E2%80%8Brungs%E2%80%8Bstoffe-active.png

How can I get rid of these errors?

答:
Try this:</p>

```<code>src={`img/warning/${this.correctNames(warnings)}-active.png`}
</code>```

Body:
I have created a little test in react with dynamic content. Within a sidebar there is something like bootstrap collapses, containing lists with icons and names. The problem is that some images within "Natürlich" are not shown. These images are stored together with all the working ones and if I follow the link from the inspector the right images is at the right place.

I have some code going on to take the name of the list item and first remove the umlauts and then put it in between the link of the image as you can see here. This seems to work for all other images except the 3 missing within "Natürlich"

correctNames: function(warning) {
  if (warning) {
    var warningCorrected = warning.toLowerCase().replace(/\u00f6/g, 'oe').replace(/\u00e4/g, 'ae').replace(/\u00fc/g, 'ue').replace(/\u00df/g, 'ss');
    return warningCorrected
  }
},

render: function() {
    var warnings = this.props.warningName;
    var isActive = this.state.warningState ? 'warning-active' : 'warning-inactive';
    return (

    {this.correctNames()}

{warnings + " " + this.correctNames(warnings)}

    );
}

You can find the page here

UPDATE!
It seems to be a problem with UTF-8 or something. While in my inspector the path is shown right, the error message is
kon%E2%80%8Bser%E2%80%8Bvie%E2%80%8Brungs%E2%80%8Bstoffe-active.png

How can I get rid of these errors?

Body:
Try this:

src={`img/warning/${this.correctNames(warnings)}-active.png`}


问:
bind json data to input select
I am using one input select where i have to bind json data to this control.

Below is the input select used:

<select id="ms" multiple="multiple" name="selector">

</select>```
</div>
</div>

Below is jquery used for bind data on page load:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$(document).ready(function () {

        $('#ms').multipleSelect({
            width: '100%'
        });
        BindCategory();
  });
   function BindCategory()
    {
        $.ajax({
            url: "/Article/BindCategory",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                var sel = $('#ms');
                $.each(response.Categories, function (i, value) {
                    j=1;
                    sel.append('<option value="' + value + '">' + i + '</option>');

                    j++;
                });
            },
            error: function (er) {
                alert(er);
            }
        });
    }</code>```

in this bindcategory function i am running one loop to get value one by one and putting in html select control but after complete this process data is not binding in this control.

I added now screen shot of response for your reference in below:

答:
I assume you're using https://github.com/wenzhixin/multiple-select multiselect plugin. If so, In the documentation it specifies to use refresh to reload the select if it dynamically fetches the data.

If you’re dynamically adding/removing option tags on the original select via AJAX or DOM manipulation methods, call refresh to reflect the changes.

Try placing $(elm).multipleSelect('refresh'); in your success function. Something like:

```<code> success: function (response) {
            var sel = $('#ms');
            $.each(response.Categories, function (i, value) {
                j=1;
                sel.append('<option value="' + value + '">' + i + '</option>');

                j++;
            });
            sel.multipleSelect('refresh');
        },
</code>```

Title: bind json data to input select

Body:
I am using one input select where i have to bind json data to this control.

Below is the input select used:

<select id="ms" multiple="multiple" name="selector">

</select>

Below is jquery used for bind data on page load:

$(document).ready(function () {

        $('#ms').multipleSelect({
            width: '100%'
        });
        BindCategory();
  });
   function BindCategory()
    {
        $.ajax({
            url: "/Article/BindCategory",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                var sel = $('#ms');
                $.each(response.Categories, function (i, value) {
                    j=1;
                    sel.append('<option value="' + value + '">' + i + '</option>');

                    j++;
                });
            },
            error: function (er) {
                alert(er);
            }
        });
    }

in this bindcategory function i am running one loop to get value one by one and putting in html select control but after complete this process data is not binding in this control.

I added now screen shot of response for your reference in below:

Body:
I assume you're using https://github.com/wenzhixin/multiple-select multiselect plugin. If so, In the documentation it specifies to use refresh to reload the select if it dynamically fetches the data.

If you’re dynamically adding/removing option tags on the original select via AJAX or DOM manipulation methods, call refresh to reflect the changes.

Try placing $(elm).multipleSelect('refresh'); in your success function. Something like:

 success: function (response) {
            var sel = $('#ms');
            $.each(response.Categories, function (i, value) {
                j=1;
                sel.append('<option value="' + value + '">' + i + '</option>');

                j++;
            });
            sel.multipleSelect('refresh');
        },


问:
Typescript with Mongoose EXEC() function async/await
I am trying to use Typescript with Express and Mongoose. So far the result has been amazing. I am however stuck at a very minor part.

Premise: I am executing a Mongoose Query using EXEC()

```<code>let result = await UserModel.User.find().exec();
</code>```

I have to use the async / await as there is some processing after this line and I want to avoid callbacks throughout

Problem

I need to get the {err, data}  from the result object returned by the query. However currently it simply holds the entire data and I am not able to perform the error handling

So need a way to get the mongoose error description when I use async/await

答:
Error handling using async/await is done by using try/catch:

```<code>try {
  let result = await UserModel.User.find().exec();
  ...
} catch(err) {
  ...
}
</code>```

Body:
I am trying to use Typescript with Express and Mongoose. So far the result has been amazing. I am however stuck at a very minor part.

Premise: I am executing a Mongoose Query using EXEC()

let result = await UserModel.User.find().exec();

I have to use the async / await as there is some processing after this line and I want to avoid callbacks throughout

Problem

I need to get the {err, data}  from the result object returned by the query. However currently it simply holds the entire data and I am not able to perform the error handling

So need a way to get the mongoose error description when I use async/await

Body:
Error handling using async/await is done by using try/catch:

try {
  let result = await UserModel.User.find().exec();
  ...
} catch(err) {
  ...
}


问:
org.hibernate.MappingNotFoundException: resource: com/corp/dept/proj/FooTbl.hbm.xml not found
No, this isn't the same question as this one or this one or this one.

for the simple reason that my *.hbm.xml files are already in the right directory (src/main/resources/com/corp/dept/proj).

Furthermore, it used to run fine, as long as I statically (i.e. hardcoded at build time) took everything from hibernate.cfg.xml, using this simple static method in my HibernateUtil.java:

```<code>private static SessionFactory buildSessionFactory() {
    try {
        return new Configuration().configure("resources/hibernate.cfg.xml").buildSessionFactory();
    }
    catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
</code>```

But since I wanted to move some of the parameters from hibernate.cfg.xml to a properties file to be read at runtime (e.g. DB's  "connection.url"):

```<code>static {
  try {
    sessionFactory = buildHibernateConfig().buildSessionFactory();
  } catch (Throwable ex) {
    System.out.println("Initial SessionFactory creation failed: " + ex.getMessage());
    throw new ExceptionInInitializerError(ex);
  }
}
</code>```

and

```<code>private static Configuration buildHibernateConfig() throws FileNotFoundException, IOException {

  Properties properties = new Properties();
  sConfig = new Configuration().configure("resources/hibernate.cfg.xml");

  try {
    properties.load(ServiceUtils.class.getResourceAsStream(MYWS_PROPS));
  }
  catch (IOException e) {
    LOG.severe("Cannot find properties file " + MYWS_PROPS);
    throw new SecurityException("Server Error: couldn't open " + MYWS_PROPS + " file");
  }

  /*hardcoded*/sConfig.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");/*hardcoded*/
  /*hardcoded*/sConfig.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");/*hardcoded*/
  sConfig.setProperty("hibernate.connection.url", properties.getProperty("dburl"));

  // Add Hibernate XML mappings
  sConfig.addClass(FooTbl.class);

  return sConfig;
}
</code>```

I am getting a runtime exception:

```<code>Apr 03, 2014 14:31:49 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Apr 03, 2014 14:31:49 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: resources/hibernate.cfg.xml
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: resources/hibernate.cfg.xml
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: resources/com/corp/dept/proj/FooTbl.hbm.xml

Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration addClass
INFO: HHH000221: Reading mappings from resource: com/corp/dept/proj/FooTbl.hbm.xml
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/corp/dept/proj/FooTbl.hbm.xml
Initial SessionFactory creation failed: resource: com/corp/dept/proj/FooTbl.hbm.xml not found

Caused by: org.hibernate.MappingNotFoundException: resource: com/corp/dept/proj/FooTbl.hbm.xml not found
        at org.hibernate.cfg.Configuration.addResource(Configuration.java:712)
        at org.hibernate.cfg.Configuration.addClass(Configuration.java:757)
        at com.corp.dept.proj.myws.HibernateUtil.buildHibernateConfig(HibernateUtil.java:141)
        at com.corp.dept.proj.myws.HibernateUtil.<clinit>(HibernateUtil.java:56)
</code>```

Now... prior to the exception, the log shows that the files are found. I also verified that the files are physically included in the WAR file in the same exact subdirectory they are expected. So, why is this error?

What is the recommended way to fix this?

答:
make sure that your file FooTbl.hbm.xml name should match with class name in case of addClass() method.

Here your class name is FooTbl then mapping file name should be FooTbl.hbm.xml otherwise exception will generate.

try this. :)

Body:
No, this isn't the same question as this one or this one or this one.

for the simple reason that my *.hbm.xml files are already in the right directory (src/main/resources/com/corp/dept/proj).

Furthermore, it used to run fine, as long as I statically (i.e. hardcoded at build time) took everything from hibernate.cfg.xml, using this simple static method in my HibernateUtil.java:

private static SessionFactory buildSessionFactory() {
    try {
        return new Configuration().configure("resources/hibernate.cfg.xml").buildSessionFactory();
    }
    catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

But since I wanted to move some of the parameters from hibernate.cfg.xml to a properties file to be read at runtime (e.g. DB's  "connection.url"):

static {
  try {
    sessionFactory = buildHibernateConfig().buildSessionFactory();
  } catch (Throwable ex) {
    System.out.println("Initial SessionFactory creation failed: " + ex.getMessage());
    throw new ExceptionInInitializerError(ex);
  }
}

and

private static Configuration buildHibernateConfig() throws FileNotFoundException, IOException {

  Properties properties = new Properties();
  sConfig = new Configuration().configure("resources/hibernate.cfg.xml");

  try {
    properties.load(ServiceUtils.class.getResourceAsStream(MYWS_PROPS));
  }
  catch (IOException e) {
    LOG.severe("Cannot find properties file " + MYWS_PROPS);
    throw new SecurityException("Server Error: couldn't open " + MYWS_PROPS + " file");
  }

  /*hardcoded*/sConfig.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");/*hardcoded*/
  /*hardcoded*/sConfig.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");/*hardcoded*/
  sConfig.setProperty("hibernate.connection.url", properties.getProperty("dburl"));

  // Add Hibernate XML mappings
  sConfig.addClass(FooTbl.class);

  return sConfig;
}

I am getting a runtime exception:

Apr 03, 2014 14:31:49 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Apr 03, 2014 14:31:49 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: resources/hibernate.cfg.xml
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: resources/hibernate.cfg.xml
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: resources/com/corp/dept/proj/FooTbl.hbm.xml

Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration addClass
INFO: HHH000221: Reading mappings from resource: com/corp/dept/proj/FooTbl.hbm.xml
Apr 03, 2014 14:31:49 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/corp/dept/proj/FooTbl.hbm.xml
Initial SessionFactory creation failed: resource: com/corp/dept/proj/FooTbl.hbm.xml not found

Caused by: org.hibernate.MappingNotFoundException: resource: com/corp/dept/proj/FooTbl.hbm.xml not found
        at org.hibernate.cfg.Configuration.addResource(Configuration.java:712)
        at org.hibernate.cfg.Configuration.addClass(Configuration.java:757)
        at com.corp.dept.proj.myws.HibernateUtil.buildHibernateConfig(HibernateUtil.java:141)
        at com.corp.dept.proj.myws.HibernateUtil.<clinit>(HibernateUtil.java:56)

Now... prior to the exception, the log shows that the files are found. I also verified that the files are physically included in the WAR file in the same exact subdirectory they are expected. So, why is this error?

What is the recommended way to fix this?


问:
Javac is not recognized even after setting the path
I have installed my jdk file. I have also set my path in the advanced setting in the user variable as well as system variable. When I tried to compile my program through  javac filename.java the command prompt is showing javac is not recognized as an internal or external command. I again set my path but still the problem remains the same</p>

答: I see that the System variable Path has an entry to C:\ProgramData\Oracle\Java\javapath. But that location doesn't have the Javac executable.(javac.exe). Adding the JDK bin path solved the problem for me. (Added C:\Program Files\Java\jdk1.8.0_121\bin to Path)


问:
Is there any way to let Lua garbage collector know about memory requirements of userdata?
I have a C++ application which embeds Lua and periodically (~10 times per second) runs scripts that can create new userdata objects that allocate non-trivial amounts of memory (~1MiB each) on C++ side. The memory is correctly freed when these objects are garbage-collected, but the problem is that they don't seem to be collected until it's too late and the process starts consuming inordinate amounts of memory (many GiBs). I guess this happens because Lua GC thinks that these objects are just not worth collecting because they appear small on Lua side, and it has no idea how much memory do they actually consume. If this is correct, is there any way to tell it about the real cost of keeping these objects around?

For people familiar with C#, I'm basically looking for the equivalent of GC.AddMemoryPressure() for Lua.

答: No. there is no such mechanism in Lua.</p>

Body: No. there is no such mechanism in Lua.