问:
WordPress site returns 404 for any page other than home
I've also put this post on the WP Stackexchange but figured a htaccess/rewrites genius may be able to fix it here as well as there.

My WordPress site is returning a 404 not found error on any page apart from the homepage and /wp-admin. I have no absolutely no idea why this is. My Permalinks are set up to use /year/month/date/post-title/ (e.g www.domain.com/2014/04/28/sample-post/). When I change the permalinks to the default (?p=123) it works fine, but not on any of the other ones.
Here is the contents of the .htaccess file:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

I have also installed the plugin 'Debug This', which provides details on the Rewrite Rules. However because it's a pretty big list and unformatted it would look quite bad, I've put it in a jsfiddle, here: http://jsfiddle.net/k8PHD/embedded/result/

I think that's all the details I have, I've disabled all plugins and stuff like that. Thanks for any help.

答:
Its a very common problem that we face once in a time while working on word press
so don't panic ,usually it  happens if your .htaccess file got deleted or something went wrong with the rewrite rules. What you need to do is just fix your permalinks settings.
just go to Settings ->Permalink and click on save changes button this will flush out all rewrite rules and your website works fine.</p>

Body:
I've also put this post on the WP Stackexchange but figured a htaccess/rewrites genius may be able to fix it here as well as there.

My WordPress site is returning a 404 not found error on any page apart from the homepage and /wp-admin. I have no absolutely no idea why this is. My Permalinks are set up to use /year/month/date/post-title/ (e.g www.domain.com/2014/04/28/sample-post/). When I change the permalinks to the default (?p=123) it works fine, but not on any of the other ones.
Here is the contents of the .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I have also installed the plugin 'Debug This', which provides details on the Rewrite Rules. However because it's a pretty big list and unformatted it would look quite bad, I've put it in a jsfiddle, here: http://jsfiddle.net/k8PHD/embedded/result/

I think that's all the details I have, I've disabled all plugins and stuff like that. Thanks for any help.


来源: stackexchange

问:
Gson malformedJsonException when casting Json string to object
I have created a Json string using Gson which is valid.I used following way to create the Json object.

```<code>Map myMap=new HashMap();
myMap.put("dryRunTest",dryRunTestObj);
myMap.put("port",22);
myMap.put("Repository",RepositoryObj);
etc...

Map temp = new HashMap();
temp.put("configuration",myMap);
new GsonBuilder().setPrettyPrinting().create().toJson(temp);
//This gave me the below Json Object that would write to a file.

{
  "configuration": {
    "dryRunTest": {
      "id": null,
      "defaultName": "sample.xml",
      "ParamsMap": null,
      "defaultVersion": "1.2",
      "dryRunTestOn": true
    },
    "port": 2323,
    "ip": "11.11.11.111",
    "configFile": "config.json",
    "Name": "007",
    "URL": "http://11.111.111.51/ma/api/ag/",
    "Password": "123",
    "configDirectory": "sss",
    "platform": "Windows7",
    "Repository": {
      "repositoryURL": "http://11.11.111.11/"
    }
  }
}
</code>```

I have tried to create Repository object using Repository Json string like following.

```<code>class Repository{
String repositoryURL;
getter and setters
}
</code>```

Then i desalinize serialize Json object using,

```<code> Map mymap= new Gson().fromJson(JsonObjectReadFromFile(aboveString), HashMap.class);

RepositoryJsonStringvalue = mymap.get("Repository");

Repository r=new Gson().fromJson(RepositoryJsonStringvalue, Repository.class);
</code>```

It return following exception.

```<code>com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 21
</code>```

Seems like problem was with it value repositoryURL but i put same value into another top level attribute URL=http://11.11.111.11/ and then can get values but when it put inside object type it throws that error.Please let me know how to fix this.

Note:I found out problem was in repositoryURL attribute if i remove special characters : \ from string i can cast to the Repository object.So i would like to know how can i put URLhttp://11.11.111.11/ in to json object even my above object is valid Json.

答:
You can try converting the string to json string  before converting it to object via gson.
This happens in case of a map where you get an object if you do  map.get(key).

The object wont have quotes "" around key or value.

While converting to json  before , will ensure that.

```<code>RepositoryJsonStringvalue = mymap.get("Repository");
String jsonString = new Gson().toJson(RepositoryJsonStringvalue).toString();
Repository r=new Gson().fromJson(jsonString, Repository.class);
</code>```

Hope it helps

ContentLicense: CC BY-SA 3.0

Body:
I have created a Json string using Gson which is valid.I used following way to create the Json object.

Map myMap=new HashMap();
myMap.put("dryRunTest",dryRunTestObj);
myMap.put("port",22);
myMap.put("Repository",RepositoryObj);
etc...

Map temp = new HashMap();
temp.put("configuration",myMap);
new GsonBuilder().setPrettyPrinting().create().toJson(temp);
//This gave me the below Json Object that would write to a file.

{
  "configuration": {
    "dryRunTest": {
      "id": null,
      "defaultName": "sample.xml",
      "ParamsMap": null,
      "defaultVersion": "1.2",
      "dryRunTestOn": true
    },
    "port": 2323,
    "ip": "11.11.11.111",
    "configFile": "config.json",
    "Name": "007",
    "URL": "http://11.111.111.51/ma/api/ag/",
    "Password": "123",
    "configDirectory": "sss",
    "platform": "Windows7",
    "Repository": {
      "repositoryURL": "http://11.11.111.11/"
    }
  }
}

I have tried to create Repository object using Repository Json string like following.

class Repository{
String repositoryURL;
getter and setters
}

Then i desalinize serialize Json object using,

 Map mymap= new Gson().fromJson(JsonObjectReadFromFile(aboveString), HashMap.class);

RepositoryJsonStringvalue = mymap.get("Repository");

Repository r=new Gson().fromJson(RepositoryJsonStringvalue, Repository.class);

It return following exception.

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 21

Seems like problem was with it value repositoryURL but i put same value into another top level attribute URL=http://11.11.111.11/ and then can get values but when it put inside object type it throws that error.Please let me know how to fix this.

Note:I found out problem was in repositoryURL attribute if i remove special characters : \ from string i can cast to the Repository object.So i would like to know how can i put URLhttp://11.11.111.11/ in to json object even my above object is valid Json.

Body:
You can try converting the string to json string  before converting it to object via gson.
This happens in case of a map where you get an object if you do  map.get(key).

The object wont have quotes "" around key or value.

While converting to json  before , will ensure that.

RepositoryJsonStringvalue = mymap.get("Repository");
String jsonString = new Gson().toJson(RepositoryJsonStringvalue).toString();
Repository r=new Gson().fromJson(jsonString, Repository.class);

Hope it helps


问:
Java: Sort Arraylist of objects on property
I have a Array list of object for class "Emp"[String eno, skill;   ArrayList<Jobs> Empjobs;].

EmpJobs in itself is an arraylist for class "Jobs"[String jobId, skill;int priority, TTC;].

Now in code I created few object of Emps, say Emp1, Emp2 and they have 2 jobs assigned to each as objects of Jobs class.

job11,job12 assigned to Emp1

job21, job22 assigned to Emp2

I need to sort Arraylist of Emp based on total of their jobs TTC(Time to Completeion). I tried using comparor method but no succeess. Any help will be much appreciated.below are snippets of code.

Also to add,

Emp array values are like : 'EmpId#Skill'

Job Array values are like :  'skill#priority#TTC#JobId'

I am not able to work out Collections.sort(emp2,new MyComparator());

