问:
Could not write JSON: Infinite recursion (StackOverflowError); nested exception spring boot
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

```<code>    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }
</code>```

The model class for state:

```<code> package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

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

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }
</code>```

Distric model:

```<code>package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}
</code>```

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-

答:
You are facing this issue because the Statemaster model contains the object of Districtmaster model, which itself contains the object of Statemaster model. This causes an infinite json recursion.

You can solve this issue by 3 methods.

1 - Create a DTO and include only the fields that you want to display in the response.

2 - You can use the @JsonManagedReference and @JsonBackReference annotations.

E.g. Add the @JsonManagedReference annotation to the Statemaster model.

```<code>@JsonManagedReference
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
public Set<Districtmaster> getDistrictmasters() {
    return this.districtmasters;
}
</code>```

Add the @JsonBackReference annotation to the Districtmaster model.

```<code>@JsonBackReference
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="district_of_state")
public Statemaster getStatemaster() {
    return this.statemaster;
}
</code>```

3 - You can use the @JsonIgnore annotation on the getter or setter method.

```<code>@JsonIgnore
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
public Set<Districtmaster> getDistrictmasters() {
    return this.districtmasters;
}
</code>```

However, this approach will omit the set of Districtmaster from the response.

Body:
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }

The model class for state:

 package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

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

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }

Distric model:

package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-

Body:
You are facing this issue because the Statemaster model contains the object of Districtmaster model, which itself contains the object of Statemaster model. This causes an infinite json recursion.

You can solve this issue by 3 methods.

1 - Create a DTO and include only the fields that you want to display in the response.

2 - You can use the @JsonManagedReference and @JsonBackReference annotations.

E.g. Add the @JsonManagedReference annotation to the Statemaster model.

@JsonManagedReference
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
public Set<Districtmaster> getDistrictmasters() {
    return this.districtmasters;
}

Add the @JsonBackReference annotation to the Districtmaster model.

@JsonBackReference
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="district_of_state")
public Statemaster getStatemaster() {
    return this.statemaster;
}

3 - You can use the @JsonIgnore annotation on the getter or setter method.

@JsonIgnore
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
public Set<Districtmaster> getDistrictmasters() {
    return this.districtmasters;
}

However, this approach will omit the set of Districtmaster from the response.


来源: stackexchange

问:
Mongo Scala Driver - Can't insert in the database
I'm practicing on a project that needs a database connection, I'm using the Play Framework combine to Scala and MongoDB.

I'm also using Mongo-scala-driver and following the documentation.
I wrote the exact same code:

```<code>    println("start")

    val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/Sandbox")

    val database: MongoDatabase = mongoClient.getDatabase("test")

    val collection: MongoCollection[Document] = database.getCollection("test")

    val doc: Document = Document("_id" -> 0, "name" -> "MongoDB", "type" -> "database", "count" -> 1, "info" -> Document("x" -> 203, "y" -> 102))

    collection.insertOne(doc).subscribe(new Observer[Completed] {

      override def onSubscribe(subscription: Subscription): Unit = println("Subscribed")

      override def onNext(result: Completed): Unit = println("Inserted")

      override def onError(e: Throwable): Unit = println("Failed")

      override def onComplete(): Unit = println("Completed")
    })

    mongoClient.close()

    println("end")
</code>```

Nothing is inserted into the database and the only result i get from the log is this:

```<code>start
Subscribed
end
</code>```

I've been looking on stackoverflow for similar subject but everything I found didn't work for me.

答:
You try insert document in asyncronous mode.
Therefore you must define three call back function onNext onError and onComplete
But you don't give time for execute insertion.

Try append any timeout before close connection. For example simple add

```<code>Thread.sleep(1000)
</code>```

before

```<code>mongoClient.close()
</code>```

And you no need redefine onSubscribe()

if you not want manually control demand when you move in documents list from you requests then you no need override onSubscribe(). The default definition for onSubscrime() very usable for trivial requests. In you case you no need override him.

The next code is worked

```<code>println("start")
val mongoClient: MongoClient = MongoClient("mongodb://DB01-MongoDB:27017/Sandbox")
val database: MongoDatabase = mongoClient.getDatabase("test")
val collection: MongoCollection[Document] = database.getCollection("test")
val doc: Document = Document("_id" -> 0,
                             "name"  -> "MongoDB",
                             "type"  -> "database",
                             "count" -> 1,
                             "info"  -> Document("x" -> 203, "y" -> 102))
collection
  .insertOne(doc)
  .subscribe(new Observer[Completed] {
    override def onNext(result: Completed): Unit = println("Inserted")
    override def onError(e: Throwable): Unit     = println("Failed")
    override def onComplete(): Unit              = println("Completed")
  })

Thread.sleep(1000)
mongoClient.close()
println("end")
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
I'm practicing on a project that needs a database connection, I'm using the Play Framework combine to Scala and MongoDB.

I'm also using Mongo-scala-driver and following the documentation.
I wrote the exact same code:

    println("start")

    val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/Sandbox")

    val database: MongoDatabase = mongoClient.getDatabase("test")

    val collection: MongoCollection[Document] = database.getCollection("test")

    val doc: Document = Document("_id" -> 0, "name" -> "MongoDB", "type" -> "database", "count" -> 1, "info" -> Document("x" -> 203, "y" -> 102))

    collection.insertOne(doc).subscribe(new Observer[Completed] {

      override def onSubscribe(subscription: Subscription): Unit = println("Subscribed")

      override def onNext(result: Completed): Unit = println("Inserted")

      override def onError(e: Throwable): Unit = println("Failed")

      override def onComplete(): Unit = println("Completed")
    })

    mongoClient.close()

    println("end")

Nothing is inserted into the database and the only result i get from the log is this:

start
Subscribed
end

I've been looking on stackoverflow for similar subject but everything I found didn't work for me.

Body:
You try insert document in asyncronous mode.
Therefore you must define three call back function onNext onError and onComplete
But you don't give time for execute insertion.

Try append any timeout before close connection. For example simple add

Thread.sleep(1000)

before

mongoClient.close()

And you no need redefine onSubscribe()

if you not want manually control demand when you move in documents list from you requests then you no need override onSubscribe(). The default definition for onSubscrime() very usable for trivial requests. In you case you no need override him.

The next code is worked

println("start")
val mongoClient: MongoClient = MongoClient("mongodb://DB01-MongoDB:27017/Sandbox")
val database: MongoDatabase = mongoClient.getDatabase("test")
val collection: MongoCollection[Document] = database.getCollection("test")
val doc: Document = Document("_id" -> 0,
                             "name"  -> "MongoDB",
                             "type"  -> "database",
                             "count" -> 1,
                             "info"  -> Document("x" -> 203, "y" -> 102))
collection
  .insertOne(doc)
  .subscribe(new Observer[Completed] {
    override def onNext(result: Completed): Unit = println("Inserted")
    override def onError(e: Throwable): Unit     = println("Failed")
    override def onComplete(): Unit              = println("Completed")
  })

Thread.sleep(1000)
mongoClient.close()
println("end")

}


问:
Filter just duplicate urls from an php array
Here is an array

```<code>Array (
   [EM Debt] => http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB
   [EM Local Debt] => Will be launched shortly
   [EM Blended Debt] => Will be launched shortly
   [Frontier Markets] => http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0501220262
   [Absolute Return Debt and FX] => Will be launched shortly
   [Em Debt] => http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0501220262
)
</code>```

If I use array_unique() it will filter Will be launched shortly from the array also.

I just want to filter duplicate urls, not text.

UPDATE:

I need to be Array order remain as same, Just filter dupl

答:
Here is your answer:</p>

```<code><?php
// taking just example here, replace `$array` with yours
$array = ['http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB', 'abc', 'abc', 'http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB'];
$url_array = [];
foreach($array as $ele) {
    if(strpos($ele, 'http://') !== false) {
        $url_array[] = $ele;
    } else {
        $string_array[] = $ele;
    }
}

$url_array = array_unique($url_array);
print_r(array_merge($string_array, $url_array));
?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is an array

Array (
   [EM Debt] => http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB
   [EM Local Debt] => Will be launched shortly
   [EM Blended Debt] => Will be launched shortly
   [Frontier Markets] => http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0501220262
   [Absolute Return Debt and FX] => Will be launched shortly
   [Em Debt] => http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0501220262
)

If I use array_unique() it will filter Will be launched shortly from the array also.

I just want to filter duplicate urls, not text.

UPDATE:

I need to be Array order remain as same, Just filter dupl

Body:
Here is your answer:

<?php
// taking just example here, replace `$array` with yours
$array = ['http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB', 'abc', 'abc', 'http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB'];
$url_array = [];
foreach($array as $ele) {
    if(strpos($ele, 'http://') !== false) {
        $url_array[] = $ele;
    } else {
        $string_array[] = $ele;
    }
}

$url_array = array_unique($url_array);
print_r(array_merge($string_array, $url_array));
?>