```<code>class EmpJobsAssign{
    class Emp
    {
    String eno, skill;
    ArrayList<Jobs> Empjobs;
    public Emp(){
        }
    @Override
    public String toString() {
        return ("eno:"+this.eno+
                " skill: "+ this.skill+
                " Job: "+  this.Empjobs);
        }
    }

public class MyComparator implements Comparator<Emp> {
@Override
public int compare(Emp e1, Emp e2) {
    if (e1.Empjobs.TTC > e2.Empjobs.TTC)
     {
         return 1;
     }
    else if (e1.Empjobs.TTC > e2.Empjobs.TTC)
    {
        return -1;
    }
    return 0;
}
}

class Jobs
    {
    String jobId, skill;
    int priority, TTC;
    public Jobs(){
     }
     @Override
    public String toString() {
        return ("jobId:"+this.jobId+
                " skill: "+ this.skill +
                " priority: "+ this.priority +
                " TTC: "+ this.TTC);
        }
     }

public static void main(String []args){

        String[] arrayEmp = {"w4#j","w1#c","w2#c","W3#j"};
        String[] arrayJob = {"c#3#25#obj1","j#2#20#obj2","j#1#45#obj3","c#4#45#obj4","c#1#15#obj5"};
        EmpJobsAssign HW =new EmpJobsAssign();
        EmpJobsAssign.Emp emp=HW.new Emp();
        EmpJobsAssign.Jobs job=HW.new Jobs();
        Emp[] emps= HW.SortEmp(arrayEmp,0);
        Jobs[] empjobs=HW.SortJob(arrayJob,1,2);
        int jobindex=0;
        while(jobindex < empjobs.length)
        {
         job=empjobs[jobindex];
            ArrayList<Emp> emp2=new ArrayList<Emp>();
             String AssignedFlag="";
            for(int empindex=0;empindex<emps.length;empindex++)
            {
                AssignedFlag="F";
                emp=emps[empindex];
               if(emp.Empjobs == null) {emp.Empjobs=new ArrayList<Jobs>();}
                if(emp.skill.equals(job.skill) && emp.Empjobs.isEmpty()){
                    emp.Empjobs.add(job);
                    System.out.println("empjobs : " +emp);
                    AssignedFlag="T";
                    System.out.println("Emp2  "+ emp2.size());
                    break;
                }
            }
            System.out.println(" AssignedFlag "+AssignedFlag);
            if(AssignedFlag.equals("F")) {
                Collections.sort(emp2,new MyComparator());
                 System.out.println("Inside If  "+ emp2.get(0));
                Iterator itr=emp2.iterator();
                while(itr.hasNext()){
                    System.out.println("test "+ itr.next());
                }
            }
            jobindex++;
        }
        System.out.println("check");
        System.out.println(Arrays.toString(emps));
        System.out.println(Arrays.toString(empjobs));
 }

private Emp[] SortEmp(String[] a, int index1)
    {
        Emp[] SortEmp=new Emp[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;j<a.length;j++){
                if(Integer.parseInt(a[i].substring(1,2))>Integer.parseInt(a[j].substring(1,2))){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                }
                Emp tempEmp = new Emp();
                tempEmp.eno=a[i].split("#")[0];
                tempEmp.skill=a[i].split("#")[1];
            SortEmp[i]=tempEmp;
        }
        return SortEmp;
    }

    private Jobs[] SortJob(String[] a, int index1, int index2)
    {
        Jobs[] SortJobs=new Jobs[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;j<a.length;j++){
                if(Integer.parseInt(a[i].split("#")[index1])>Integer.parseInt(a[j].split("#")[index1])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                 if(Integer.parseInt(a[i].split("#")[index1])==Integer.parseInt(a[j].split("#")[index1])){
                    if(Integer.parseInt(a[i].split("#")[index2]) > Integer.parseInt(a[j].split("#")[index2])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                    }
                }
                }
                Jobs tempJobs=new Jobs();
                tempJobs.jobId=a[i].split("#")[3];
                tempJobs.skill=a[i].split("#")[0];
                tempJobs.priority=Integer.parseInt(a[i].split("#")[1]);
                tempJobs.TTC=Integer.parseInt(a[i].split("#")[2]);
            SortJobs[i]=tempJobs;
        }
        return SortJobs;
    }
  }
</code>```

答:
Don't put down your own comparison if you don't have to.

Your compare() boils down to:

```<code>return Integer.compare(e1.Empjobs.TTC, e2.Empjobs.TTC);
</code>```

Completely eliminating the chance of introducing such subtle typos as your original code is showing (where you simply did a < b, a  b).

Body:
I have a Array list of object for class "Emp"[String eno, skill;   ArrayList<Jobs> Empjobs;].

EmpJobs in itself is an arraylist for class "Jobs"[String jobId, skill;int priority, TTC;].

Now in code I created few object of Emps, say Emp1, Emp2 and they have 2 jobs assigned to each as objects of Jobs class.

job11,job12 assigned to Emp1

job21, job22 assigned to Emp2

I need to sort Arraylist of Emp based on total of their jobs TTC(Time to Completeion). I tried using comparor method but no succeess. Any help will be much appreciated.below are snippets of code.

Also to add,

Emp array values are like : 'EmpId#Skill'

Job Array values are like :  'skill#priority#TTC#JobId'

I am not able to work out Collections.sort(emp2,new MyComparator());

class EmpJobsAssign{
    class Emp
    {
    String eno, skill;
    ArrayList<Jobs> Empjobs;
    public Emp(){
        }
    @Override
    public String toString() {
        return ("eno:"+this.eno+
                " skill: "+ this.skill+
                " Job: "+  this.Empjobs);
        }
    }

public class MyComparator implements Comparator<Emp> {
@Override
public int compare(Emp e1, Emp e2) {
    if (e1.Empjobs.TTC > e2.Empjobs.TTC)
     {
         return 1;
     }
    else if (e1.Empjobs.TTC > e2.Empjobs.TTC)
    {
        return -1;
    }
    return 0;
}
}

class Jobs
    {
    String jobId, skill;
    int priority, TTC;
    public Jobs(){
     }
     @Override
    public String toString() {
        return ("jobId:"+this.jobId+
                " skill: "+ this.skill +
                " priority: "+ this.priority +
                " TTC: "+ this.TTC);
        }
     }

public static void main(String []args){

        String[] arrayEmp = {"w4#j","w1#c","w2#c","W3#j"};
        String[] arrayJob = {"c#3#25#obj1","j#2#20#obj2","j#1#45#obj3","c#4#45#obj4","c#1#15#obj5"};
        EmpJobsAssign HW =new EmpJobsAssign();
        EmpJobsAssign.Emp emp=HW.new Emp();
        EmpJobsAssign.Jobs job=HW.new Jobs();
        Emp[] emps= HW.SortEmp(arrayEmp,0);
        Jobs[] empjobs=HW.SortJob(arrayJob,1,2);
        int jobindex=0;
        while(jobindex < empjobs.length)
        {
         job=empjobs[jobindex];
            ArrayList<Emp> emp2=new ArrayList<Emp>();
             String AssignedFlag="";
            for(int empindex=0;empindex<emps.length;empindex++)
            {
                AssignedFlag="F";
                emp=emps[empindex];
               if(emp.Empjobs == null) {emp.Empjobs=new ArrayList<Jobs>();}
                if(emp.skill.equals(job.skill) && emp.Empjobs.isEmpty()){
                    emp.Empjobs.add(job);
                    System.out.println("empjobs : " +emp);
                    AssignedFlag="T";
                    System.out.println("Emp2  "+ emp2.size());
                    break;
                }
            }
            System.out.println(" AssignedFlag "+AssignedFlag);
            if(AssignedFlag.equals("F")) {
                Collections.sort(emp2,new MyComparator());
                 System.out.println("Inside If  "+ emp2.get(0));
                Iterator itr=emp2.iterator();
                while(itr.hasNext()){
                    System.out.println("test "+ itr.next());
                }
            }
            jobindex++;
        }
        System.out.println("check");
        System.out.println(Arrays.toString(emps));
        System.out.println(Arrays.toString(empjobs));
 }

private Emp[] SortEmp(String[] a, int index1)
    {
        Emp[] SortEmp=new Emp[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;jInteger.parseInt(a[j].substring(1,2))){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                }
                Emp tempEmp = new Emp();
                tempEmp.eno=a[i].split("#")[0];
                tempEmp.skill=a[i].split("#")[1];
            SortEmp[i]=tempEmp;
        }
        return SortEmp;
    }

    private Jobs[] SortJob(String[] a, int index1, int index2)
    {
        Jobs[] SortJobs=new Jobs[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;jInteger.parseInt(a[j].split("#")[index1])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                 if(Integer.parseInt(a[i].split("#")[index1])==Integer.parseInt(a[j].split("#")[index1])){
                    if(Integer.parseInt(a[i].split("#")[index2]) > Integer.parseInt(a[j].split("#")[index2])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                    }
                }
                }
                Jobs tempJobs=new Jobs();
                tempJobs.jobId=a[i].split("#")[3];
                tempJobs.skill=a[i].split("#")[0];
                tempJobs.priority=Integer.parseInt(a[i].split("#")[1]);
                tempJobs.TTC=Integer.parseInt(a[i].split("#")[2]);
            SortJobs[i]=tempJobs;
        }
        return SortJobs;
    }
  }

Body:
Don't put down your own comparison if you don't have to.

Your compare() boils down to:

return Integer.compare(e1.Empjobs.TTC, e2.Empjobs.TTC);

Completely eliminating the chance of introducing such subtle typos as your original code is showing (where you simply did a < b, a  b).


问:
Display number in rectangle
Note that I am using Python3 and Phoenix.

I would like to display a number (double, but that does not matter now) formatted in some way (again, no matter what that way is) within a rectangle: almost a wx.StaticText but not editable by the user. This is to display some data coming from some hardware, such as a temperature.

Is there such a widget?

I tried with using the default wx.StaticText with a style but I must have done something wrong:

```<code>    hbox = wx.BoxSizer(wx.HORIZONTAL)

    title = wx.StaticText(parent, label=label)
    title.SetLabelMarkup("<b>{}</b>".format(label))
    hbox.Add(title, border=5)

    value = wx.StaticText(parent, label="3.141592", style=wx.BORDER_RAISED)
    value.SetWindowStyle(wx.BORDER_SIMPLE)
    hbox.Add(value, border=5)

    title = wx.StaticText(parent, label="\u2103")
    hbox.Add(title, border=5)
</code>```

Shows this on Linux (Fedora 24, GTK):

答: The simplest solution is to just use wxStaticText with a border style (e.g. wxBORDER_SIMPLE, ...). If you don't like the appearance this results in, it's pretty simple to make your own widget drawing whatever border you desire: just create a window, define its wxEVT_PAINT handler and draw the (presumably centered) text in it and a border outside of it.

Title: Display number in rectangle

Body:
Note that I am using Python3 and Phoenix.

I would like to display a number (double, but that does not matter now) formatted in some way (again, no matter what that way is) within a rectangle: almost a wx.StaticText but not editable by the user. This is to display some data coming from some hardware, such as a temperature.

Is there such a widget?

I tried with using the default wx.StaticText with a style but I must have done something wrong:

    hbox = wx.BoxSizer(wx.HORIZONTAL)

    title = wx.StaticText(parent, label=label)
    title.SetLabelMarkup("{}".format(label))
    hbox.Add(title, border=5)

    value = wx.StaticText(parent, label="3.141592", style=wx.BORDER_RAISED)
    value.SetWindowStyle(wx.BORDER_SIMPLE)
    hbox.Add(value, border=5)

    title = wx.StaticText(parent, label="\u2103")
    hbox.Add(title, border=5)

Shows this on Linux (Fedora 24, GTK):


问:
use Adam optimizer TWICE in tensorflow
I am trying to use adam optimizer twice to minimize different tensor in my code, I have tried use GradientDescentOptimizer twice, it's fine, but I get wrong message when using adam optimizer twice, I asked another question at:tensorflowVariable RNNLM/RNNLM/embedding/Adam_2/ does not exist, but that solution doesn't work in here.  I also look up page:https://github.com/tensorflow/tensorflow/issues/6220, But I still don't understand.

 Here is my code, I get Error message:ValueError: Variable NN/NN/W/Adam_2/ does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?

Then I tried the solution at tensorflowVariable RNNLM/RNNLM/embedding/Adam_2/ does not exist, but doesn't work

import tensorflow as tf

def main():
    optimizer = tf.train.GradientDescentOptimizer(0.005)
    # optimizer = tf.train.AdamOptimizer(0.005)

    with tf.variable_scope('NN') as scope:
        W = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y_ = tf.get_variable(name='y_', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y1 = W + X
        loss_1 = tf.reduce_mean(tf.abs(y_ - y1))

        # train_op1 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_1)
        train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)
        # with tf.variable_scope('opt'):
        #     train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)

        ##############################################################################################
        scope.reuse_variables()

        W2 = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X2 = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        b = tf.Variable(tf.random_normal(shape=[5, 1], dtype=tf.float32))
        y2 = W2 + X2 + b
        loss_2 = tf.reduce_mean(tf.abs(y_ - y2))

        # train_op2 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_2)
        train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)
        # with tf.variable_scope('opt'):
        #     train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)

if __name__ == '__main__':
    main()
```

答:
If you absolutely have to do it in the same scope,
make sure all variables are defined in time.
I'd have to do some more research on why it works like this, but the optimizer settings are locked in the graph at a lower level, no longer dynamically accessible.

Minimal working example:

```<code>import tensorflow as tf

def main():
    optimizer = tf.train.GradientDescentOptimizer(0.005)
    # optimizer = tf.train.AdamOptimizer(0.005)

    with tf.variable_scope('NN') as scope:
        assert scope.reuse == False
        W2 = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X2 = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y2_ = tf.get_variable(name='y_', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        b = tf.get_variable(name='b', initializer=tf.random_normal(shape=[5, 1], dtype=tf.float32))
        y2 = W2 + X2 + b
        loss_2 = tf.reduce_mean(tf.abs(y2_ - y2))

        # train_op2 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_2)
        train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)

        # with tf.variable_scope('opt'):
        #     train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)

    ##############################################################################################
    with tf.variable_scope('NN', reuse = True) as scope:

        W = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y_ = tf.get_variable(name='y_', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        b = tf.get_variable(name='b', initializer=tf.random_normal(shape=[5, 1], dtype=tf.float32))

        y1 = W + X
        loss_1 = tf.reduce_mean(tf.abs(y_ - y1))

        # train_op1 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_1)
        train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)
        # with tf.variable_scope('opt'):
        #     train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)

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

Title: use Adam optimizer TWICE in tensorflow

Body:
If you absolutely have to do it in the same scope,
make sure all variables are defined in time.
I'd have to do some more research on why it works like this, but the optimizer settings are locked in the graph at a lower level, no longer dynamically accessible.

Minimal working example:

import tensorflow as tf

def main():
    optimizer = tf.train.GradientDescentOptimizer(0.005)
    # optimizer = tf.train.AdamOptimizer(0.005)

    with tf.variable_scope('NN') as scope:
        assert scope.reuse == False
        W2 = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X2 = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y2_ = tf.get_variable(name='y_', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        b = tf.get_variable(name='b', initializer=tf.random_normal(shape=[5, 1], dtype=tf.float32))
        y2 = W2 + X2 + b
        loss_2 = tf.reduce_mean(tf.abs(y2_ - y2))

        # train_op2 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_2)
        train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)

        # with tf.variable_scope('opt'):
        #     train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)

    ##############################################################################################
    with tf.variable_scope('NN', reuse = True) as scope:

        W = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y_ = tf.get_variable(name='y_', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        b = tf.get_variable(name='b', initializer=tf.random_normal(shape=[5, 1], dtype=tf.float32))

        y1 = W + X
        loss_1 = tf.reduce_mean(tf.abs(y_ - y1))

        # train_op1 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_1)
        train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)
        # with tf.variable_scope('opt'):
        #     train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)

if __name__ == '__main__':
    main()


问:
Low memory writing/reading with Apache POI
I'm trying to write a pretty large XLSX file (4M+ cells) and I'm having some memory issues.

I can't use SXSSF since I also need to read the existing cells in the template.

Is there anything I can do to reduce the memory footprint?

Perhaps combine streaming reading and streaming writing?

答:
I used SAX parser to process events of the XML document presentation. This is</p>

```<code>import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class LowMemoryExcelFileReader {

    private String file;

    public LowMemoryExcelFileReader(String file) {
        this.file = file;
    }

    public List<String[]> read() {
        try {
            return processFirstSheet(file);
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }

    private List<String []> readSheet(Sheet sheet) {
        List<String []> res = new LinkedList<>();
        Iterator<Row> rowIterator = sheet.rowIterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            int cellsNumber = row.getLastCellNum();
            String [] cellsValues = new String[cellsNumber];

            Iterator<Cell> cellIterator = row.cellIterator();
            int cellIndex = 0;

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                cellsValues[cellIndex++] = cell.getStringCellValue();
            }

            res.add(cellsValues);
        }
        return res;
    }

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        this.file = file;
    }

    private List<String []> processFirstSheet(String filename) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();

        SheetHandler handler = new SheetHandler(sst);
        XMLReader parser = fetchSheetParser(handler);
        Iterator<InputStream> sheetIterator = r.getSheetsData();

        if (!sheetIterator.hasNext()) {
            return Collections.emptyList();
        }

        InputStream sheetInputStream = sheetIterator.next();
        BufferedInputStream bisSheet = new BufferedInputStream(sheetInputStream);
        InputSource sheetSource = new InputSource(bisSheet);
        parser.parse(sheetSource);
        List<String []> res = handler.getRowCache();
        bisSheet.close();
        return res;
    }

    public XMLReader fetchSheetParser(ContentHandler handler) throws SAXException {
        XMLReader parser = new SAXParser();
        parser.setContentHandler(handler);
        return parser;
    }

    /**
     * See org.xml.sax.helpers.DefaultHandler javadocs
     */
    private static class SheetHandler extends DefaultHandler {

        private static final String ROW_EVENT = "row";
        private static final String CELL_EVENT = "c";

        private SharedStringsTable sst;
        private String lastContents;
        private boolean nextIsString;

        private List<String> cellCache = new LinkedList<>();
        private List<String[]> rowCache = new LinkedList<>();

        private SheetHandler(SharedStringsTable sst) {
            this.sst = sst;
        }

        public void startElement(String uri, String localName, String name,
                                 Attributes attributes) throws SAXException {
            // c => cell
            if (CELL_EVENT.equals(name)) {
                String cellType = attributes.getValue("t");
                if(cellType != null && cellType.equals("s")) {
                    nextIsString = true;
                } else {
                    nextIsString = false;
                }
            } else if (ROW_EVENT.equals(name)) {
                if (!cellCache.isEmpty()) {
                    rowCache.add(cellCache.toArray(new String[cellCache.size()]));
                }
                cellCache.clear();
            }

            // Clear contents cache
            lastContents = "";
        }

        public void endElement(String uri, String localName, String name)
                throws SAXException {
            // Process the last contents as required.
            // Do now, as characters() may be called more than once
            if(nextIsString) {
                int idx = Integer.parseInt(lastContents);
                lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                nextIsString = false;
            }

            // v => contents of a cell
            // Output after we've seen the string contents
            if(name.equals("v")) {
                cellCache.add(lastContents);
            }
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {
            lastContents += new String(ch, start, length);
        }

        public List<String[]> getRowCache() {
            return rowCache;
        }
    }
}
</code>```

Body:
I used SAX parser to process events of the XML document presentation. This is