问:
Jquery $(window).on("load"... and chrome extensions
I'm making a chrome extension, I need to add a few listeners and classes to elements when my popup load.

So far, I've did this :

```<code>$("body").ready(main());
</code>```

where I added things to the elements in my main function, problem is, elements doesn't exist when main is run, so it doesn't work.

I've looked and found that $(window).load() should be used. I tried, but got jquery errors. I've looked and found that $(window).on("load",main()) should work instead. I tried, and it "worked" just like my $("body").ready(...
For some ready, even the "window on load" thing doesn't wait for my elements to be fully loaded.
Simple test I'm trying to do is :

```<code>function main(){
    console.log($("#toto").attr("id"));
}
</code>```

When I open the popup of my extension, it returns "undefined" in the console, but if I paste the same code, it returns "toto".
How could I make this work please ?

答:
Ok, it's weird but I solved it like that :

```<code>window.onload=function(){
    main();
}
</code>```

while $(window).load(... or $(window).on("load"... didn't worked.

Body:
I'm making a chrome extension, I need to add a few listeners and classes to elements when my popup load.

So far, I've did this :

$("body").ready(main());

where I added things to the elements in my main function, problem is, elements doesn't exist when main is run, so it doesn't work.

I've looked and found that $(window).load() should be used. I tried, but got jquery errors. I've looked and found that $(window).on("load",main()) should work instead. I tried, and it "worked" just like my $("body").ready(...
For some ready, even the "window on load" thing doesn't wait for my elements to be fully loaded.
Simple test I'm trying to do is :

function main(){
    console.log($("#toto").attr("id"));
}

When I open the popup of my extension, it returns "undefined" in the console, but if I paste the same code, it returns "toto".
How could I make this work please ?

Body:
Ok, it's weird but I solved it like that :

window.onload=function(){
    main();
}

while $(window).load(... or $(window).on("load"... didn't worked.


问:
Refresh page with Ajax without jQuery
I need to update my page automatically without refreshing it with Ajax. But so far I have seen is that people use jQuery and PHP, and I'm not that good at coding. So what I need to do is to add Ajax to HTML without adding PHP or jQuery.
Pages where I found something similar, but all of them uses jQuery:
ajax jquery update page without refreshing
Update data on a page without refreshing
http://api.jquery.com/load/
Thank You</p>

答:
```<code><script>
    setInterval(function(){ location.reload(); },5000);
</script>
</code>```

Put this snippet in your desired HTML page. This setInterval() function refresh the page every 5 second.

Title: Refresh page with Ajax without jQuery

Body:
<script>
    setInterval(function(){ location.reload(); },5000);
</script>

Put this snippet in your desired HTML page. This setInterval() function refresh the page every 5 second.


问:
INSTALL_PARSE_FAILED_MANIFEST_MALFORMED error android
I get the INSTALL_PARSE_FAILED_MANIFEST_MALFORMED error when trying to deploy my updated app on my phone. (can't quite recall everything I changed I must admit)
Here is the logcat:

```<code>    11-19 01:17:34.709 344-344/? E/installd: Couldn't opendir/data/app/vmdl535902261.tmp: No such file or directory
    11-19 01:17:34.710 19506-19506/? E/Pm: Failure details:Bundle[{android.content.pm.extra.STATUS=4,android.content.pm.extra.PACKAGE_NAME=ProjectRomero.CarRemote, android.content.pm.extra.SESSION_ID=535902261, android.content.pm.extra.LEGACY_STATUS=-108, android.content.pm.extra.STATUS_MESSAGE=INSTALL_PARSE_FAILED_MANIFEST_MALFORMED: Failed parse during installPackageLI: /data/app/vmdl535902261.tmp/base.apk (at Binary XML file line #28): <activity> does not have valid android:name}]
</code>```

and my AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="ProjectRomero.CarRemote">

        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

        <uses-feature
            android:name="android.hardware.bluetooth_le"
            android:required="true" />

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">

            <activity
                android:name=".scan_activity"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <activity
                android:name=".remote_activity"
                android:label="@string/app_name">
            </activity>

        </application>
    </manifest>
```

<p>And my two activities headers:</p>

<pre class="lang-java prettyprint-override"><code>  package ProjectRomero.CarRemote;
  //imports
  public class remote_activity extends AppCompatActivity {}

  package ProjectRomero.CarRemote;
  //imports
  public class scan_activity extends AppCompatActivity {}
</code>```

I must admit I am quite confused, how can I correct this error? tried cleaning quite a few times, even recreated a project and copied the code, deleted the previous version of the app on my phone, restarted my phone, and still nothing...

Thanks in advance :)

答:
Change package="ProjectRomero.CarRemote"
to package="projectromero.carremote" in the manifest

For some reason the Caps put it off

Body:
I get the INSTALL_PARSE_FAILED_MANIFEST_MALFORMED error when trying to deploy my updated app on my phone. (can't quite recall everything I changed I must admit)
Here is the logcat:

    11-19 01:17:34.709 344-344/? E/installd: Couldn't opendir/data/app/vmdl535902261.tmp: No such file or directory
    11-19 01:17:34.710 19506-19506/? E/Pm: Failure details:Bundle[{android.content.pm.extra.STATUS=4,android.content.pm.extra.PACKAGE_NAME=ProjectRomero.CarRemote, android.content.pm.extra.SESSION_ID=535902261, android.content.pm.extra.LEGACY_STATUS=-108, android.content.pm.extra.STATUS_MESSAGE=INSTALL_PARSE_FAILED_MANIFEST_MALFORMED: Failed parse during installPackageLI: /data/app/vmdl535902261.tmp/base.apk (at Binary XML file line #28): <activity> does not have valid android:name}]

and my AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="ProjectRomero.CarRemote">

        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

        <uses-feature
            android:name="android.hardware.bluetooth_le"
            android:required="true" />

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">

            <activity
                android:name=".scan_activity"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <activity
                android:name=".remote_activity"
                android:label="@string/app_name">
            </activity>

        </application>
    </manifest>

And my two activities headers:

  package ProjectRomero.CarRemote;
  //imports
  public class remote_activity extends AppCompatActivity {}

  package ProjectRomero.CarRemote;
  //imports
  public class scan_activity extends AppCompatActivity {}

I must admit I am quite confused, how can I correct this error? tried cleaning quite a few times, even recreated a project and copied the code, deleted the previous version of the app on my phone, restarted my phone, and still nothing...

Thanks in advance :)


问:
Can't submit apps to AppStore: ERROR ITMS-90534: "Invalid Toolchain

ERROR ITMS-90534: "Invalid Toolchain.

New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds." ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

I found this error during upload IPA to account.

答:
From Xcode -> Go to Organizer -> Under Archives, select the build and right click to Show in finder -> Select the Project and right click to -> Show Package Contents -> Double click on Info.plist and add a row. The key is  BuildMachineOSBuild and the Type is String and the Value is 16G29 (Value is based on your Mac OS Version. Please follow the below given link)

https://support.apple.com/en-in/HT201260   .....Check the version number for your Mac OS version and set the value in the Info.plist

For example if your Mac OS version is 10.12.6 then add this to your plist

```<code><key>BuildMachineOSBuild</key>
<string>16G29</string>
</code>```

You are ready to send your build to iTunes Connect

Body:
From Xcode -> Go to Organizer -> Under Archives, select the build and right click to Show in finder -> Select the Project and right click to -> Show Package Contents -> Double click on Info.plist and add a row. The key is  BuildMachineOSBuild and the Type is String and the Value is 16G29 (Value is based on your Mac OS Version. Please follow the below given link)

https://support.apple.com/en-in/HT201260   .....Check the version number for your Mac OS version and set the value in the Info.plist

For example if your Mac OS version is 10.12.6 then add this to your plist

<key>BuildMachineOSBuild</key>
<string>16G29</string>

You are ready to send your build to iTunes Connect


问:
Bad range of polar streamplot with matplotlib

I'm trying to plot streamlines in polar coordinates with matplotlib. However, some issues seem to appear on the ranges of the polar plot. Here is one short example to illustrate the problem:

```<code>import numpy as np
import matplotlib.pyplot as plt

r1 = np.linspace(0.5, 1, 50)
r2 = np.logspace(np.log10(0.5), np.log10(1.), 50)
t = np.linspace(0, 2*np.pi, 360)
r = r1

tt, rr = np.meshgrid(t, r)
v = 0*rr
u = rr

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(1,1,1, projection='polar')
ax.streamplot(t, r, v, u, density=1., color='k', linewidth=3)
plt.show()
plt.close()
</code>```

With r=r1 (linspace), there is no problem. But with r=r2, the radial range of the plot is wrong and varies in [0.5, 0.82] instead of [0.5, 1.].

What is wrong with my code ?

答:
From matplotlib.pyplot.streamplot's doc, both x, y have to be evenly spaced. So you can interpolate your data using scipy's interpolants for instance. griddata might fit your needs.

[EDIT] This was solved in this SO question with interpolation.

Body:
I'm trying to plot streamlines in polar coordinates with matplotlib. However, some issues seem to appear on the ranges of the polar plot. Here is one short example to illustrate the problem:

import numpy as np
import matplotlib.pyplot as plt

r1 = np.linspace(0.5, 1, 50)
r2 = np.logspace(np.log10(0.5), np.log10(1.), 50)
t = np.linspace(0, 2*np.pi, 360)
r = r1

tt, rr = np.meshgrid(t, r)
v = 0*rr
u = rr

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(1,1,1, projection='polar')
ax.streamplot(t, r, v, u, density=1., color='k', linewidth=3)
plt.show()
plt.close()

With r=r1 (linspace), there is no problem. But with r=r2, the radial range of the plot is wrong and varies in [0.5, 0.82] instead of [0.5, 1.].

What is wrong with my code ?


问:
How to get the smallest list?
So I got four Lists:

```<code>1, 2, 3, 4
1, 2, 3
1, 2
1, 2, 3, 4, 5
</code>```

What is the easiest way of getting the one with smallest size in elements (list.size())?

答:
I dont know how you named your Lists, so I'm just going to call them List a, b, c and d.

```<code>public List<?> getLongestList(List<?> a, List<?> b, List<?> c, List<?> d) {
  if (a.size() >= b.size() && a.size() >= c.size() && a.size() >= d.size()) return a;
  if (b.size() >= a.size() && b.size() >= c.size() && b.size() >= d.size()) return b;
  if (c.size() >= a.size() && c.size() >= b.size() && c.size() >= d.size()) return c;
  if (d.size() >= a.size() && d.size() >= b.size() && d.size() >= c.size()) return d;
  return null; //impossible to reach
}
</code>```

I know this is a very ugly solution, but it's easy to understand for java beginners, which I assume you are. If two or more Lists have the same size and are the longest, the first one of those will be returned.

Title: How to get the smallest list?

Body:
So I got four Lists:

1, 2, 3, 4
1, 2, 3
1, 2
1, 2, 3, 4, 5

What is the easiest way of getting the one with smallest size in elements (list.size())?

Body:
I dont know how you named your Lists, so I'm just going to call them List a, b, c and d.

public List<?> getLongestList(List<?> a, List<?> b, List<?> c, List<?> d) {
  if (a.size() >= b.size() && a.size() >= c.size() && a.size() >= d.size()) return a;
  if (b.size() >= a.size() && b.size() >= c.size() && b.size() >= d.size()) return b;
  if (c.size() >= a.size() && c.size() >= b.size() && c.size() >= d.size()) return c;
  if (d.size() >= a.size() && d.size() >= b.size() && d.size() >= c.size()) return d;
  return null; //impossible to reach
}

I know this is a very ugly solution, but it's easy to understand for java beginners, which I assume you are. If two or more Lists have the same size and are the longest, the first one of those will be returned.


问:
How do I know when an user call hide or show method on custom user control?
I have a custom user control. Is there any way to know when an user call hide or show methods ?

winforms, 2.0

答:
Theres a Visible Changed Event which is raised when control is shown or hidden or simply when its visibility is changed.

Remember that Hiding the control is equivalent to setting the Visible property to false. After the Hide method is called, the Visible property returns a value of false until the Show method is called.

Here is a sample code:

```<code>private void Button_Click(object sender, EventArgs e)
{
   myLabel.Visible = false;
}

///Somewhere in your form load or wherever you like
private void form1_Load(object sender, EventArgs e)
{
   myLabel.VisibleChanged += new EventHandler(this.Label_VisibleChanged);
}

private void Label_VisibleChanged(object sender, EventArgs e)
{
   MessageBox.Show("Visible change event raised!!!");
}
</code>```

Similarly you can do for any control, even User Control

ContentLicense: CC BY-SA 2.5

Body:
Theres a Visible Changed Event which is raised when control is shown or hidden or simply when its visibility is changed.

Remember that Hiding the control is equivalent to setting the Visible property to false. After the Hide method is called, the Visible property returns a value of false until the Show method is called.

Here is a sample code:

private void Button_Click(object sender, EventArgs e)
{
   myLabel.Visible = false;
}

///Somewhere in your form load or wherever you like
private void form1_Load(object sender, EventArgs e)
{
   myLabel.VisibleChanged += new EventHandler(this.Label_VisibleChanged);
}

private void Label_VisibleChanged(object sender, EventArgs e)
{
   MessageBox.Show("Visible change event raised!!!");
}

Similarly you can do for any control, even User Control


问:
Should I include adminlte in packages.json / composer.json file?
Should I include adminlte in packages.json / composer.json file?

Is there necessary to include it in my packages.json / composer.json for my FE library?

Or I just download the zip file add to my public/ folder will be easier?

Since I am using version control, I will easily find out the file changes.

Is anyone added to their packages.json / composer.json? What is the advantage?

Anyone mind to share their workflow. I found that everytime have new update. That will be challenged to update.

I think it is same goes to other Front End Framework.

答:
You have to include the needed functions, include the whole package if this isn't expressly needed could lead to additional security problems under certain circumstances.

I suggest you to give a look to AdminLTE structure.
https://adminlte.io/themes/AdminLTE/documentation/index.html


问:
Tableau Desktop : Use of COUNTD
my data is presented as follow.

```<code>Col1 Col2
A   x
A   x
A   y
B   x
C   z
</code>```

I simply want to represent Column 1 on a graph in the X axis with the number of unique references to of the data in Column 2 as Y axis.

Basically my graph would be like A (2) ;  B (1) ; C (1).

I'm not sure how to use COUNTD on that purpose.

答: Place Col1 on the Rows shelf and Number of Records measure in Text/value.

Title: Tableau Desktop : Use of COUNTD

Body:
my data is presented as follow.

Col1 Col2
A   x
A   x
A   y
B   x
C   z

I simply want to represent Column 1 on a graph in the X axis with the number of unique references to of the data in Column 2 as Y axis.

Basically my graph would be like A (2) ;  B (1) ; C (1).

I'm not sure how to use COUNTD on that purpose.


问:
Apple Script app help
I'm trying to make an applescript based app that can, with only one click, activate/deactivate both Network and Adium proxy settings. The Adium part is done.
What I cannot do is to make a switch/if_then_else statement to chose between:
Network / Location: "Automatic" and "uMinho" settings.
The script should select the unactive option.
Any ideas ?

Here is the script:

```<code>-- Activate Location "uminho"
tell application "Finder" to activate
tell application "System Events"
tell process "Finder"
    tell menu bar 1
        tell menu bar item "Apple"
        tell menu "Apple"
        tell menu item "Location"
            tell menu "Location"
 -- Need to switch between "Automatic" and "uMinho"
 -- Switch to the unactive one
                     click menu item "uMinho"
            end tell
            end tell
                end tell
            end tell
        end tell
    end tell
end tell

-- Activate adium proxy settings to all accounts
tell application "Adium" to activate
-- let's do this
tell application "System Events"
    tell process "Adium"
        -- open prefs
        keystroke "," using command down
        tell window 1
            -- open the accounts pane
            tell tool bar 1 to click button "Accounts"
            repeat with i from 1 to count of rows of table 1 of scroll area 1
                    -- tell group 1
                -- select the account
                set selected of row i of table 1 of scroll area 1 to true
                -- edit it
                click button "Edit"
                -- end tell
                tell sheet 1
                    tell tab group 1
                        -- open the personal info pane
                        click radio button "Proxy"
                        -- change the name, if one was provided
                        click checkbox "Connect using proxy"
                    end tell
                    click button "OK"
                end tell
            end repeat
            keystroke "w" using command down
        end tell
    end tell
end tell
</code>```

答:
In 10.5 or later this will work, else you can use the command line utility scselect to switch locations.</p>

```<code>tell application "System Events"
    tell network preferences
        set currentName to name of current location
        if currentName is "Automatic" then
            set current location to location "uMinho"
        else
            set current location to location "Automatic"
        end if
    end tell
end tell
</code>```

Title: Apple Script app help

Body:
I'm trying to make an applescript based app that can, with only one click, activate/deactivate both Network and Adium proxy settings. The Adium part is done.
What I cannot do is to make a switch/if_then_else statement to chose between:
Network / Location: "Automatic" and "uMinho" settings.
The script should select the unactive option.
Any ideas ?

Here is the script:

-- Activate Location "uminho"
tell application "Finder" to activate
tell application "System Events"
tell process "Finder"
    tell menu bar 1
        tell menu bar item "Apple"
        tell menu "Apple"
        tell menu item "Location"
            tell menu "Location"
 -- Need to switch between "Automatic" and "uMinho"
 -- Switch to the unactive one
                     click menu item "uMinho"
            end tell
            end tell
                end tell
            end tell
        end tell
    end tell
end tell

-- Activate adium proxy settings to all accounts
tell application "Adium" to activate
-- let's do this
tell application "System Events"
    tell process "Adium"
        -- open prefs
        keystroke "," using command down
        tell window 1
            -- open the accounts pane
            tell tool bar 1 to click button "Accounts"
            repeat with i from 1 to count of rows of table 1 of scroll area 1
                    -- tell group 1
                -- select the account
                set selected of row i of table 1 of scroll area 1 to true
                -- edit it
                click button "Edit"
                -- end tell
                tell sheet 1
                    tell tab group 1
                        -- open the personal info pane
                        click radio button "Proxy"
                        -- change the name, if one was provided
                        click checkbox "Connect using proxy"
                    end tell
                    click button "OK"
                end tell
            end repeat
            keystroke "w" using command down
        end tell
    end tell
end tell

Body:
In 10.5 or later this will work, else you can use the command line utility scselect to switch locations.

tell application "System Events"
    tell network preferences
        set currentName to name of current location
        if currentName is "Automatic" then
            set current location to location "uMinho"
        else
            set current location to location "Automatic"
        end if
    end tell
end tell


问:
ValueError: invalid literal for int() with base 10: ' ',on tkinter entry and Postgresql database
I tried to operate on tkinter entry ...
The value of that entry is used as integer type in the database..
I converted my entry value to integer as follows...

self.yr=(int(self.year.get()))

self.isb=(int(self.isbn.get()))

eventhough it throws ValueError..

How to convert string value from an ENTRY WIDGET to an integer value to be used as an argument for my search function in Postgresql database..

My Backend search function is: here in the code..[year,isbn are integer values]

```<code>def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        return row
</code>```

My Frontend code is:

```<code>from tkinter import *
from books_db import database

db=database()
class Window(object):
    def __init__(self,window):
            self.window=window
            self.window.wm_title("BOOK STORE")

    #############  ENTRIES.................
            self.title=Entry(window)
            self.title.grid(row=0,column=1)

            self.year=Entry(window)
            self.year.grid(row=1,column=1)
            self.yr=(int(self.year.get()))

            self.author=Entry(window)
            self.author.grid(row=0,column=3)

            self.isbn=Entry(window)
            self.isbn.grid(row=1,column=3)
            self.isb=(int(self.isbn.get()))

    ############  LISTBOX.................
            self.list=Listbox(window,height=6,width=35)
            self.list.grid(row=2,column=0,rowspan=6,columnspan=2)

    ########## BUTTONS...............

            b2=Button(window,text="SEARCH ENTRY",width=15,command=self.search_cmd)
            b2.grid(row=3,column=3)

    def search_cmd(self):
           self.list.delete(0,END)
           for item in db.search(self.title.get(),self.author.get(),self.yr,self.isb):
               self.list.insert(END,item)

window=Tk()
Window(window)
window.mainloop()
</code>```

答:
Consider these three lines of code:

```<code>self.isbn=Entry(window)
self.isbn.grid(row=1,column=3)
self.isb=(int(self.isbn.get()))
</code>```

You are creating a Entry widget, and about a microsecond later you are getting the value and converting it to an int. The user will not have even seen the entry widget, much less typed into it. Thus, the value will be the empty string, and the call to int() will fail.

Your code must wait to call get() until after the user has had a chance to enter data.

Body:
I tried to operate on tkinter entry ...
The value of that entry is used as integer type in the database..
I converted my entry value to integer as follows...

self.yr=(int(self.year.get()))

self.isb=(int(self.isbn.get()))

eventhough it throws ValueError..

How to convert string value from an ENTRY WIDGET to an integer value to be used as an argument for my search function in Postgresql database..

My Backend search function is: here in the code..[year,isbn are integer values]

def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        return row

My Frontend code is:

from tkinter import *
from books_db import database

db=database()
class Window(object):
    def __init__(self,window):
            self.window=window
            self.window.wm_title("BOOK STORE")

    #############  ENTRIES.................
            self.title=Entry(window)
            self.title.grid(row=0,column=1)

            self.year=Entry(window)
            self.year.grid(row=1,column=1)
            self.yr=(int(self.year.get()))

            self.author=Entry(window)
            self.author.grid(row=0,column=3)

            self.isbn=Entry(window)
            self.isbn.grid(row=1,column=3)
            self.isb=(int(self.isbn.get()))

    ############  LISTBOX.................
            self.list=Listbox(window,height=6,width=35)
            self.list.grid(row=2,column=0,rowspan=6,columnspan=2)

    ########## BUTTONS...............

            b2=Button(window,text="SEARCH ENTRY",width=15,command=self.search_cmd)
            b2.grid(row=3,column=3)

    def search_cmd(self):
           self.list.delete(0,END)
           for item in db.search(self.title.get(),self.author.get(),self.yr,self.isb):
               self.list.insert(END,item)

window=Tk()
Window(window)
window.mainloop()

Body:
Consider these three lines of code:

self.isbn=Entry(window)
self.isbn.grid(row=1,column=3)
self.isb=(int(self.isbn.get()))

You are creating a Entry widget, and about a microsecond later you are getting the value and converting it to an int. The user will not have even seen the entry widget, much less typed into it. Thus, the value will be the empty string, and the call to int() will fail.

Your code must wait to call get() until after the user has had a chance to enter data.


问:
exceptions throw or catch and try
I'm trying to learn java and I have a little problem with understanding how exceptions work.

When do we need to use throw after a condition?
As an example

```<code>public Ex(String name, String prenom, int age) throws exceptionex  {
    if (name.length() < 3 && prenom.length() < 3 && age < 1) throw new exceptionex();

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}
</code>```

excepetionex is an empty class which extends Exception.

And what is the difference between the previous example and this one?

```<code>public Ex(String name, String prenom, int age)   {
    if (name.length() < 3 && prenom.length() < 3 && age < 1)
        try {
            throw new exceptionex();
        } catch (exceptionex e) {
            e.printStackTrace();
        }

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}
</code>```

And what does printstackTrace exactly do?

Do we always need to create another class if we wanted to customise an exception (exeptionex here ) or we can just use (throw new Exception)?

I googled my questions but i didn't find an answer which i can understand maybe because I'm new or because English is not my native language I need a simple explanation as much as possible please.

答:
The first snippet will interrupt the flow of the program before assigning the age, name and prenom, returning the control to the caller method, which will need to catch the exception.

The second snippet wont interrupt the flow of the program. It will print the stacktrace (which will be only your exception) and then assgin age, name and prenom.

printStackTrace just outputs the stack of calls on standard output when an exception happens, so you can see the full hierarchy of method calls to triage the cause of the exception.

The common practice when throwing exceptions is to have subclasses of Exception or Throwable which provide semantical information about what kind of error is happening. You have probably already seen NullPointerException, for instance.

In the example you are providing, I guess you could rename your exception to something like IvalidPersonalDetailsException, so when it is thrown, the caller code can know what went wrong.

Title: exceptions throw or catch and try

Body:
I'm trying to learn java and I have a little problem with understanding how exceptions work.

When do we need to use throw after a condition?
As an example

public Ex(String name, String prenom, int age) throws exceptionex  {
    if (name.length() < 3 && prenom.length() < 3 && age < 1) throw new exceptionex();

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}

excepetionex is an empty class which extends Exception.

And what is the difference between the previous example and this one?

public Ex(String name, String prenom, int age)   {
    if (name.length() < 3 && prenom.length() < 3 && age < 1)
        try {
            throw new exceptionex();
        } catch (exceptionex e) {
            e.printStackTrace();
        }

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}

And what does printstackTrace exactly do?

Do we always need to create another class if we wanted to customise an exception (exeptionex here ) or we can just use (throw new Exception)?

I googled my questions but i didn't find an answer which i can understand maybe because I'm new or because English is not my native language I need a simple explanation as much as possible please.


问:
Logback-android: Log not getting writen to a file
Trying to redirect the log messages using logback-android, so that messages can be saved in a file. However, it is not getting saved into a file.

This is my logback.xml file configration, which is stored under src/main/assets in my Android Studio

```<code><configuration debug="true">
    <!-- Create a file appender for a log in the application's data directory -->
    <appender name="FILE" class="ch.qos.logback.classic.android.FileAppender">
        <file>/data/com.test.equa/files/log/foo.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- Write INFO (and higher-level) messages to the log file -->
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>
</code>```

This is piece of code where i am initiating the logging.

```<code> @Override
    public void onCreate() {
        super.onCreate();
        loadData();

        Logger log = LoggerFactory.getLogger(MyActivity.class);
        log.error("Application Data setup in progress");

    }
</code>```

Issue: I continue to see the messages in the logcat, but i expect them to be stored in my android sd card memory.

Added the user permission in manifest for writting the logs in the sd card

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Am i missing some thing in this configuration, as i don't see any errors or message in my logcat for any configuration errors also. Can some one help me here

答:
For me it was kind of solved by the first comment of Nija on the question.

My file tag now looks like this:

```<code><file>/sdcard/Android/data/[my-package-from-AndroidManifest]/logs.log</file>
</code>```

The weird think is though, that the logs.log file appeared on my internal storage under the given path (without /sdcard/).

My phone is running Android 6.0.1 in case thats relevant.

Concluding my answer is to try the above file path and check internal storage in case the other answers don't work.

Update:

Just wanted to open the log file on the computer, but couldn't find it. I can still find it with any storage access app (e.g. file commander) on the phone itself. But when looking at exactly the same folder with the PC it's not there. So check it out with a storage access app when that's good enough for you.

Body:
Trying to redirect the log messages using logback-android, so that messages can be saved in a file. However, it is not getting saved into a file.

This is my logback.xml file configration, which is stored under src/main/assets in my Android Studio

<configuration debug="true">

    <appender name="FILE" class="ch.qos.logback.classic.android.FileAppender">
        <file>/data/com.test.equa/files/log/foo.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>

This is piece of code where i am initiating the logging.

 @Override
    public void onCreate() {
        super.onCreate();
        loadData();

        Logger log = LoggerFactory.getLogger(MyActivity.class);
        log.error("Application Data setup in progress");

    }

Issue: I continue to see the messages in the logcat, but i expect them to be stored in my android sd card memory.

Added the user permission in manifest for writting the logs in the sd card

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Am i missing some thing in this configuration, as i don't see any errors or message in my logcat for any configuration errors also. Can some one help me here

Body:
For me it was kind of solved by the first comment of Nija on the question.

My file tag now looks like this:

<file>/sdcard/Android/data/[my-package-from-AndroidManifest]/logs.log</file>

The weird think is though, that the logs.log file appeared on my internal storage under the given path (without /sdcard/).

My phone is running Android 6.0.1 in case thats relevant.

Concluding my answer is to try the above file path and check internal storage in case the other answers don't work.

Update:

Just wanted to open the log file on the computer, but couldn't find it. I can still find it with any storage access app (e.g. file commander) on the phone itself. But when looking at exactly the same folder with the PC it's not there. So check it out with a storage access app when that's good enough for you.


问:
Get posts of users using *ngFor (angular + apollo + graphcool)
I have this query graphql in Graphcool:

```<code>const FeedQuery = gql`
     query FeedPosts($id:ID!){
          User(id:$id){
              id
              follows{
                 id
                 followed{
                     id
                     name
                     lastname
                     posts{
                        id
                        title
                        description
                        city
                        state
        } }} }}`;
</code>```

I tried to map using rxjs but I could only get the data from the "followed" level of the query ... How to get a list of "posts" using the apollo + angular * ngFor? ...

答:
I got the answer in this Topic …I changed the query to:

```<code>const FeedQuery = gql`
query FeedPosts($id: ID!){
 allPosts(filter:{
           user:{
          followedBy_some:{
               follower:{
                   id:$id
         }
         }
    }
 }) {
id
title
description
title
description
createdAt
user{
    id
    name
    }
   } } `;
</code>```

using _some can get the related fields

Body:
I have this query graphql in Graphcool:

const FeedQuery = gql`
     query FeedPosts($id:ID!){
          User(id:$id){
              id
              follows{
                 id
                 followed{
                     id
                     name
                     lastname
                     posts{
                        id
                        title
                        description
                        city
                        state
        } }} }}`;

I tried to map using rxjs but I could only get the data from the "followed" level of the query ... How to get a list of "posts" using the apollo + angular * ngFor? ...

Body:
I got the answer in this Topic …I changed the query to:

const FeedQuery = gql`
query FeedPosts($id: ID!){
 allPosts(filter:{
           user:{
          followedBy_some:{
               follower:{
                   id:$id
         }
         }
    }
 }) {
id
title
description
title
description
createdAt
user{
    id
    name
    }
   } } `;

using _some can get the related fields


问:
Determining the physical address from a virtual memory's page table
Assuming a virtual memory paging system with pages 4k long, I was given the following table

```<code>      P A M
0x003 1 1 0
0x04A 0 0 0
0xA78 1 1 1
0x0A1 1 0 0
0x000 1 0 0

*(P = presence digit, A = access digit, ; M = modified digit)*
</code>```

and asked what is the real address of 0x003A78.

I am a bit lost here, I guess the idea is to decompose 0x003A78 in 2? That'd be 0x003 A78, so it'd be (2 * 4k) + 0x078 ?

Is this it or am I completing off on this?

答:
The first colomn would be "number of physical page". You just have to use the number of virtual page (0x3A78 / 0x1000, that is 3) as index to that table.

The page is present, so the physical page number is correct, that means that the physical address would be 0xA1 * 0x1000 + 0xA78, or 0x0A1A78.

Body:
Assuming a virtual memory paging system with pages 4k long, I was given the following table

      P A M
0x003 1 1 0
0x04A 0 0 0
0xA78 1 1 1
0x0A1 1 0 0
0x000 1 0 0

*(P = presence digit, A = access digit, ; M = modified digit)*

and asked what is the real address of 0x003A78.

I am a bit lost here, I guess the idea is to decompose 0x003A78 in 2? That'd be 0x003 A78, so it'd be (2 * 4k) + 0x078 ?

Is this it or am I completing off on this?


问:
Message: Undefined property: CI_DB_mysqli_result::$level
I have a difficulty on my program. The error say :

A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_DB_mysqli_result::$level

Filename: controllers/Auth.php

Line Number: 30

Backtrace:

File:
  C:\xampp\htdocs\PKLTelkom\Telkom2\application\controllers\Auth.php
  Line: 30 Function: _error_handler

File: C:\xampp\htdocs\PKLTelkom\Telkom2\index.php Line: 315 Function:
  require_once

Here's my controller named "Auth" :

```<code><?php
/**
*
*/
class Auth extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('m_login');

    }

    public function index()
    {
        $this->load->view("login");
    }

    public function AksiLogin()
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $passwordx = md5($password);
        $login = $this->m_login->data_login($username, $passwordx);
        $tes = count($login);
        if ($tes > 0) {
            //ambil detail data
            $row = $this->m_login->data_login($username, $passwordx);
            $level = $row->level;
            //daftarkan session
            $data_session = array('level' => $level);
            $this->session->set_userdata($data_session);
            //direct page
            if ($level == 'superadmin') {
                redirect('superadmin');
            }
            else if ($level == 'admin') {
                redirect('admin');
            }

        }
        else {
            $this->index();
        }
    }

    public function logout()
    {
        $this->session->unset_userdata("login");
        $this->session->unset_userdata("username");
        redirect ('index.php/auth');
    }
    }
?>
</code>```

Here's my models named "M_Login" :

```<code><?php
class M_login extends CI_Model
{

function data_login($username, $password)
{
 $this->db->where('username', $username);
 $this->db->where('password', $password);
 return $this->db->get('akun');
}
}
?>
</code>```

答:
Looks like your return $this->db->get('akun'); on "M_login" model doesn't return object with the name level.

Try changing this line on "M_Login" model :

```<code><?php
class M_login extends CI_Model
{

function data_login($username, $password)
{
$this->db->where('username', $username);
$this->db->where('password', $password);
return $this->db->get('akun')->row(); // change this line
}
}
?>
</code>```

Body:
I have a difficulty on my program. The error say :

A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_DB_mysqli_result::$level

Filename: controllers/Auth.php

Line Number: 30

Backtrace:

File:
  C:\xampp\htdocs\PKLTelkom\Telkom2\application\controllers\Auth.php
  Line: 30 Function: _error_handler

File: C:\xampp\htdocs\PKLTelkom\Telkom2\index.php Line: 315 Function:
  require_once

Here's my controller named "Auth" :

<?php
/**
*
*/
class Auth extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('m_login');

    }

    public function index()
    {
        $this->load->view("login");
    }

    public function AksiLogin()
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $passwordx = md5($password);
        $login = $this->m_login->data_login($username, $passwordx);
        $tes = count($login);
        if ($tes > 0) {
            //ambil detail data
            $row = $this->m_login->data_login($username, $passwordx);
            $level = $row->level;
            //daftarkan session
            $data_session = array('level' => $level);
            $this->session->set_userdata($data_session);
            //direct page
            if ($level == 'superadmin') {
                redirect('superadmin');
            }
            else if ($level == 'admin') {
                redirect('admin');
            }

        }
        else {
            $this->index();
        }
    }

    public function logout()
    {
        $this->session->unset_userdata("login");
        $this->session->unset_userdata("username");
        redirect ('index.php/auth');
    }
    }
?>

Here's my models named "M_Login" :

<?php
class M_login extends CI_Model
{

function data_login($username, $password)
{
 $this->db->where('username', $username);
 $this->db->where('password', $password);
 return $this->db->get('akun');
}
}
?>

Body:
Looks like your return $this->db->get('akun'); on "M_login" model doesn't return object with the name level.

Try changing this line on "M_Login" model :

<?php
class M_login extends CI_Model
{

function data_login($username, $password)
{
$this->db->where('username', $username);
$this->db->where('password', $password);
return $this->db->get('akun')->row(); // change this line
}
}
?>


问:
Shiny interactive plotting with selected likert scale
I have created several likert scales with R package "likert" and would like to plot each one of them in shiny when the radio button of that one is selected.
The sample scales is:

```<code>a <- sample(rep((1:5),5))
b <- sample(rep((1:5),5))
c <- data.frame(sapply(data.frame(a), factor))
d <- data.frame(sapply(data.frame(b), factor))
scaledc <- likert(c)
scaledd <- likert(d)
</code>```

The shiny codes are:

```<code>ui <- fluidPage(
  titlePanel("Survey"),
  sidebarLayout(
    sidebarPanel(
      selectInput("type",
                  "Plot Type",
                  choices = c("Likert"="bar",
                              "Density"="density",
                              "Heatmap"="heat"), selected="Likert"),
      radioButtons("qtype",
                    "Question type:",
                    c("Agreement"="scaledc", "Helpfulness"="scaledd"),
                selected="scaledc")
  ),

# Show a plot of the generated distribution
mainPanel(
  tabsetPanel(
    tabPanel("Yearly Data", plotOutput("distPlot1"))
      )
    )
  )
)

#server
server <- function(input, output) {
  output$distPlot1 <- renderPlot({plot(input$qtype, type=input$type)+
      ggtitle("How agree are you with following statements?")}, height = 1000)

}
</code>```

The shiny returned error "need finite 'ylim' values." I think it's becaue the input$qtype doesn't pass the correct information to the plot command, but I don't know how to fix it. Thank you for advance!

答:
I've just solved the problem.
The missing codes in server are:

```<code>  scale <- reactive({
   get(input$qtype)
})
  output$dat <- renderPrint({
   scale()
})
</code>```

And then do plot with scale() will show selected plot.

Body:
I have created several likert scales with R package "likert" and would like to plot each one of them in shiny when the radio button of that one is selected.
The sample scales is:

a <- sample(rep((1:5),5))
b <- sample(rep((1:5),5))
c <- data.frame(sapply(data.frame(a), factor))
d <- data.frame(sapply(data.frame(b), factor))
scaledc <- likert(c)
scaledd <- likert(d)

The shiny codes are:

ui <- fluidPage(
  titlePanel("Survey"),
  sidebarLayout(
    sidebarPanel(
      selectInput("type",
                  "Plot Type",
                  choices = c("Likert"="bar",
                              "Density"="density",
                              "Heatmap"="heat"), selected="Likert"),
      radioButtons("qtype",
                    "Question type:",
                    c("Agreement"="scaledc", "Helpfulness"="scaledd"),
                selected="scaledc")
  ),

# Show a plot of the generated distribution
mainPanel(
  tabsetPanel(
    tabPanel("Yearly Data", plotOutput("distPlot1"))
      )
    )
  )
)

#server
server <- function(input, output) {
  output$distPlot1 <- renderPlot({plot(input$qtype, type=input$type)+
      ggtitle("How agree are you with following statements?")}, height = 1000)

}

The shiny returned error "need finite 'ylim' values." I think it's becaue the input$qtype doesn't pass the correct information to the plot command, but I don't know how to fix it. Thank you for advance!

Body:
I've just solved the problem.
The missing codes in server are:

  scale <- reactive({
   get(input$qtype)
})
  output$dat <- renderPrint({
   scale()
})

And then do plot with scale() will show selected plot.


问:
ModelMapper: how to handle null values for enums
I am trying to map one object type to another using ModelMapper.
I have defined the following mapping in my PropertyMap implementation:

```<code>map().getExtended().setIncludeMaskType(MaskType.fromValue(source.getExtendedPollingType().getMaskSettings().getIncludeMask().getMaskType()));
</code>```

The problem is that the source type method call source.getExtendedPollingType().getMaskSettings().getIncludeMask().getMaskType()
returns String while the destination type accepts a MaskType enum

Therefore I am using MaskType.fromValue() to convert the String to enum.
The problem is that value of fails with Caused by: java.lang.IllegalArgumentException since this is source method call basically returns null during configuration.

So how should I handle this use case?

答:
OK seems that the correct way to do this is with using a Converter:

```<code>using((MappingContext<String, MaskType> context) -> {
    return MaskType.fromValue(context.getSource());
}).
map(source.getExtendedPollingType().getMaskSettings().getIncludeMask().getMaskType()).getExtended().setIncludeMaskType(null);
</code>```

This is explained in more details here:
https://github.com/modelmapper/modelmapper/issues/20

Body:
I am trying to map one object type to another using ModelMapper.
I have defined the following mapping in my PropertyMap implementation:

map().getExtended().setIncludeMaskType(MaskType.fromValue(source.getExtendedPollingType().getMaskSettings().getIncludeMask().getMaskType()));

The problem is that the source type method call source.getExtendedPollingType().getMaskSettings().getIncludeMask().getMaskType()
returns String while the destination type accepts a MaskType enum

Therefore I am using MaskType.fromValue() to convert the String to enum.
The problem is that value of fails with Caused by: java.lang.IllegalArgumentException since this is source method call basically returns null during configuration.

So how should I handle this use case?

Body:
OK seems that the correct way to do this is with using a Converter:

using((MappingContext<String, MaskType> context) -> {
    return MaskType.fromValue(context.getSource());
}).
map(source.getExtendedPollingType().getMaskSettings().getIncludeMask().getMaskType()).getExtended().setIncludeMaskType(null);

This is explained in more details here:
https://github.com/modelmapper/modelmapper/issues/20


问:
How to slice particular values from a string using regular expression in JavaScript or Java
How do I slice, and get only string values excluding characters inside {} braces.

I'm able to get characters inside curly braces, but how to get contents outside the curly braces?

I have a string like this:

name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}

I want output array like this:

["the name is","and disease is","and drug is"]

答:
Instead of matching content inside brackets you can just split by content between brackets.

In JavaScript you can use .split() function with this regex /{\[\w\.\]+}/i:

```<code>var str = 'name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}';
var arr = str.split(/{[\w\.]+}/).filter(s => s != "");
</code>```

Demo:

var str = 'name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}';
var arr = str.split(/{[\w\.]+}/).filter(s => s != "");
console.log(arr);```

Body:
Instead of matching content inside brackets you can just split by content between brackets.

In JavaScript you can use .split() function with this regex /{\[\w\.\]+}/i:

var str = 'name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}';
var arr = str.split(/{[\w\.]+}/).filter(s => s != "");

Demo:

var str = 'name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}';
var arr = str.split(/{[\w\.]+}/).filter(s => s != "");
console.log(arr);


问:
Checkbox next to collapsable details summary in ng-repeat
I want to place a checkbox next to the expandable summary of a details element which is inside a ng-repeat.

It all looks fine initially, but when I click on the expand arrow, the checkbox gets places inside the summary instead of next to the arrow. The checkbox must be inside the ng-repeat because I need the $index in my checkbox ng-click function:

```<code><div ng-repeat="n in ctrl.array track by $index">
        <input type="checkbox" style="display: inline-block"
               ng-model="ctrl.checked[$index]" ng-click="ctrl.setSelected($index)">
        <details style="display: inline-block">
            <summary>Display something (element {{$index + 1}})</summary>
            <iframe></iframe>
        </details>
    </div>
</code>```

答:
I found a solution. I just have to use

```<code>style="float: left"
</code>```

for the input element. That's it. No further styling of the details element needed.

Body:
I want to place a checkbox next to the expandable summary of a details element which is inside a ng-repeat.

It all looks fine initially, but when I click on the expand arrow, the checkbox gets places inside the summary instead of next to the arrow. The checkbox must be inside the ng-repeat because I need the $index in my checkbox ng-click function:

        <input type="checkbox" style="display: inline-block"
               ng-model="ctrl.checked[$index]" ng-click="ctrl.setSelected($index)">

            Display something (element {{$index + 1}})

Body:
I found a solution. I just have to use

style="float: left"

for the input element. That's it. No further styling of the details element needed.


问:
Compare strings in List 1 with values in List 2, and export to new location
I'm trying to compare 2 .csv files against each other - the first looks like this (list1.csv):

```<code>london,
clapham,
brighton,
oxford,
elephant and castle,
</code>```

This is effectively a list of locations, that has a total length of over 20,000  rows (locations)

The sheet that I am comparing this against looks like this (but has a lot of random words in)(list2.csv):

```<code>iron service,
ironing london,
laundry chelmsford,
dry cleaners elephant and castle,
laundry in oxford,
</code>```

The output that I am aiming for would be:

```<code>ironing london,
laundry chelmsford,
dry cleaners elephant and castle,
laundry in oxford,
</code>```

I am trying to use grep to accomplish this, but the data that i get has a number of unrelated words (that are in my second list). I am effectively trying to compare 'strings' in list1.csv - that can contain spaces - with data in the list2.csv. If the string shows up anywhere in a line in list 2, I want that line exported to a new location "list3"

grep that I am using:

```<code>grep -F list1.csv list2.csv > list3.csv
</code>```

from what i can see from the output, the 'strings' are not being treated as such from list1.csv, and instead are being treated as single words - so if a string contains 2 words, it will extract a line that has either of those words.

答:
Simple grep approach:

```<code>grep -Ff list1.csv list2.csv
</code>```

Body:
I'm trying to compare 2 .csv files against each other - the first looks like this (list1.csv):

london,
clapham,
brighton,
oxford,
elephant and castle,

This is effectively a list of locations, that has a total length of over 20,000  rows (locations)

The sheet that I am comparing this against looks like this (but has a lot of random words in)(list2.csv):

iron service,
ironing london,
laundry chelmsford,
dry cleaners elephant and castle,
laundry in oxford,

The output that I am aiming for would be:

ironing london,
laundry chelmsford,
dry cleaners elephant and castle,
laundry in oxford,

I am trying to use grep to accomplish this, but the data that i get has a number of unrelated words (that are in my second list). I am effectively trying to compare 'strings' in list1.csv - that can contain spaces - with data in the list2.csv. If the string shows up anywhere in a line in list 2, I want that line exported to a new location "list3"

grep that I am using:

grep -F list1.csv list2.csv > list3.csv

from what i can see from the output, the 'strings' are not being treated as such from list1.csv, and instead are being treated as single words - so if a string contains 2 words, it will extract a line that has either of those words.

Body:
Simple grep approach:

grep -Ff list1.csv list2.csv


问:
Hindi text not rendered properly in android
I'm working on an app where I have to show text received from a server response in a textview. The text could be in English or Hindi. In case of hindi, some of the letter are replaced by question marks (?). What is the issue here?
This is how I set my text. Android version 6. Font type- Proxima Nova Alt Regular

```<code> for (int i = 0; i < 3; i++) {
 viewHolder.lines[i].setText(poem.lines[i].lineText);
 }
</code>```

答:
Download Hindi Font From Here : http://fonts.webtoolhub.com/font-n17979-kruti-dev-010.aspx

put this font in "assets" folder : app/src/main/assets/kruti-dev-010.ttf

```<code>Typeface hindiFont = Typeface.createFromAsset(MainActivity.this.getAssets(), "fonts/Kruti_Dev_010.ttf");
    txtFont.setTypeface(hindiFont);
    txtFont.setText("एनडीटीवी इंडिया : हिन्दी समाचार की आधिकारिक वेबसाइट");
</code>```

Body:
I'm working on an app where I have to show text received from a server response in a textview. The text could be in English or Hindi. In case of hindi, some of the letter are replaced by question marks (?). What is the issue here?
This is how I set my text. Android version 6. Font type- Proxima Nova Alt Regular

 for (int i = 0; i < 3; i++) {
 viewHolder.lines[i].setText(poem.lines[i].lineText);
 }

Body:
Download Hindi Font From Here : http://fonts.webtoolhub.com/font-n17979-kruti-dev-010.aspx

put this font in "assets" folder : app/src/main/assets/kruti-dev-010.ttf

Typeface hindiFont = Typeface.createFromAsset(MainActivity.this.getAssets(), "fonts/Kruti_Dev_010.ttf");
    txtFont.setTypeface(hindiFont);
    txtFont.setText("एनडीटीवी इंडिया : हिन्दी समाचार की आधिकारिक वेबसाइट");


问:
set_block_property with multiple columns for order by clause
I am working on a form where I have 3 lov fields in data block which represents the column names for the query to sort.

How can I set the set_block_property to take more than one column and then sort accordingly.

Eg:

```<code>set_block_property('table name', order by, column1, column2, column3)
</code>```

at present it is giving error as too many arguments.

答:
in Oracle Forms, Set_Block_Property should have three arguments as the following example with Order_by clause:

```<code>declare
  v_order varchar2(500);
begin
  if ( :system.mode = 'ENTER-QUERY' ) then
   v_order := 'column1,column2,column3'
   Set_Block_Property('myblock',Order_By,v_order);
   Go_Block('myblock');
   Execute_Query;
  else
   v_order := null;
   Go_Block('myblock');
   Enter_Query;
  end;
end;
</code>```

Body:
I am working on a form where I have 3 lov fields in data block which represents the column names for the query to sort.

How can I set the set_block_property to take more than one column and then sort accordingly.

Eg:

set_block_property('table name', order by, column1, column2, column3)

at present it is giving error as too many arguments.

Body:
in Oracle Forms, Set_Block_Property should have three arguments as the following example with Order_by clause:

declare
  v_order varchar2(500);
begin
  if ( :system.mode = 'ENTER-QUERY' ) then
   v_order := 'column1,column2,column3'
   Set_Block_Property('myblock',Order_By,v_order);
   Go_Block('myblock');
   Execute_Query;
  else
   v_order := null;
   Go_Block('myblock');
   Enter_Query;
  end;
end;


问:
Create json file out of a multidimensional array
I have a multi dimensional array that consists of 3 arrays inside. See below my minimum runnable example:

```<code><?php

$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

//Multi Dimensional Array
$multi = array($array1, $array2, $array3);
print_r($multi);

foreach($multi as $k =>$a){
  $multi[$k] = json_decode(json_encode($a));
}

print_r($multi);

// $json_data = json_encode($multi);
file_put_contents('data/myfile.json', $multi);
</code>```

However, I get the following output in my output file:

```<code>ArrayArrayArray
</code>```

Any suggestions how to get the data like the following:

```<code>{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},
</code>```

答:
```<code>{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},
</code>```

Is not valid JSON format. '{' and '}' means that it's map (object), so there must be 'key:value' rows like:

```<code>{
0: "Bitcoin"
}
</code>```

Proper JSON for array uses '[' and ']'.

```<code><?php
$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

//Multi Dimensional Array
$multi = array();
foreach($array1 as $key => $v) {
    $multi[] = [$array1[$key], $array2[$key], $array3[$key]];
}

file_put_contents('data/myfile.json', json_encode($multi));
</code>```

Produces:

```<code>[["Bitcoin","BTC","10000"],["Ethereum","ETH","3000"],["Bitcoin Cash","BTC","6666"]]
</code>```

Formated:

```<code>[
    [
        "Bitcoin",
        "BTC",
        "10000"
    ],
    [
        "Ethereum",
        "ETH",
        "3000"
    ],
    [
        "Bitcoin Cash",
        "BTC",
        "6666"
    ]
]
</code>```

Body:
I have a multi dimensional array that consists of 3 arrays inside. See below my minimum runnable example:

<?php

$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

//Multi Dimensional Array
$multi = array($array1, $array2, $array3);
print_r($multi);

foreach($multi as $k =>$a){
  $multi[$k] = json_decode(json_encode($a));
}

print_r($multi);

// $json_data = json_encode($multi);
file_put_contents('data/myfile.json', $multi);

However, I get the following output in my output file:

ArrayArrayArray

Any suggestions how to get the data like the following:

{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},

Body:
{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},

Is not valid JSON format. '{' and '}' means that it's map (object), so there must be 'key:value' rows like:

{
0: "Bitcoin"
}

Proper JSON for array uses '[' and ']'.

<?php
$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

//Multi Dimensional Array
$multi = array();
foreach($array1 as $key => $v) {
    $multi[] = [$array1[$key], $array2[$key], $array3[$key]];
}

file_put_contents('data/myfile.json', json_encode($multi));

Produces:

[["Bitcoin","BTC","10000"],["Ethereum","ETH","3000"],["Bitcoin Cash","BTC","6666"]]

Formated:

[
    [
        "Bitcoin",
        "BTC",
        "10000"
    ],
    [
        "Ethereum",
        "ETH",
        "3000"
    ],
    [
        "Bitcoin Cash",
        "BTC",
        "6666"
    ]
]


问:
How can I count the number of seconds a window is open?
I'm trying to write a script where I need a timer to count the number of seconds a popup is open. I'm new to programming but I assume you use javascript for it?</p>

答:
Within the pop-up, you can use the unload event of the window object to detect the window closing or navigating to a new page, having previously recorded the time it opened at the the top of the document. For example:

```<code><html>
  <head>
    <script type="text/javascript">
      var start = new Date();

      window.onunload = function() {
        var end = new Date();
        var secondsOpen = Math.floor((end - start) / 1000);
        alert("Pop-up was open for " + secondsOpen + " seconds");
      };
    </script>
  </head>
  <body>
     ...
  </body>
</html>
</code>```

Body:
Within the pop-up, you can use the unload event of the window object to detect the window closing or navigating to a new page, having previously recorded the time it opened at the the top of the document. For example:

<html>
  <head>
    <script type="text/javascript">
      var start = new Date();

      window.onunload = function() {
        var end = new Date();
        var secondsOpen = Math.floor((end - start) / 1000);
        alert("Pop-up was open for " + secondsOpen + " seconds");
      };
    </script>
  </head>
  <body>
     ...
  </body>
</html>


问:
Get Variation ID and Attribute Value on Product page
I wish to have a Quick Buy (Flipkart like) button on product page. Clicking on this button adds the selected product to cart and gets the user to the checkout (not on the cart page). Also note here that the user is not redirected to the cart page and takes the user in the checkout process as far as possible. I also do not want to replace default “add to cart” button, instead, I want to add another button that says Quickbuy. Can you help me with this?

What I have figured out so far?
Well, I have tried and create a URL structure that add products to cart and goes to checkout, something like this.

https://www.similarfeathers.com/checkout/?add-to-cart=6711&variation_id=6714&attribute_pa_size=M

(6711 being the product ID, 6714 being that variable ID, M being that size (attribute)).
Now, I want to add this hyperlink, that gets generated dynamically on the product page, takes the value of size attribute from the dropdown and get variationID. When a user will click this URL, my job will be done.

Any way to create the custom hyperlink URL on the product page?

答:
global $product;</p>

```<code>    $args = array(
                 'post_type'     => 'product_variation',
                 'post_status'   => array( 'private', 'publish' ),
                 'numberposts'   => -1,
                 'orderby'       => 'menu_order',
                 'order'         => 'asc',
                 'post_parent'   => $product->id
             );
             $variations = get_posts( $args );

    foreach ( $variations as $variation ) {

                echo  $variation_id           = absint( $variation->ID );$variable_id = $this['variation_id'];
                 $variation_post_status  = esc_attr( $variation->post_status );

                 $variation_data         = get_post_meta( $variation_id );
                 $variation_data['variation_post_id'] = $variation_id;

             echo get_post_meta( $variation_data['variation_post_id'], 'variable_regular_price[]', true) . '<br>';

                echo $id = $product->id.'<br>';
                 echo $price =get_post_meta($variation_id, '_regular_price', true).'<br>';
                 //echo $variation['image_src'];

             }
</code>```

Body:
global $product;

    $args = array(
                 'post_type'     => 'product_variation',
                 'post_status'   => array( 'private', 'publish' ),
                 'numberposts'   => -1,
                 'orderby'       => 'menu_order',
                 'order'         => 'asc',
                 'post_parent'   => $product->id
             );
             $variations = get_posts( $args );

    foreach ( $variations as $variation ) {

                echo  $variation_id           = absint( $variation->ID );$variable_id = $this['variation_id'];
                 $variation_post_status  = esc_attr( $variation->post_status );

                 $variation_data         = get_post_meta( $variation_id );
                 $variation_data['variation_post_id'] = $variation_id;

             echo get_post_meta( $variation_data['variation_post_id'], 'variable_regular_price[]', true) . '<br>';

                echo $id = $product->id.'<br>';
                 echo $price =get_post_meta($variation_id, '_regular_price', true).'<br>';
                 //echo $variation['image_src'];

             }


问:
Merge PDF's with PDFTK with Bookmarks?
Using pdftk to merge multiple pdf's is working well. However, any easy way to make a bookmark for each pdf merged?

I don't see anything on the pdftk docs regarding this so I don't think it's possible with pdftk.

All of our files merged will be 1 page, so wondering if there's any other utility that can add in bookmarks afterwards?

Or another linux based pdf utility that will allow to merge while specifying a bookmark for each individual pdf.

答:
Sejda PDF (which was suggested in one of the answers) is also available as an online service: https://www.sejda.com/merge-pdf.

This might come in handy if you don't want to install any additional software and prefer working online from a browser.

Steps to merge:

Drag and drop all PDF files to the web page

By default all existing bookmarks are preserved and will work in the merged document as well.

Optionally, the merge tool can build a table of contents based on the PDF documents being combined

The online service to merge PDF files is free to use for up to 30 files per hour and files up to 50Mb/200 pages.

Disclaimer: I'm an open source dev working on Sejda.

Title: Merge PDF's with PDFTK with Bookmarks?


问:
Is it a good practice to re-create a Topic Client before sending a message to Azure Topic
I am using Microsoft.Azure.ServiceBus, Version=2.0.0.0 assembly to connect to Azure Topics. The code is below

```<code>public void SendMessage(Message brokeredMessage)
{
    var topicClient = new TopicClient(_configuration.ConnectionString, topicName, _defaultRetryPolicy);
    await topicClient.SendAsync(brokeredMessage);
    await topicClient.CloseAsync();
}
</code>```

I was wondering whether it's a good practice to create the Topic Client every time I need to send a message to the topic, or should I create the Topic Client on application startup and keep using the same client every time I need to send a message?

Are there any performance or scalability issues that I need to consider?

答:
From Azure Service Bus Best Practices post:

Reusing factories and clients

Service Bus client objects, such as QueueClient or MessageSender, are
  created through a MessagingFactory object, which also provides
  internal management of connections. You should not close messaging
  factories or queue, topic, and subscription clients after you send a
  message, and then re-create them when you send the next message.
  Closing a messaging factory deletes the connection to the Service Bus
  service, and a new connection is established when recreating the
  factory. Establishing a connection is an expensive operation that you
  can avoid by re-using the same factory and client objects for multiple
  operations. You can safely use the QueueClient object for sending
  messages from concurrent asynchronous operations and multiple threads.

Based on this, you should be reusing the Topic Client object.

Body:
I am using Microsoft.Azure.ServiceBus, Version=2.0.0.0 assembly to connect to Azure Topics. The code is below

public void SendMessage(Message brokeredMessage)
{
    var topicClient = new TopicClient(_configuration.ConnectionString, topicName, _defaultRetryPolicy);
    await topicClient.SendAsync(brokeredMessage);
    await topicClient.CloseAsync();
}

I was wondering whether it's a good practice to create the Topic Client every time I need to send a message to the topic, or should I create the Topic Client on application startup and keep using the same client every time I need to send a message?

Are there any performance or scalability issues that I need to consider?


问:
Unable to check response size with Rack Deflater
I'm trying to use Rack::Deflater to compress responses when the body is greater than 512 bytes in size.

Using the example given in the latest Rack Deflater source code in my config.ru I get the following error:

/gems/rack-1.5.5/lib/rack/deflater.rb:20:in `initialize': wrong number
  of arguments (2 for 1) (ArgumentError)

Any idea what I'm doing wrong here? Any documentation I've found online suggests the syntax I'm using is correct. I'm using RoR 4 and Rack 1.5.5.

This is my config.ru file in its entirety:

```<code>require ::File.expand_path('../config/environment',  __FILE__)
require 'rack'

use Rack::Deflater, :if => lambda { |*, body| sum=0; body.each { |i| sum += i.length }; sum > 512 }

run Rails.application
</code>```

I suspect it's some kind of versioning error but I'm unsure.

答:
Yes, you are right. It's version issue. You paste code from the very last version (2.0.3/2.0.4), but according to your trace you have 1.5.5 in your local setup.

Here you can see that Rack::Deflater doesn't accept any additional options in 1.5.5 -- https://github.com/rack/rack/blob/1.5.5/lib/rack/deflater.rb#L20

Firstly options were added in the very next release 1.6.0.beta. You can see that here -- https://github.com/rack/rack/blob/1.6.0.beta/lib/rack/deflater.rb#L28

Updating your rack should solve your issue for you

Body:
I'm trying to use Rack::Deflater to compress responses when the body is greater than 512 bytes in size.

Using the example given in the latest Rack Deflater source code in my config.ru I get the following error:

/gems/rack-1.5.5/lib/rack/deflater.rb:20:in `initialize': wrong number
  of arguments (2 for 1) (ArgumentError)

Any idea what I'm doing wrong here? Any documentation I've found online suggests the syntax I'm using is correct. I'm using RoR 4 and Rack 1.5.5.

This is my config.ru file in its entirety:

require ::File.expand_path('../config/environment',  __FILE__)
require 'rack'

use Rack::Deflater, :if => lambda { |*, body| sum=0; body.each { |i| sum += i.length }; sum > 512 }

run Rails.application

I suspect it's some kind of versioning error but I'm unsure.


问:
Find a character in a data frame and change adjacent rows
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

```<code>data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])
</code>```

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

答:
If I understood you correct the following might work. I am not sure, if it will work for your large data frame.</p>

```<code>df<-data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])
u<-df=='h'
v<-rbind(u[6:26,], matrix(nrow=5, ncol=3, FALSE))
df[u|v]=NA
</code>```

Body:
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

Body:
If I understood you correct the following might work. I am not sure, if it will work for your large data frame.

df<-data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])
u<-df=='h'
v<-rbind(u[6:26,], matrix(nrow=5, ncol=3, FALSE))
df[u|v]=NA