import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class LowMemoryExcelFileReader {

    private String file;

    public LowMemoryExcelFileReader(String file) {
        this.file = file;
    }

    public List<String[]> read() {
        try {
            return processFirstSheet(file);
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }

    private List<String []> readSheet(Sheet sheet) {
        List<String []> res = new LinkedList<>();
        Iterator<Row> rowIterator = sheet.rowIterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            int cellsNumber = row.getLastCellNum();
            String [] cellsValues = new String[cellsNumber];

            Iterator<Cell> cellIterator = row.cellIterator();
            int cellIndex = 0;

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                cellsValues[cellIndex++] = cell.getStringCellValue();
            }

            res.add(cellsValues);
        }
        return res;
    }

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        this.file = file;
    }

    private List<String []> processFirstSheet(String filename) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();

        SheetHandler handler = new SheetHandler(sst);
        XMLReader parser = fetchSheetParser(handler);
        Iterator<InputStream> sheetIterator = r.getSheetsData();

        if (!sheetIterator.hasNext()) {
            return Collections.emptyList();
        }

        InputStream sheetInputStream = sheetIterator.next();
        BufferedInputStream bisSheet = new BufferedInputStream(sheetInputStream);
        InputSource sheetSource = new InputSource(bisSheet);
        parser.parse(sheetSource);
        List<String []> res = handler.getRowCache();
        bisSheet.close();
        return res;
    }

    public XMLReader fetchSheetParser(ContentHandler handler) throws SAXException {
        XMLReader parser = new SAXParser();
        parser.setContentHandler(handler);
        return parser;
    }

    /**
     * See org.xml.sax.helpers.DefaultHandler javadocs
     */
    private static class SheetHandler extends DefaultHandler {

        private static final String ROW_EVENT = "row";
        private static final String CELL_EVENT = "c";

        private SharedStringsTable sst;
        private String lastContents;
        private boolean nextIsString;

        private List<String> cellCache = new LinkedList<>();
        private List<String[]> rowCache = new LinkedList<>();

        private SheetHandler(SharedStringsTable sst) {
            this.sst = sst;
        }

        public void startElement(String uri, String localName, String name,
                                 Attributes attributes) throws SAXException {
            // c => cell
            if (CELL_EVENT.equals(name)) {
                String cellType = attributes.getValue("t");
                if(cellType != null && cellType.equals("s")) {
                    nextIsString = true;
                } else {
                    nextIsString = false;
                }
            } else if (ROW_EVENT.equals(name)) {
                if (!cellCache.isEmpty()) {
                    rowCache.add(cellCache.toArray(new String[cellCache.size()]));
                }
                cellCache.clear();
            }

            // Clear contents cache
            lastContents = "";
        }

        public void endElement(String uri, String localName, String name)
                throws SAXException {
            // Process the last contents as required.
            // Do now, as characters() may be called more than once
            if(nextIsString) {
                int idx = Integer.parseInt(lastContents);
                lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                nextIsString = false;
            }

            // v => contents of a cell
            // Output after we've seen the string contents
            if(name.equals("v")) {
                cellCache.add(lastContents);
            }
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {
            lastContents += new String(ch, start, length);
        }

        public List<String[]> getRowCache() {
            return rowCache;
        }
    }
}


问:
How can I store and retrieve an image using an SQLite database and a WPF application?
I have to store an image from my WPF application to the SQLite database, and then retrieve the same image and display it in the application. I tried doing this by coverting the image into byte array and storing that byte array to the SQLite database as BLOB, but this is not working. Can someone help me?</p>

答:
I would suggest to convert the image to a base64 string first and then store it in the database.

In C#:

Image to Base64 String

```<code>public string ImageToBase64(Image image,
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}
</code>```

Base64 String to Image

```<code>public Image Base64ToImage(string base64String)
{
  // Convert Base64 String to byte[]
  byte[] imageBytes = Convert.FromBase64String(base64String);
  MemoryStream ms = new MemoryStream(imageBytes, 0,
    imageBytes.Length);

  // Convert byte[] to Image
  ms.Write(imageBytes, 0, imageBytes.Length);
  Image image = Image.FromStream(ms, true);
  return image;
}
</code>```

You can save the string in the database. This question is related to it: How do i read a base64 image in WPF?

ContentLicense: CC BY-SA 2.5

Body:
I would suggest to convert the image to a base64 string first and then store it in the database.

In C#:

Image to Base64 String

public string ImageToBase64(Image image,
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Base64 String to Image

public Image Base64ToImage(string base64String)
{
  // Convert Base64 String to byte[]
  byte[] imageBytes = Convert.FromBase64String(base64String);
  MemoryStream ms = new MemoryStream(imageBytes, 0,
    imageBytes.Length);

  // Convert byte[] to Image
  ms.Write(imageBytes, 0, imageBytes.Length);
  Image image = Image.FromStream(ms, true);
  return image;
}

You can save the string in the database. This question is related to it: How do i read a base64 image in WPF?


问:
Error cannot find the specified path while executing protractor
Hi I have write a nodejs application that contains some tests written in jasmine.I am trying to get the test results published in TFS using CLI.

I have installed the following packages

"jasmine-spec-reporter": "^4.1.1",
 "jasmine-tfs-reporter": "^1.0.0",
 "phantomjs-prebuilt": "^2.1.14",
 "ts-node": "^3.2.0"

Following is the protractor.conf

```<code>/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
var TfsReporter = require('jasmine-tfs-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/tests/*spec.js'
  ],
  capabilities: {
    'browserName': 'phantomjs',
    'phantomjs.binary.path': require('phantomjs-prebuilt').path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: 'PartyAndIndustryDataMigration'
    });
  },
  onPrepare: function() {
    jasmine.getEnv().addReporter(new SpecReporter());
    jasmine.getEnv().addReporter(new TfsReporter());
  }
};
</code>```

When i try and execute protractor from the command prompt i get error
the specified path does not exist PartyAndIndustryDataMigration

答:
It was a minor fix. It had to just correct the path</p>

```<code>  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: '../PartyAndIndustryDataMigration'
    });
  },
</code>```

Body:
Hi I have write a nodejs application that contains some tests written in jasmine.I am trying to get the test results published in TFS using CLI.

I have installed the following packages

"jasmine-spec-reporter": "^4.1.1",
 "jasmine-tfs-reporter": "^1.0.0",
 "phantomjs-prebuilt": "^2.1.14",
 "ts-node": "^3.2.0"

Following is the protractor.conf

/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
var TfsReporter = require('jasmine-tfs-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/tests/*spec.js'
  ],
  capabilities: {
    'browserName': 'phantomjs',
    'phantomjs.binary.path': require('phantomjs-prebuilt').path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: 'PartyAndIndustryDataMigration'
    });
  },
  onPrepare: function() {
    jasmine.getEnv().addReporter(new SpecReporter());
    jasmine.getEnv().addReporter(new TfsReporter());
  }
};

When i try and execute protractor from the command prompt i get error
the specified path does not exist PartyAndIndustryDataMigration

Body:
It was a minor fix. It had to just correct the path

  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: '../PartyAndIndustryDataMigration'
    });
  },


问:
Guard let construction, still getting fatal error: Index out of range
I am trying to parse some data with this code:

```<code>func findDate(data: String?) -> String {
    guard let date: String? = (data!.componentsSeparatedByString("T"))[0] else{
        return "20000101"
    }
    return date!
}
</code>```

I tried the guard structure to prevent errors when there is no data found, or it has a different structure, but I still get the error when I run it:

fatal error: Index out of range

Does somebody know how to fix this?

答:
Please check out this code:</p>

```<code>func findDate(data: String?) -> String {
    guard let date: String? = (data?.componentsSeparatedByString("T"))?[0] else{
        return "20000101"
    }
    return date!
}

findDate(nil)
findDate("")
findDate("98588T99")
</code>```

Body:
I am trying to parse some data with this code:

func findDate(data: String?) -> String {
    guard let date: String? = (data!.componentsSeparatedByString("T"))[0] else{
        return "20000101"
    }
    return date!
}

I tried the guard structure to prevent errors when there is no data found, or it has a different structure, but I still get the error when I run it:

fatal error: Index out of range

Does somebody know how to fix this?

Body:
Please check out this code:

func findDate(data: String?) -> String {
    guard let date: String? = (data?.componentsSeparatedByString("T"))?[0] else{
        return "20000101"
    }
    return date!
}

findDate(nil)
findDate("")
findDate("98588T99")


问:
XMLHttpRequest cant load
How to come up this error,

XMLHttpRequest cannot load http://samples.openweathermap.org/data/2.5/forecast?appid=bXXXXa1&q=London,us. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

The application is building up in AngularJS and server is created through gulp-connect.
even not sure, this will fix in AngularJs file or in gulp :(

答:
You need to add this headers on server side</p>

```<code>Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
</code>```

Title: XMLHttpRequest cant load

Body:
You need to add this headers on server side

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *


问:
How to remove elements from queue in javascript?
I was trying to use the queue inside javascript. I was referring this link

I was able to add to queue, but while trying to remove from queue i was not successful completely.

```<code>var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("<span class='charToFade'>" + input.charAt(i) +"</span>");
}
$(".text").text("");
for (var j = 0; j < queue.length; j++) {
  $(".text").append(queue.shift());
}
</code>```

Input:

```<code><div class="text">Phone</div>
</code>```

Output:

```<code>Pho
</code>```

you can check the Jsfiddle

Can any one help me here

答:
The problem that you are running into is that for each iteration of the queue an item is removed.

This changes the expected evaluation of the condition for the for loop because the length of the queue is changing each time, about half way through the var j is equal to the length of the queue.

I suggest using a while loop instead of a for:

```<code>while(queue.length > 0){
 $(".text").append(queue.shift());
}
</code>```

Body:
I was trying to use the queue inside javascript. I was referring this link

I was able to add to queue, but while trying to remove from queue i was not successful completely.

var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("" + input.charAt(i) +"");
}
$(".text").text("");
for (var j = 0; j < queue.length; j++) {
  $(".text").append(queue.shift());
}

Input:

Phone

Output:

Pho

you can check the Jsfiddle

Can any one help me here

Body:
The problem that you are running into is that for each iteration of the queue an item is removed.

This changes the expected evaluation of the condition for the for loop because the length of the queue is changing each time, about half way through the var j is equal to the length of the queue.

I suggest using a while loop instead of a for:

while(queue.length > 0){
 $(".text").append(queue.shift());
}


问:
REST/RPC API asyn calls to micro services
I am working on many micro services for the users request. Any library do asyn call to many other services like billing, recommendation
and do the check and response back.

Ex:

call some api

```<code>get(request):

  // call two services async
  billing = billingService(user_id)  //service end point 1
  recommendation = recommendation_service(user_id)  //service end point 2

  // we will have results from those two services

  //check conditions response to user
  if billing == OK:
       response (recommendation)  // response
</code>```

答:
You can try to use ES7's async/await. It'll be easier to write and your code will look a lot cleaner too.

Once you get it to work, your code will look something like:

```<code>const billing = await billingService(user_id)
const recommendation = await recommendation_service(user_id)
</code>```

I'd recommend learning Promises too (afterall they've been successfully saving people from callback hell) to unmistify async/await (as your billingService and recommendation_service would eventually need to be async functions before they can be awaited)

Hope this helps!

Body:
I am working on many micro services for the users request. Any library do asyn call to many other services like billing, recommendation
and do the check and response back.

Ex:

call some api

get(request):

  // call two services async
  billing = billingService(user_id)  //service end point 1
  recommendation = recommendation_service(user_id)  //service end point 2

  // we will have results from those two services

  //check conditions response to user
  if billing == OK:
       response (recommendation)  // response

Body:
You can try to use ES7's async/await. It'll be easier to write and your code will look a lot cleaner too.

Once you get it to work, your code will look something like:

const billing = await billingService(user_id)
const recommendation = await recommendation_service(user_id)

I'd recommend learning Promises too (afterall they've been successfully saving people from callback hell) to unmistify async/await (as your billingService and recommendation_service would eventually need to be async functions before they can be awaited)

Hope this helps!


问:
Bootstrap table not working good with ng-repeat
```<code><div ng-controller="reportCtrl">
      <table class="table table-hover">
          <thead class="row col-md-3">
              <tr class="row">
                  <th class="col-md-6">Key </th>
                  <th class="col-md-6"> Value</th>
              </tr>
          </thead>
          <tbody ng-repeat="param in params" class="row col-md-3">
              <tr class="row">
                  <td class="col-md-6 info">{{param.key}}</td>
                  <td class="col-md-6 info">{{param.val}}</td>
              </tr>
          </tbody>
      </table>
</div>
</code>```

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..

答:
```<code> Remove the bootstrap classes row, col-md-6 in tbody  ,use the below code..
 for all medias, it will be resized

<div ng-controller="reportCtrl" class="table-responsive>
  <table class="table table-hover table-bordered">
      <thead>
          <tr>
              <th>Key </th>
              <th> Value</th>
          </tr>
      </thead>
      <tbody ng-repeat="param in params">
          <tr>
              <td>{{param.key}}</td>
              <td>{{param.val}}</td>
          </tr>
      </tbody>
  </table>
</div>
</code>```

Body:
                  Key
                   Value

                  {{param.key}}
                  {{param.val}}

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..


问:
Removing all spaces in an ArrayList. Java
I am taking input from a .txt file and storing it into an ArrayList. I need to get rid of all the spaces so I can parse the ArrayList to an <Integer>. I am going to post commented out sections so you can see what i have tried to use to do this. Thank you. If you can give me somewhere to look that would be great.

```<code>import java.io.*;
import java.util.*;

public class LabWriterReadre {

  public static void main(String [] args){
       BufferedReader br = null;
       BufferedWriter bw = null;
      // fileWriter = new FileWriter("output.txt",false);
       ArrayList<String> storage = new ArrayList<String>();
       ArrayList<String> convertToInt = new ArrayList<String>();
       ArrayList<Integer> matrix = new ArrayList<Integer>();
         String strLine = "";
        int row1,col1,row2,col2;

        try {
            br = new BufferedReader( new FileReader("C:/Users/jeremiahlukus/Desktop/New folder/jj.txt"));
            while( (strLine = br.readLine()) != null)
            {
                System.out.println(strLine);
                storage.add(strLine);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }

        /*
        String[] trimmedArray = new String[string.size()];
        for (int i = 0; i < string.size(); i++)
        {
            trimmedArray[i] = string[i].trim();
            string.removeAll(Arrays.asList(null,""));
        }
        */
        //string.removeAll(Collections.singleton(""));
       // string.removeAll(Arrays.asList(null,"")

      for (String str : storage)
      {
         if (//str != " ")
             !str.isEmpty())
         {
          convertToInt.add(str);
          //convertToInt.trim();

         }
     }

System.out.println(convertToInt);
}

 /*

       row1 = Integer.parseInt(convertToInt.get(0));
       col1 = Integer.parseInt(convertToInt.get(1));
       row2 = Integer.parseInt(convertToInt.get(2));
       col2 = Integer.parseInt(convertToInt.get(3));

       int[][] matrix1=new int[row1][col1];
       int[][] matrix2=new int[row2][col2];

     */

      //  System.out.println(row1);

        /*
</code>```

This is the .txt file I am reading, _ means space

```<code>3___________3
3_4

1 ______2 3
4_5 _6
7 _8 _9

1 _2_ 3_ 4
5 _6 _7 _8
9_ 10_ 11_ 12
</code>```

This is the ArrayList printed out

```<code>[3______3,_3 _4,__ 1_______2_ 3 , ___4 _5 _6, 7_ 8 _9, 1_ 2_ 3_ 4, 5 _6_ 7_ 8, 9 _10_ 11_ 12]
</code>```

This is what I want to happen

```<code>[3,3,3,4,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]
</code>```

答:
```<code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

  public static void main(String[] args) throws FileNotFoundException, IOException
  {
      String total="";
      List list=new ArrayList();

         try {
           BufferedReader br = new BufferedReader( new FileReader("filename.txt"));
            while( (total = br.readLine()) != null)
            {
           list.add(total);
            }
            br.close();

        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        }

      String firstname1 = list.toString();
      String regex = "[0-9]+";
      firstname1 = firstname1.replaceAll("_", ",");

      firstname1 = firstname1.replace(",", ",");

      String str = firstname1.toString().replaceAll("\\s+", ",").replace("[", "").replace("]", "");

      String arr[] = str.split(",");
      String sum="";
      for (int i = 0; i < arr.length; i++) {

          if (arr[i].matches(regex)) {

              sum += arr[i] + ",";

          }
      }
      sum = sum.substring(0, sum.length() - 1);
      List finalList = Arrays.asList(sum);

      System.out.println("finallist-->>>"+finalList);
     //output-->> [3,3,3,4,1,2,3,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]
  }
}
</code>```

Body:
I am taking input from a .txt file and storing it into an ArrayList. I need to get rid of all the spaces so I can parse the ArrayList to an <Integer>. I am going to post commented out sections so you can see what i have tried to use to do this. Thank you. If you can give me somewhere to look that would be great.

import java.io.*;
import java.util.*;

public class LabWriterReadre {

  public static void main(String [] args){
       BufferedReader br = null;
       BufferedWriter bw = null;
      // fileWriter = new FileWriter("output.txt",false);
       ArrayList<String> storage = new ArrayList<String>();
       ArrayList<String> convertToInt = new ArrayList<String>();
       ArrayList<Integer> matrix = new ArrayList<Integer>();
         String strLine = "";
        int row1,col1,row2,col2;

        try {
            br = new BufferedReader( new FileReader("C:/Users/jeremiahlukus/Desktop/New folder/jj.txt"));
            while( (strLine = br.readLine()) != null)
            {
                System.out.println(strLine);
                storage.add(strLine);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }

        /*
        String[] trimmedArray = new String[string.size()];
        for (int i = 0; i < string.size(); i++)
        {
            trimmedArray[i] = string[i].trim();
            string.removeAll(Arrays.asList(null,""));
        }
        */
        //string.removeAll(Collections.singleton(""));
       // string.removeAll(Arrays.asList(null,"")

      for (String str : storage)
      {
         if (//str != " ")
             !str.isEmpty())
         {
          convertToInt.add(str);
          //convertToInt.trim();

         }
     }

System.out.println(convertToInt);
}

 /*

       row1 = Integer.parseInt(convertToInt.get(0));
       col1 = Integer.parseInt(convertToInt.get(1));
       row2 = Integer.parseInt(convertToInt.get(2));
       col2 = Integer.parseInt(convertToInt.get(3));

       int[][] matrix1=new int[row1][col1];
       int[][] matrix2=new int[row2][col2];

     */

      //  System.out.println(row1);

        /*

This is the .txt file I am reading, _ means space

3___________3
3_4

1 ______2 3
4_5 _6
7 _8 _9

1 _2_ 3_ 4
5 _6 _7 _8
9_ 10_ 11_ 12

This is the ArrayList printed out

[3______3,_3 _4,__ 1_______2_ 3 , ___4 _5 _6, 7_ 8 _9, 1_ 2_ 3_ 4, 5 _6_ 7_ 8, 9 _10_ 11_ 12]

This is what I want to happen

[3,3,3,4,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]


问:
Java Regex capture nested matches
I am having trouble with regex here.

Say i have this input:

```<code>608094.21.1.2014.TELE.&BIG00Z.1.1.GBP
</code>```

My regex looks like this

```<code>(\d\d\d\d\.\d?\d\.\d?\d)|(\d?\d\.\d?\d\.\d?\d?\d\d)
</code>```

I want to extract the date 21.1.2014 out of the string, but all i get is

```<code>8094.21.1
</code>```

I think my problem here is, that 21.1.2014 starts within the (wrong) match before. Is there a simple way to make the matcher look for the next match not after the end of the match before but one character after the beginning of the match before?

答:
I hope this will help you.</p>

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        String x = "608094.21.1.2014.TELE.&BIG00Z.1.1.GBP";
        String pattern = "[0-9]{2}.[0-9]{1}.[0-9]{4}";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(x);
        if (m.find( )) {
            System.out.println("Found value: " + m.group() );
        }else {
            System.out.println("NO MATCH");
        }
    }
</code>```

Title: Java Regex capture nested matches

Body:
I am having trouble with regex here.

Say i have this input:

608094.21.1.2014.TELE.&BIG00Z.1.1.GBP

My regex looks like this

(\d\d\d\d\.\d?\d\.\d?\d)|(\d?\d\.\d?\d\.\d?\d?\d\d)

I want to extract the date 21.1.2014 out of the string, but all i get is

8094.21.1

I think my problem here is, that 21.1.2014 starts within the (wrong) match before. Is there a simple way to make the matcher look for the next match not after the end of the match before but one character after the beginning of the match before?

Body:
I hope this will help you.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        String x = "608094.21.1.2014.TELE.&BIG00Z.1.1.GBP";
        String pattern = "[0-9]{2}.[0-9]{1}.[0-9]{4}";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(x);
        if (m.find( )) {
            System.out.println("Found value: " + m.group() );
        }else {
            System.out.println("NO MATCH");
        }
    }


答:
The access of the element at index zero always happens. If the result of the call to components(separatedBy:) returns an empty array, your code crashes. Also, you should avoid force unwrapping data.

A solution to these crashes is to use the first property of the array, which is optional, so you can safely unwrap it.

```<code>guard let date = data?.components(separatedBy: "T").first else {
    return "20000101"
}
return date.
</code>```

Also, this could then be simplified using the nil coalescing operator:

```<code>return data?.components(separatedBy: "T").first ?? "20000101"
</code>```

Title: Guard let construction, still getting fatal error: Index out of range

Body:
The access of the element at index zero always happens. If the result of the call to components(separatedBy:) returns an empty array, your code crashes. Also, you should avoid force unwrapping data.

A solution to these crashes is to use the first property of the array, which is optional, so you can safely unwrap it.

guard let date = data?.components(separatedBy: "T").first else {
    return "20000101"
}
return date.

Also, this could then be simplified using the nil coalescing operator:

return data?.components(separatedBy: "T").first ?? "20000101"


问:
pass method with template arguments to a macro
I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws:

```<code>ASSERT_THROW(Matrix<5,1>(), std::runtime_error);
</code>```

(this example doesn't make a lot of sense, of course this shoud not throw, but it is what stayed after simplifying what I had.)

I get this output from MS VC++ 2008:

```<code>warning C4002: too many actual parameters for macro 'ASSERT_THROW'
error C2143: syntax error : missing ',' before ';'
</code>```

Whereas there are no problems with:

```<code>ASSERT_THROW(Matrix<1>(), std::runtime_error);
</code>```

How can I overcome this problem?

Thanks!

答:
```<code>#define COMMA ,
ASSERT_THROW(Matrix<5 COMMA 1>(), std::runtime_error);
</code>```

Edit: @tletnes answer is simpler, however this one will work even if the macro parameter used as a non-expression. For example:

```<code>BOOST_FOREACH(std::pair<int COMMA int>& v, myVec) { } // works
BOOST_FOREACH((std::pair<int, int>)& v, myVec) { } // fails
</code>```

More edit: The macro COMMA is already defined in boost:

```<code>#include <boost/preprocessor/punctuation/comma.hpp>
ASSERT_THROW(Matrix<5 BOOST_PP_COMMA() 1>(), std::runtime_error);
BOOST_FOREACH(std::pair<int BOOST_PP_COMMA() int>& v, myVec) { }
</code>```

Body:
I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws:

ASSERT_THROW(Matrix<5,1>(), std::runtime_error);

(this example doesn't make a lot of sense, of course this shoud not throw, but it is what stayed after simplifying what I had.)

I get this output from MS VC++ 2008:

warning C4002: too many actual parameters for macro 'ASSERT_THROW'
error C2143: syntax error : missing ',' before ';'

Whereas there are no problems with:

ASSERT_THROW(Matrix<1>(), std::runtime_error);

How can I overcome this problem?

Thanks!

Body:
#define COMMA ,
ASSERT_THROW(Matrix<5 COMMA 1>(), std::runtime_error);

Edit: @tletnes answer is simpler, however this one will work even if the macro parameter used as a non-expression. For example:

BOOST_FOREACH(std::pair<int COMMA int>& v, myVec) { } // works
BOOST_FOREACH((std::pair<int, int>)& v, myVec) { } // fails

More edit: The macro COMMA is already defined in boost:

#include <boost/preprocessor/punctuation/comma.hpp>
ASSERT_THROW(Matrix<5 BOOST_PP_COMMA() 1>(), std::runtime_error);
BOOST_FOREACH(std::pair<int BOOST_PP_COMMA() int>& v, myVec) { }


问:
How to convert a NSString to long double?
I am dealing with a long double value that can have huge values.

At one time I have this number represented as NSString and I need to convert it to long double. I see that the only API I have is

```<code>[myString doubleValue];
</code>```

I don't see a longDoubleValue.

Trying to convert this number using doubleValue...

```<code>long double x = (long double)[@"3765765765E933" doubleValue];
</code>```

gives me inf and the number in question is a legit long double value, as these numbers can go up to 1.18973149535723176502E+4932.

How do I do that?

答:
Perhaps create a category on NSString yourself

```<code>NSArray *array = [myString componentsSeparatedByString:@"E"];
long double mantis = (long double)[array[0] doubleValue];
long double exponent = (long double)[array[1] doubleValue];
return mantis * exponent;
</code>```

There will possibly be a loss of data though

edit

It would seem that long double on iOS is the same size as double. Maybe you will need a custom class to hold such large numbers.

Body:
I am dealing with a long double value that can have huge values.

At one time I have this number represented as NSString and I need to convert it to long double. I see that the only API I have is

[myString doubleValue];

I don't see a longDoubleValue.

Trying to convert this number using doubleValue...

long double x = (long double)[@"3765765765E933" doubleValue];

gives me inf and the number in question is a legit long double value, as these numbers can go up to 1.18973149535723176502E+4932.

How do I do that?

Body:
Perhaps create a category on NSString yourself

NSArray *array = [myString componentsSeparatedByString:@"E"];
long double mantis = (long double)[array[0] doubleValue];
long double exponent = (long double)[array[1] doubleValue];
return mantis * exponent;

There will possibly be a loss of data though

edit

It would seem that long double on iOS is the same size as double. Maybe you will need a custom class to hold such large numbers.


问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
To get the mathematical operators you have used nextInt.

a.nextInt()=='+'

This is the cause of the problem.
Also, use switch to make the code more robust and readable.

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)


问:
How to show approved comments in Laravel
I want to show post's comments (approved = true) We have a single post with a random slug/id, But the problem is: How can I show approved comments with that specific post id !?

I think i have to use something like this following example :

```<code>Post::find($id)->Comments()->whereApproved(true)->get()
</code>```

Comments Table :

答:
$comments = Comments::where('comments',1)->get();
here 1 is your approved comments

ContentLicense: CC BY-SA 4.0

Body:
I want to show post's comments (approved = true) We have a single post with a random slug/id, But the problem is: How can I show approved comments with that specific post id !?

I think i have to use something like this following example :

Post::find($id)->Comments()->whereApproved(true)->get()

Comments Table :


问:
Redirection of Form after submitted
I am using Ruby on rails 5.1, How can I redirect the User to the Edit Page after submitting the form successfully after login_in in his page after a Long Time

答:
As suggested I would do this way, let me know if it works </p>

```<code>  def create
    @your_instance_variable = YourInstanceVariable.new(your_params)
      if @your_instance_variable.save
        render :edit
      else
       #do something else...
      end
  end
</code>```

Title: Redirection of Form after submitted

Body:
As suggested I would do this way, let me know if it works

  def create
    @your_instance_variable = YourInstanceVariable.new(your_params)
      if @your_instance_variable.save
        render :edit
      else
       #do something else...
      end
  end


问:
Python threads all executing on a single core
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:

```<code>for object in list:
    t = Thread(target=process, args=(object))
    # if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue
</code>```

But when the program is run, Activity Monitor in OS X shows that 1 of the 4 logical cores is at 100% and the others are at nearly 0. Obviously I can't force the OS to do anything but I've never had to pay attention to performance in multi-threaded code like this before so I was wondering if I'm just missing or misunderstanding something.

Thanks.

答: AFAIK, in CPython the Global Interpreter Lock means that there can't be more than one block of Python code being run at any one time. Although this does not really affect anything in a single processor/single-core machine, on a mulitcore machine it means you have effectively only one thread running at any one time - causing all the other core to be idle.</p>

Body:
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:

for object in list:
    t = Thread(target=process, args=(object))
    # if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue

But when the program is run, Activity Monitor in OS X shows that 1 of the 4 logical cores is at 100% and the others are at nearly 0. Obviously I can't force the OS to do anything but I've never had to pay attention to performance in multi-threaded code like this before so I was wondering if I'm just missing or misunderstanding something.

Thanks.


问:
Kendo Export To PDF Unicode Support
I have been trying to incorporate languages dynamically into the Kendo controls, and have run into a issue with Chinese translations which are stored as a list of Unicodes in Sql Server Database.

Translations stored in the Database

It didn't take long to get the Kendo Grid up and running to display these Unicodes in Chinese, through the use of the column template attribute:

```<code>template: '#= Translation #'
</code>```

Kendo Grid Displaying Translations

The issue I am having is with the Excel/PDF exports. They do not render the Unicode values, in the same way that the Kendo Grid does through the use of the template. Instead they display default font characters:

PDF Export

CSV Export

I have tried the following solutions following research on the issue, to no avail:

Setting the font family of the grid control following this recommendation; (which I don't particularly want to do as a matter of consistency with the rest of the site nor do I understand why this would work as the actual Kendo Grid itself is displaying the Chinese characters perfectly):

```<code>.k-widget {
    font-family: 'Arial Unicode MS';
}
</code>```

Setting the column encoded attribute to true:

```<code>{ field: "AnalyteName", title: "Analyte", attributes: { "class": "customKendoGridCell"}, width: "25%", encoded: true, template: '#= TranslationField #' },
</code>```

Using kendo.template:

If you want to render an encoded HTML value in a template, Kendo UI templates can automatically handle the encoding.

```<code>template: '#=setFieldName(TranslationField)#'

function setFieldName(TranslationField) {
    return kendo.template("<div id='box'>#: TranslationField #</div>");
}
</code>```

This appears to display the entire function instead of just the field, perhaps kendo.template needs to be used differently in the context of a Kendo Grid column?

I have made a Dojo example to demonstrate the issue with the PDF export.

答:
I have never come across the issue of Unicode, still, I know a solution that may help you.

```<code>.k-grid {
        font-family: "DejaVu Sans", "Arial", sans-serif;
    }
</code>```

Use this line in your grid file, as in kendo, The standard PDF fonts have no support for Unicode characters.

Title: Kendo Export To PDF Unicode Support

Body:
I have been trying to incorporate languages dynamically into the Kendo controls, and have run into a issue with Chinese translations which are stored as a list of Unicodes in Sql Server Database.

Translations stored in the Database

It didn't take long to get the Kendo Grid up and running to display these Unicodes in Chinese, through the use of the column template attribute:

template: '#= Translation #'

Kendo Grid Displaying Translations

The issue I am having is with the Excel/PDF exports. They do not render the Unicode values, in the same way that the Kendo Grid does through the use of the template. Instead they display default font characters:

PDF Export

CSV Export

I have tried the following solutions following research on the issue, to no avail:

Setting the font family of the grid control following this recommendation; (which I don't particularly want to do as a matter of consistency with the rest of the site nor do I understand why this would work as the actual Kendo Grid itself is displaying the Chinese characters perfectly):

.k-widget {
    font-family: 'Arial Unicode MS';
}

Setting the column encoded attribute to true:

{ field: "AnalyteName", title: "Analyte", attributes: { "class": "customKendoGridCell"}, width: "25%", encoded: true, template: '#= TranslationField #' },

Using kendo.template:

If you want to render an encoded HTML value in a template, Kendo UI templates can automatically handle the encoding.

template: '#=setFieldName(TranslationField)#'

function setFieldName(TranslationField) {
    return kendo.template("
#: TranslationField #
");
}

This appears to display the entire function instead of just the field, perhaps kendo.template needs to be used differently in the context of a Kendo Grid column?

I have made a Dojo example to demonstrate the issue with the PDF export.

Body:
I have never come across the issue of Unicode, still, I know a solution that may help you.

.k-grid {
        font-family: "DejaVu Sans", "Arial", sans-serif;
    }

Use this line in your grid file, as in kendo, The standard PDF fonts have no support for Unicode characters.


问:
Efficient standard basis vector with numpy
Given an index and a size, is there a more efficient way to produce the standard basis vector:</p>

```<code>import numpy as np
np.array([1.0 if i == index else 0.0 for i in range(size)])
</code>```

答:
Often, you need not one but all basis vectors. If this is the case, consider np.eye:

```<code>basis = np.eye(3)
for vector in basis:
  ...
</code>```

Not exactly the same, but closely related: This even works to get a set of basis matrices with a bit of tricks:

```<code>>>> d, e = 2, 3    # want 2x3 matrices
>>> basis = np.eye(d*e,d*e).reshape((d*e,d,e))
>>> print(basis)
[[[ 1.  0.  0.]
  [ 0.  0.  0.]]

 [[ 0.  1.  0.]
  [ 0.  0.  0.]]

 [[ 0.  0.  1.]
  [ 0.  0.  0.]]

 [[ 0.  0.  0.]
  [ 1.  0.  0.]]

 [[ 0.  0.  0.]
  [ 0.  1.  0.]]

 [[ 0.  0.  0.]
  [ 0.  0.  1.]]]
</code>```

and so on.

Body:
Given an index and a size, is there a more efficient way to produce the standard basis vector:

import numpy as np
np.array([1.0 if i == index else 0.0 for i in range(size)])

Body:
Often, you need not one but all basis vectors. If this is the case, consider np.eye:

basis = np.eye(3)
for vector in basis:
  ...

Not exactly the same, but closely related: This even works to get a set of basis matrices with a bit of tricks:

>>> d, e = 2, 3    # want 2x3 matrices
>>> basis = np.eye(d*e,d*e).reshape((d*e,d,e))
>>> print(basis)
[[[ 1.  0.  0.]
  [ 0.  0.  0.]]

 [[ 0.  1.  0.]
  [ 0.  0.  0.]]

 [[ 0.  0.  1.]
  [ 0.  0.  0.]]

 [[ 0.  0.  0.]
  [ 1.  0.  0.]]

 [[ 0.  0.  0.]
  [ 0.  1.  0.]]

 [[ 0.  0.  0.]
  [ 0.  0.  1.]]]

and so on.


问:
How to load a large xlsx file with Apache POI?
I have a large .xlsx file (141 MB, containing 293413 lines with 62 columns each)  I need to perform some operations within.

I am having problems with loading this file (OutOfMemoryError), as POI has a large memory footprint on XSSF (xlsx) workbooks.

This SO question is similar, and the solution presented is to increase the VM's allocated/maximum memory.

It seems to work for that kind of file-size (9MB), but for me, it just simply doesn't work even if a allocate all available system memory. (Well, it's no surprise considering the file is over 15 times larger)

I'd like to know if there is any way to load the workbook in a way it won't consume all the memory, and yet, without doing the processing based (going into) the XSSF's underlying XML. (In other words, maintaining a puritan POI solution)

If there isn't tough, you are welcome to say it ("There isn't.") and point me the ways to a "XML" solution.

答:
Check this post. I show how to use SAX parser to process an XLSX file.

https://stackoverflow.com/a/44969009/4587961

In short, I extended org.xml.sax.helpers.DefaultHandler whih processes XML structure for XLSX filez. t is event parser - SAX.

```<code>class SheetHandler extends DefaultHandler {

    private static final String ROW_EVENT = "row";
    private static final String CELL_EVENT = "c";

    private SharedStringsTable sst;
    private String lastContents;
    private boolean nextIsString;

    private List<String> cellCache = new LinkedList<>();
    private List<String[]> rowCache = new LinkedList<>();

    private SheetHandler(SharedStringsTable sst) {
        this.sst = sst;
    }

    public void startElement(String uri, String localName, String name,
                             Attributes attributes) throws SAXException {
        // c => cell
        if (CELL_EVENT.equals(name)) {
            String cellType = attributes.getValue("t");
            if(cellType != null && cellType.equals("s")) {
                nextIsString = true;
            } else {
                nextIsString = false;
            }
        } else if (ROW_EVENT.equals(name)) {
            if (!cellCache.isEmpty()) {
                rowCache.add(cellCache.toArray(new String[cellCache.size()]));
            }
            cellCache.clear();
        }

        // Clear contents cache
        lastContents = "";
    }

    public void endElement(String uri, String localName, String name)
            throws SAXException {
        // Process the last contents as required.
        // Do now, as characters() may be called more than once
        if(nextIsString) {
            int idx = Integer.parseInt(lastContents);
            lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
            nextIsString = false;
        }

        // v => contents of a cell
        // Output after we've seen the string contents
        if(name.equals("v")) {
            cellCache.add(lastContents);
        }
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        lastContents += new String(ch, start, length);
    }

    public List<String[]> getRowCache() {
        return rowCache;
    }
}
</code>```

And then I parse the XML presending XLSX file

```<code>private List<String []> processFirstSheet(String filename) throws Exception {
    OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
    XSSFReader r = new XSSFReader(pkg);
    SharedStringsTable sst = r.getSharedStringsTable();

    SheetHandler handler = new SheetHandler(sst);
    XMLReader parser = fetchSheetParser(handler);
    Iterator<InputStream> sheetIterator = r.getSheetsData();

    if (!sheetIterator.hasNext()) {
        return Collections.emptyList();
    }

    InputStream sheetInputStream = sheetIterator.next();
    BufferedInputStream bisSheet = new BufferedInputStream(sheetInputStream);
    InputSource sheetSource = new InputSource(bisSheet);
    parser.parse(sheetSource);
    List<String []> res = handler.getRowCache();
    bisSheet.close();
    return res;
}

public XMLReader fetchSheetParser(ContentHandler handler) throws SAXException {
    XMLReader parser = new SAXParser();
    parser.setContentHandler(handler);
    return parser;
}
</code>```

Body:
Check this post. I show how to use SAX parser to process an XLSX file.

https://stackoverflow.com/a/44969009/4587961

In short, I extended org.xml.sax.helpers.DefaultHandler whih processes XML structure for XLSX filez. t is event parser - SAX.

class SheetHandler extends DefaultHandler {

    private static final String ROW_EVENT = "row";
    private static final String CELL_EVENT = "c";

    private SharedStringsTable sst;
    private String lastContents;
    private boolean nextIsString;

    private List<String> cellCache = new LinkedList<>();
    private List<String[]> rowCache = new LinkedList<>();

    private SheetHandler(SharedStringsTable sst) {
        this.sst = sst;
    }

    public void startElement(String uri, String localName, String name,
                             Attributes attributes) throws SAXException {
        // c => cell
        if (CELL_EVENT.equals(name)) {
            String cellType = attributes.getValue("t");
            if(cellType != null && cellType.equals("s")) {
                nextIsString = true;
            } else {
                nextIsString = false;
            }
        } else if (ROW_EVENT.equals(name)) {
            if (!cellCache.isEmpty()) {
                rowCache.add(cellCache.toArray(new String[cellCache.size()]));
            }
            cellCache.clear();
        }

        // Clear contents cache
        lastContents = "";
    }

    public void endElement(String uri, String localName, String name)
            throws SAXException {
        // Process the last contents as required.
        // Do now, as characters() may be called more than once
        if(nextIsString) {
            int idx = Integer.parseInt(lastContents);
            lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
            nextIsString = false;
        }

        // v => contents of a cell
        // Output after we've seen the string contents
        if(name.equals("v")) {
            cellCache.add(lastContents);
        }
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        lastContents += new String(ch, start, length);
    }

    public List<String[]> getRowCache() {
        return rowCache;
    }
}

And then I parse the XML presending XLSX file

private List<String []> processFirstSheet(String filename) throws Exception {
    OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
    XSSFReader r = new XSSFReader(pkg);
    SharedStringsTable sst = r.getSharedStringsTable();

    SheetHandler handler = new SheetHandler(sst);
    XMLReader parser = fetchSheetParser(handler);
    Iterator<InputStream> sheetIterator = r.getSheetsData();

    if (!sheetIterator.hasNext()) {
        return Collections.emptyList();
    }

    InputStream sheetInputStream = sheetIterator.next();
    BufferedInputStream bisSheet = new BufferedInputStream(sheetInputStream);
    InputSource sheetSource = new InputSource(bisSheet);
    parser.parse(sheetSource);
    List<String []> res = handler.getRowCache();
    bisSheet.close();
    return res;
}

public XMLReader fetchSheetParser(ContentHandler handler) throws SAXException {
    XMLReader parser = new SAXParser();
    parser.setContentHandler(handler);
    return parser;
}


问:
Scrapy Splash not respecting Rendering "wait" time
I'm using Scrapy and Splash to scrape this page : https://www.athleteshop.nl/shimano-voor-as-108mm-37184

Here's the image I get in Scrapy Shell with view(response):
scrapy shell img

I need the barcode highlighted in red. But it's generated in javascript as it can be seen in the source code in Chrome with F12.
However, although displayed correctly in both Scrapy Shell and Splash localhost, although Splash localhost gives me the right html, the barcode I want to select always equals to None with response.xpath("//table[@class='data-table']//tr[@class='even']/td[@class='data last']/text()").extract_first().

The selector isn't the problem since it works in Chrome's source code.
I've been looking for the answer on the web and SO for two days and no one seems to have the same problem. Is it just that Splash doesn't support it ?
  The settings are the classic ones as follows :

```<code>SPLASH_URL = 'http://192.168.99.100:8050/'
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware':
810,
}
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
</code>```

My code is as follows (the parse part aims at clicking on the link provided by a search engine inside the website. It works fine) :

```<code>    def parse(self, response):
        try :
            link=response.xpath("//li[@class='item last']/a/@href").extract_first()
            yield SplashRequest(link, self.parse_item, endpoint = 'render.html', args={'wait': 20})
        except Exception as e:
            print (str(e))

    def parse_item(self, response):
        product = {}
        product['name']=response.xpath("//div[@class='product-name']/h1/text()").extract_first()
        product['ean']=response.xpath("//table[@class='data-table']//tr[@class='even']/td[@class='data last']/text()").extract_first()
        product['price']=response.xpath("//div[@class='product-shop']//p[@class='special-price']/span[@class='price']/text()").extract_first()
        product['image']=response.xpath("//div[@class='item image-photo']//img[@class='owl-product-image']/@src").extract_first()
        print (product['name'])
        print (product['ean'])
        print (product['image'])
</code>```

The print on the name and the image url work perfectly fine since they're not generated by javascript.
  The code is alright, the settings are fine, the Splash localhost shows me something good, but my selectors don't work in the execution of the script (which doesn't show any errors), neither in Scrapy Shell.

The problem might be that  Scrapy Splash instantly renders without caring about the wait time (20secs !) put in argument. What did I do wrong, please ?

Thanks in advance.

答: It doesn't seem to me, that the content of barcode field is generated dynamically, I can see it in the page source and extract from scrapy shell with response.css('.data-table tbody tr:nth-child(2) td:nth-child(2)::text').extract_first().

Body:
I'm using Scrapy and Splash to scrape this page : https://www.athleteshop.nl/shimano-voor-as-108mm-37184

Here's the image I get in Scrapy Shell with view(response):
scrapy shell img

I need the barcode highlighted in red. But it's generated in javascript as it can be seen in the source code in Chrome with F12.
However, although displayed correctly in both Scrapy Shell and Splash localhost, although Splash localhost gives me the right html, the barcode I want to select always equals to None with response.xpath("//table[@class='data-table']//tr[@class='even']/td[@class='data last']/text()").extract_first().

The selector isn't the problem since it works in Chrome's source code.
I've been looking for the answer on the web and SO for two days and no one seems to have the same problem. Is it just that Splash doesn't support it ?
  The settings are the classic ones as follows :

SPLASH_URL = 'http://192.168.99.100:8050/'
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware':
810,
}
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'

My code is as follows (the parse part aims at clicking on the link provided by a search engine inside the website. It works fine) :

    def parse(self, response):
        try :
            link=response.xpath("//li[@class='item last']/a/@href").extract_first()
            yield SplashRequest(link, self.parse_item, endpoint = 'render.html', args={'wait': 20})
        except Exception as e:
            print (str(e))

    def parse_item(self, response):
        product = {}
        product['name']=response.xpath("//div[@class='product-name']/h1/text()").extract_first()
        product['ean']=response.xpath("//table[@class='data-table']//tr[@class='even']/td[@class='data last']/text()").extract_first()
        product['price']=response.xpath("//div[@class='product-shop']//p[@class='special-price']/span[@class='price']/text()").extract_first()
        product['image']=response.xpath("//div[@class='item image-photo']//img[@class='owl-product-image']/@src").extract_first()
        print (product['name'])
        print (product['ean'])
        print (product['image'])

The print on the name and the image url work perfectly fine since they're not generated by javascript.
  The code is alright, the settings are fine, the Splash localhost shows me something good, but my selectors don't work in the execution of the script (which doesn't show any errors), neither in Scrapy Shell.

The problem might be that  Scrapy Splash instantly renders without caring about the wait time (20secs !) put in argument. What did I do wrong, please ?

Thanks in advance.