问:
Pass an array of strings into a function without having to specify N (compile time constant)
The following code runs:

```<code>fn last_el(arr: [&str; 2]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(names)]);
}
</code>```

However it only does so with [&str; 2] and 2 has to match the number of elements in names. For example, the following code fails to compile:

```<code>fn last_el(arr: [&str]) -> usize {
    arr.len() - 1
}

fn main(){
    let names = ["this","that"];
    println!("{}", names[last_el(names)]);
}
</code>```

How would I write this so that I don't have to specify N?

I understand that arr.len() - 1 is probably less of a headache than trying to write a function that does the same thing, but as far as understanding how functions accept arrays with strings in them, why does the second example fail to compile?

答:
[&str] is an unsized type. You can't manipulate values of unsized types directly, they need to be behind a reference or a pointer. In your case, you should use &[&str] (also called a slice).

```<code>fn last_el(arr: &[&str]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(&names)]);
}
</code>```

I'll also note that there's a last() method defined on slices. It would be used like this:

```<code>fn main() {
    let names = ["this", "that"];
    println!("{}", names.last().unwrap());
}
</code>```

Body:
The following code runs:

fn last_el(arr: [&str; 2]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(names)]);
}

However it only does so with [&str; 2] and 2 has to match the number of elements in names. For example, the following code fails to compile:

fn last_el(arr: [&str]) -> usize {
    arr.len() - 1
}

fn main(){
    let names = ["this","that"];
    println!("{}", names[last_el(names)]);
}

How would I write this so that I don't have to specify N?

I understand that arr.len() - 1 is probably less of a headache than trying to write a function that does the same thing, but as far as understanding how functions accept arrays with strings in them, why does the second example fail to compile?

Body:
[&str] is an unsized type. You can't manipulate values of unsized types directly, they need to be behind a reference or a pointer. In your case, you should use &[&str] (also called a slice).

fn last_el(arr: &[&str]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(&names)]);
}

I'll also note that there's a last() method defined on slices. It would be used like this:

fn main() {
    let names = ["this", "that"];
    println!("{}", names.last().unwrap());
}


来源: stackexchange

问:
Curses keypad(True) does not get special keys
I am trying to write code for both Python 2 and 3.  Here is my complete code that I am using to learn curses:

```<code># -*- coding: utf-8 -*-
from __future__ import print_function

import curses
import sys
import traceback

class Cursor(object):
    def __init__(self):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        self.stdscr.keypad(True)

    def end_window(self):
        curses.nocbreak()
        self.stdscr.keypad(False)
        curses.echo()
        curses.endwin()

    def start_win(self, begin_x=0, begin_y=1, height=24, width=71):
        return curses.newwin(height, width, begin_y, begin_x)

def applic():
    print("yo man")
    x = Cursor()
    window = x.start_win()
    try:
        # This raises ZeroDivisionError when i == 10.
        for i in range(0, 11):
            v = i - 10
            key = window.getch()
            # EDIT - Added this debug line to verify what key gets
            window.addstr('type of {} is {}\n'.format(key, type(key)))
            if key == curses.KEY_UP:
                return
            window.addstr('10 divided by {} is {}\n'.format(v, 10 // v))
            window.refresh()

    except Exception:
        x.end_window()
        errorstring = sys.exc_info()[2]
        traceback.print_tb(errorstring)

applic()
</code>```

My problem is that key will never equal curses.KEY_UP because getch() (or getkey()) is returning single character strings, not the entire escape key code that equals KEY_UP (\x1b]A).  So each time I press the up arrow in the routine, the program cycles through the three parts of the key code \x1b, [, A, and producing three lines of output:

```<code>10 divided by -10 is -1
10 divided by -9 is -2
10 divided by -8 is -2
</code>```

for this test, I want the UP arrow key to allow me to break out before the expected exception that will occur when i equals 10.

According to the python documentation for Curses, stdscr.keypad(True) is supposed to allow returning the entire key code, but does not appear to do so.

Added some debugging printout information to show what is coming back.  Whether I use getch() or getkey(), the result is the same; it returns a string (the documentation indicated that an integer would be returned for getch):

```<code>type of ^[ is <class 'str'>
10 divided by -9 is -2
type of [ is <class 'str'>
10 divided by -8 is -2
type of A is <class 'str'>
10 divided by -7 is -2
</code>```

答:
The problem is that you set the keypad property on the main window, but are reading from a different window using getch.  This change would make your program accept a KEY_UP:

```<code>--- curses-vs-keypad.py 2017/04/02 11:07:41     1.1
+++ curses-vs-keypad.py 2017/04/03 00:57:16
@@ -28,6 +28,7 @@
     print("yo man")
     x = Cursor()
     window = x.start_win()
+    window.keypad(True)
     try:
         # This raises ZeroDivisionError when i == 10.
         for i in range(0, 11):
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write code for both Python 2 and 3.  Here is my complete code that I am using to learn curses:

# -*- coding: utf-8 -*-
from __future__ import print_function

import curses
import sys
import traceback

class Cursor(object):
    def __init__(self):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        self.stdscr.keypad(True)

    def end_window(self):
        curses.nocbreak()
        self.stdscr.keypad(False)
        curses.echo()
        curses.endwin()

    def start_win(self, begin_x=0, begin_y=1, height=24, width=71):
        return curses.newwin(height, width, begin_y, begin_x)

def applic():
    print("yo man")
    x = Cursor()
    window = x.start_win()
    try:
        # This raises ZeroDivisionError when i == 10.
        for i in range(0, 11):
            v = i - 10
            key = window.getch()
            # EDIT - Added this debug line to verify what key gets
            window.addstr('type of {} is {}\n'.format(key, type(key)))
            if key == curses.KEY_UP:
                return
            window.addstr('10 divided by {} is {}\n'.format(v, 10 // v))
            window.refresh()

    except Exception:
        x.end_window()
        errorstring = sys.exc_info()[2]
        traceback.print_tb(errorstring)

applic()

My problem is that key will never equal curses.KEY_UP because getch() (or getkey()) is returning single character strings, not the entire escape key code that equals KEY_UP (\x1b]A).  So each time I press the up arrow in the routine, the program cycles through the three parts of the key code \x1b, [, A, and producing three lines of output:

10 divided by -10 is -1
10 divided by -9 is -2
10 divided by -8 is -2

for this test, I want the UP arrow key to allow me to break out before the expected exception that will occur when i equals 10.

According to the python documentation for Curses, stdscr.keypad(True) is supposed to allow returning the entire key code, but does not appear to do so.

Added some debugging printout information to show what is coming back.  Whether I use getch() or getkey(), the result is the same; it returns a string (the documentation indicated that an integer would be returned for getch):

type of ^[ is <class 'str'>
10 divided by -9 is -2
type of [ is <class 'str'>
10 divided by -8 is -2
type of A is <class 'str'>
10 divided by -7 is -2

Body:
The problem is that you set the keypad property on the main window, but are reading from a different window using getch.  This change would make your program accept a KEY_UP:

--- curses-vs-keypad.py 2017/04/02 11:07:41     1.1
+++ curses-vs-keypad.py 2017/04/03 00:57:16
@@ -28,6 +28,7 @@
     print("yo man")
     x = Cursor()
     window = x.start_win()
+    window.keypad(True)
     try:
         # This raises ZeroDivisionError when i == 10.
         for i in range(0, 11):


问:
What is a rule for converting an array into a string in Small Basic?
What is a rule for converting an array into a string in Small Basic?

```<code>b[0] = "b0"
b[2] = 1

a[0][0] = "a"
a[0][1] = 123
a[1][2] = "True"
a[1][3] = b

TextWindow.WriteLine(a)
'0=0\=a\;1\=123\;;1=2\=True\;3\=0\\\=b0\\\;2\\\=1\\\;\;;

c[0][0][0] = "a"
c[0][1][0] = 123
c[1][2][0] = "True"
c[1][3][0] = "b0"
c[1][3][2] = 1

TextWindow.WriteLine(c)
'0=0\=0\\\=a\\\;\;1\=0\\\=123\\\;\;;1=2\=0\\\=True\\\;\;3\=0\\\=b0\\\;2\\\=1\\\;\;;
</code>```

In the conversion examples above, I do not understand when backslashes come.

Could you please help me to understand the conversion rule?

Thanks in advance.

G.Kim

答:
In most programming languages, arrays are very efficient and are designed to run as quickly as possible. This is not the case with Small Basic. Actually, Small Basic does not, strictly speaking, have an array structure. Arrays are stored as a Map where a key is stored as a pair with its matching value.

You usually use arrays as such: ary[1] = 12

But you could just as easily use it as such: ary["cat"] = 12

The first versions of Small Basic didn't even support the square bracket [] notation. You stored lists in information using a Map object. For backwards compatibility the Map object is still there. Access to it has been wrapped up in some syntactic sugar to take it more traditional. The end result is something very flexible, but very slow.

Now, to answer your actual question...

What you are seeing is when you write out an array is the Map storage of your array. The values are in pairs. The map key, an equal sign, and the associated map value, ending with a semicolon. When you do multiple dimensional arrays the idea is nested. For a two dimensional array you get the first index, an equal sign, the second index, a slash, a second equal sign and then the associated value. For each added index you get another slash and another semicolon. This is easier to see when you use non-numeric indexes.

```<code>a["cat"] = "hat"
a["shark"] = "bait"

TextWindow.WriteLine(a)  'cat=hat;shark=bait;

b["apple"]["orange"] = "fruit"
b["VW"]["BMW"] = "cars"

TextWindow.WriteLine(b)  'apple=orange\=fruit\;;VW=BMW\=cars\;;

c["hot"]["medium"]["cold"] = "temps"
c["cheese"]["meat"]["vegies"] = "food"

TextWindow.WriteLine(c)  'hot=medium\=cold\\\=temps\\\;\;;cheese=meat\=vegies\\\=food\\\;\;;
</code>```

The idea can go in reverse. If you want to make your code as compact as possible you can load an array using a string. Simply follow the pattern detailed above and rather then having six different lines to load six values into six indexes, you can do it all at once on a single line:

```<code>d = "work=money;stone=cold;"

TextWindow.WriteLine(d["work"]) 'money
TextWindow.WriteLine(d["stone"]) 'cold
</code>```

Body:
What is a rule for converting an array into a string in Small Basic?

b[0] = "b0"
b[2] = 1

a[0][0] = "a"
a[0][1] = 123
a[1][2] = "True"
a[1][3] = b

TextWindow.WriteLine(a)
'0=0\=a\;1\=123\;;1=2\=True\;3\=0\\\=b0\\\;2\\\=1\\\;\;;

c[0][0][0] = "a"
c[0][1][0] = 123
c[1][2][0] = "True"
c[1][3][0] = "b0"
c[1][3][2] = 1

TextWindow.WriteLine(c)
'0=0\=0\\\=a\\\;\;1\=0\\\=123\\\;\;;1=2\=0\\\=True\\\;\;3\=0\\\=b0\\\;2\\\=1\\\;\;;

In the conversion examples above, I do not understand when backslashes come.

Could you please help me to understand the conversion rule?

Thanks in advance.

G.Kim

Body:
In most programming languages, arrays are very efficient and are designed to run as quickly as possible. This is not the case with Small Basic. Actually, Small Basic does not, strictly speaking, have an array structure. Arrays are stored as a Map where a key is stored as a pair with its matching value.

You usually use arrays as such: ary[1] = 12

But you could just as easily use it as such: ary["cat"] = 12

The first versions of Small Basic didn't even support the square bracket [] notation. You stored lists in information using a Map object. For backwards compatibility the Map object is still there. Access to it has been wrapped up in some syntactic sugar to take it more traditional. The end result is something very flexible, but very slow.

Now, to answer your actual question...

What you are seeing is when you write out an array is the Map storage of your array. The values are in pairs. The map key, an equal sign, and the associated map value, ending with a semicolon. When you do multiple dimensional arrays the idea is nested. For a two dimensional array you get the first index, an equal sign, the second index, a slash, a second equal sign and then the associated value. For each added index you get another slash and another semicolon. This is easier to see when you use non-numeric indexes.

a["cat"] = "hat"
a["shark"] = "bait"

TextWindow.WriteLine(a)  'cat=hat;shark=bait;

b["apple"]["orange"] = "fruit"
b["VW"]["BMW"] = "cars"

TextWindow.WriteLine(b)  'apple=orange\=fruit\;;VW=BMW\=cars\;;

c["hot"]["medium"]["cold"] = "temps"
c["cheese"]["meat"]["vegies"] = "food"

TextWindow.WriteLine(c)  'hot=medium\=cold\\\=temps\\\;\;;cheese=meat\=vegies\\\=food\\\;\;;

The idea can go in reverse. If you want to make your code as compact as possible you can load an array using a string. Simply follow the pattern detailed above and rather then having six different lines to load six values into six indexes, you can do it all at once on a single line:

d = "work=money;stone=cold;"

TextWindow.WriteLine(d["work"]) 'money
TextWindow.WriteLine(d["stone"]) 'cold


问:
Can't make kubernetes example for wordpress & mysql with persistent data work
I followed this kubernetes example to create a wordpress and mysql with persistent data

I followed everything from the tutorial from creation of the disk to deployment and on the first try deletion as well

1st try

https://s3-ap-southeast-2.amazonaws.com/dorward/2017/04/git-cmd_2017-04-03_08-25-33.png

Problem: persistent volumes does not bind to the persistent volume claim.  It remains at pending status both for the creation of the pod and the volume claim.  Volume status remains at Released state as well.

Had to delete everything as describe in the example and try again.  This time I mounted the created volumes to an instance in the cluster,  formatted the disk using ext4 fs then unmounted the disks.

2nd try

https://s3-ap-southeast-2.amazonaws.com/dorward/2017/04/git-cmd_2017-04-03_08-26-21.png

Problem: After formatting the volumes,  they are now bound to the claims yay!  unfortunately mysql pod doesn't run with status crashLoopback off.  Eventually the wordpress pod crashed as well.

https://s3-ap-southeast-2.amazonaws.com/dorward/2017/04/git-cmd_2017-04-03_08-27-22.png

Did anyone else experience this?  I'm wondering if I did something wrong or if something has changed from the write up of the exam til now that made the example break.  How do I go around fixing it?

Any help is appreciated.

答:
Get logs for pods:

```<code>kubectl logs pod-name
</code>```

If log indicates the pods are not even starting (crashloopback) investigate the events in k8s:

```<code>kubectl get events
</code>```

The event log indicates the node running out of memory (OOM):

```<code>    LASTSEEN   FIRSTSEEN   COUNT     NAME                                              KIND      SUBOBJECT                    TYPE      REASON       SOURCE                                                      MESSAGE
1m         7d          1555      gke-hostgeniuscom-au-default-pool-xxxh   Node                                   Warning   SystemOOM    {kubelet gke-hostgeniuscom-au-default-pool-xxxxxf-qmjh}   System OOM encountered
</code>```

Trying a larger instance size should solve the issue.

Body:
Get logs for pods:

kubectl logs pod-name

If log indicates the pods are not even starting (crashloopback) investigate the events in k8s:

kubectl get events

The event log indicates the node running out of memory (OOM):

    LASTSEEN   FIRSTSEEN   COUNT     NAME                                              KIND      SUBOBJECT                    TYPE      REASON       SOURCE                                                      MESSAGE
1m         7d          1555      gke-hostgeniuscom-au-default-pool-xxxh   Node                                   Warning   SystemOOM    {kubelet gke-hostgeniuscom-au-default-pool-xxxxxf-qmjh}   System OOM encountered

Trying a larger instance size should solve the issue.


问:
Transition from SQL Server to MySQL (no data migration) - what's the difference?
I've written my website using ASP.NET MVC and SQL Server (used a SQL Server instance which ran locally on my machine).

I'm about to upload my site to a hosting provider. However, his DB works under MySQL. I don't care about the data already in the DB itself. It's mostly mock data and a few tables which I don't mind rewriting. But how do I go about the transition from SQL Server to MySQL? How does this influence my queries inside my code? is it the same code syntax? Will I have to recreate the table definitions? In my project I used LINQ to SQL.

Am I forced to look for a host with SQL Server capabilities (i.e. licenses)? (I hope not...)

Thanks!

答:
You may be able to transition smoothly, but I greatly doubt this will be the case.

The differences are many and whether you could depends on what features you used when developing.

If you kept to one of the standards, you may be in luck.

See a comparison sheet on wikipedia.

In regards to the Linq aspect of your question - you should be able to use a Linq provider for MySql instead of MSSql without a problem.

Here is a link to one: http://code2code.net/DB_Linq/

If you do decide to go with the MySql hosting, I suggest you test all aspects of you application to ensure they are working as expected.

ContentLicense: CC BY-SA 2.5


问:
Django python change multipleChoiceField html output
I have multipleChicesField:

```<code>OPTIONS = (
        ("AUT", "Austria"),
        ("DEU", "Germany"),
        ("NLD", "Neitherlands"),
    )

    countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={"name": "select_0","class": "fff"}),
                                          choices=OPTIONS)
</code>```

Right now it produces following html:

```<code>    <ul id="id_countries">
      <li><label for="id_countries_0"><input class="fff" id="id_countries_0" name="countries" type="checkbox" value="AUT"> Austria</label></li>

      <li><label for="id_countries_1"><input class="fff" id="id_countries_1" name="countries" type="checkbox" value="DEU"> Germany</label></li>

      <li><label for="id_countries_2"><input class="fff" id="id_countries_2" name="countries" type="checkbox" value="NLD"> Neitherlands</label></li>
    </ul>
</code>```

How do I change my code to produce html structure something like:

```<code>  <div class="someClass">
    <input class="fff" id="id_countries_0" name="countries" type="checkbox" value="AUT">
    <label for="id_countries_0">Austria</label>
  </div>

  <div class="someClass">
    <input class="fff" id="id_countries_1" name="countries" type="checkbox" value="DE">
    <label for="id_countries_0">Germany</label>
  </div>
</code>```

答:
You can render the form manually, and then use whatever markup you like

https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-fields-manually

See this example for looping through each form field:

https://docs.djangoproject.com/en/1.10/topics/forms/#looping-over-the-form-s-fields

Body:
I have multipleChicesField:

OPTIONS = (
        ("AUT", "Austria"),
        ("DEU", "Germany"),
        ("NLD", "Neitherlands"),
    )

    countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={"name": "select_0","class": "fff"}),
                                          choices=OPTIONS)

Right now it produces following html:

<input class="fff" id="id_countries_0" name="countries" type="checkbox" value="AUT"> Austria

<input class="fff" id="id_countries_1" name="countries" type="checkbox" value="DEU"> Germany

<input class="fff" id="id_countries_2" name="countries" type="checkbox" value="NLD"> Neitherlands

How do I change my code to produce html structure something like:

    <input class="fff" id="id_countries_0" name="countries" type="checkbox" value="AUT">
    Austria

    <input class="fff" id="id_countries_1" name="countries" type="checkbox" value="DE">
    Germany


问:
Error configuring .NET producer client of Apache Kafka to work with big messages
I'm using a .NET client (producer and consumer) of Apache Kafka.

I'm trying to increase the size of the max message that can be sent. I read the configuration manual and some posts regarding my issue:

Kafka: Sending a 15MB message

https://github.com/confluentinc/kafka-rest/issues/208

I saw that I should set the property "max.request.size" for the producer.
So I did the following:

```<code>   var config = new Dictionary<string, object>
        {
            { "bootstrap.servers", brokerList },
            { "max.request.size", 10 * 1024 * 1024 }
        };

        using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
        {
         ...
</code>```

But when I run the Producer, an exception is thrown :

```<code>System.InvalidOperationException: 'No such configuration property: "max.request.size"'
</code>```

The Apache Kafka documentation tells the following about this property of the producer:

The maximum size of a request in bytes. This is also effectively a cap
  on the maximum record size. Note that the server has its own cap on
  record size which may be different from this. This setting will limit
  the number of record batches the producer will send in a single
  request to avoid sending huge requests.

If, for some reason the documentation isn't up-to-date, what is the right property to use ?

Thanks

答:
confluent-kafka-dotnet uses librdkafka under the hood which has a different set of configuration parameters to the java client. These are documented here:

https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md

I believe the parameter you are looking for is message.max.bytes

Body:
I'm using a .NET client (producer and consumer) of Apache Kafka.

I'm trying to increase the size of the max message that can be sent. I read the configuration manual and some posts regarding my issue:

Kafka: Sending a 15MB message

https://github.com/confluentinc/kafka-rest/issues/208

I saw that I should set the property "max.request.size" for the producer.
So I did the following:

   var config = new Dictionary<string, object>
        {
            { "bootstrap.servers", brokerList },
            { "max.request.size", 10 * 1024 * 1024 }
        };

        using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
        {
         ...

But when I run the Producer, an exception is thrown :

System.InvalidOperationException: 'No such configuration property: "max.request.size"'

The Apache Kafka documentation tells the following about this property of the producer:

The maximum size of a request in bytes. This is also effectively a cap
  on the maximum record size. Note that the server has its own cap on
  record size which may be different from this. This setting will limit
  the number of record batches the producer will send in a single
  request to avoid sending huge requests.

If, for some reason the documentation isn't up-to-date, what is the right property to use ?

Thanks


问:
Detect duplicate inserts when adding many-to-many relation
Let's assume there are two models, A and B:

```<code>class A(models.Model):
    name = models.CharField(max_length=100)

class B(models.Model):
    children = models.ManyToManyField(A)
</code>```

I'm using b.children.add() method to add instance of A to b:

```<code>a = A.objects.get(pk=SOMETHING)
b.children.add(a)
</code>```

As far as I know, Django by default doesn't allow duplicate many-to-many relationship. So I cannot add same instance of A more than once.

But the problem is here, I fetch instances of A with another query, then loop around them and add them one by one. How can I detect a duplicate relation? Does add() method return something useful?

答:
A look at the source code reveals that Django first checks to see if there are any entries that already exist in the database, and then only adds the new ones. It doesn't return any information to the caller, though.

It's not clear if you actually need to detect duplicates, or if you just want to make sure that they're not being added to the database? If it's the latter then everything's fine. If it's the former, there's no way around hitting the database. If you're really concerned about performance you could always perform the check and update the through table yourself (i.e. re-implement add()).

Body:
Let's assume there are two models, A and B:

class A(models.Model):
    name = models.CharField(max_length=100)

class B(models.Model):
    children = models.ManyToManyField(A)

I'm using b.children.add() method to add instance of A to b:

a = A.objects.get(pk=SOMETHING)
b.children.add(a)

As far as I know, Django by default doesn't allow duplicate many-to-many relationship. So I cannot add same instance of A more than once.

But the problem is here, I fetch instances of A with another query, then loop around them and add them one by one. How can I detect a duplicate relation? Does add() method return something useful?

ContentLicense: CC BY-SA 4.0


问:
Difference between constructor and getter and setter
I have been doing assignments for college projects. At one point, I am getting confused at what is actually the use of getter and setter when you can actually use constructor methods to achieve the same results. I have searched and found many answers but not satisfactory explanation.
I have laptop.java as follows

```<code>public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }

    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}
</code>```

and the laoptopRecords.java that is calling constructor as

```<code>public class laptopRecords {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        laptop laptop1=new laptop("Dell");
        System.out.println(laptop1);
    }

}
</code>```

Here I am not using the getter and setter methods and I get desired result for every laptop object.

If I do in another way using getter and setter methods in laptopRecord.java as follows, I get the same result. But I am not getting what is use of getter and setter methods if actually we can achive the results with constructor as well.

laptop.java with getter and setter

```<code>public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }
    public void setlaptop(String brand){
        model=brand;
    }
    public String getlaptop(){
        return model;
    }
    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}
</code>```

答:
I tell you an easy way:

getters() and setters():

actually getters() and setters available in POJO/Bean classes.

The main reason used for getters() setters() in java classes is To get the Java Encapsulation Mechanism.

In POJO/Bean classes we declare all attributes as a private. that means these class attributes can't use in other classes and packages, so in this, we can achieve Encapsulation.

Constructors():

I think you know the definition of constructor, The constructor is used for initializing the attributes giving our own values rather than storing the default values

We can say another way i.e Constructor used for creating an object and setters used for changing the values inside object, getters() user for getting the values, this is only the main difference.

Body:
I have been doing assignments for college projects. At one point, I am getting confused at what is actually the use of getter and setter when you can actually use constructor methods to achieve the same results. I have searched and found many answers but not satisfactory explanation.
I have laptop.java as follows

public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }

    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}

and the laoptopRecords.java that is calling constructor as

public class laptopRecords {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        laptop laptop1=new laptop("Dell");
        System.out.println(laptop1);
    }

}

Here I am not using the getter and setter methods and I get desired result for every laptop object.

If I do in another way using getter and setter methods in laptopRecord.java as follows, I get the same result. But I am not getting what is use of getter and setter methods if actually we can achive the results with constructor as well.

laptop.java with getter and setter

public class laptop {
    private String model;

    public laptop(String brand){
     model=brand;
        }
    public void setlaptop(String brand){
        model=brand;
    }
    public String getlaptop(){
        return model;
    }
    public String toString(){
        return "Laptop Brand is: "+ model;
    }
}


问:
Updating to latest Swift version problems
I just updated to the latest version of Swift and I am getting issues with a breakpoint error. There are no errors in the console.

```<code>backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height))
self.view.addSubview(backgroundsetting)
</code>```

Then after the update it wanted me to set the backgroundsetting.frame as! CGRect and it crashes the app when I open that part of the app. Why is this occurring? Here is the after code:

```<code>backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height)) as! CGRect
self.view.addSubview(backgroundsetting)
</code>```

答:
The backgroundsetting.frame property is a type of CGRect, why not creating a CGRect like this:

```<code>backgroundsetting.frame = CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height)
</code>```

Body:
I just updated to the latest version of Swift and I am getting issues with a breakpoint error. There are no errors in the console.

backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height))
self.view.addSubview(backgroundsetting)

Then after the update it wanted me to set the backgroundsetting.frame as! CGRect and it crashes the app when I open that part of the app. Why is this occurring? Here is the after code:

backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height)) as! CGRect
self.view.addSubview(backgroundsetting)

Body:
The backgroundsetting.frame property is a type of CGRect, why not creating a CGRect like this:

backgroundsetting.frame = CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height)


问:
Laravel 5 Auth: These credentials do not match our records
I'm just starting out with Laravel 5, I come from Laravel 4 environment so it shouldn't be too hard.

I heard L5 comes with a built-in authentication system which is neat.
I've set everything up from database to views.

The registration process is working correctly and after that it logs me in automatically. but when I log out and try to log back in, I get this error:

These credentials do not match our records.

I'm not sure what's wrong. do I have to write the login controller manually or how does it work in L5?

答:
Further to what @mervasdayi & Gerard Reches have suggested. Just thought I'd make a note that you will need to include

```<code>use Illuminate\Support\Facades\Hash;
</code>```

at the top of your User model when adding in these fixes.

Body:
Further to what @mervasdayi & Gerard Reches have suggested. Just thought I'd make a note that you will need to include

use Illuminate\Support\Facades\Hash;

at the top of your User model when adding in these fixes.


问:
Migrations in Laravel are not been placed in 'database\migrations' folder
I'm making a migration in laravel like this:

```<code>php artisan make:migration create_tasks_table
</code>```

and then I get a message from the console like this:

```<code>Created Migration: 2017_04_03_002411_create_tasks_table
</code>```

But when I go to the 'database\migrations' directory there's no .php file related to the migration I made.

Why is this happening?

答: It could be that your IDE is not updating the filesystem. What i would suggest is to use the terminal to navigate to the migrations directory and list the content of the directory to see if its truely empty.</p>

Body:
I'm making a migration in laravel like this:

php artisan make:migration create_tasks_table

and then I get a message from the console like this:

Created Migration: 2017_04_03_002411_create_tasks_table

But when I go to the 'database\migrations' directory there's no .php file related to the migration I made.

Why is this happening?


问:
Javascript click event triggers twice
In the following snippet, why does divClicked() trigger twice when the  is clicked, but only once when <input> is clicked?

function divClicked(_index) {
  console.log("div click event");
}

function inputClicked(_index) {
  console.log("input click event");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="option" onclick="divClicked(1)">
  <input id="1_1" name="group_1" type="radio" value="1" onclick="inputClicked(1)" />
  <label for="1_1">label</label>
</div></code>```

Note: I want to know why this happens, not a "quick fix" like: put onclick() on label.

答:
This happens because of what the HTML spec describes at 4.10.4:

For example, on platforms where clicking a checkbox label checks the
  checkbox, clicking the label in the following snippet could trigger
  the user agent to run synthetic click activation steps on the input
  element, as if the element itself had been triggered by the user:

```<code><label><input type=checkbox name=lost> Lost</label>
</code>```

On other platforms, the behavior might be just to focus the control,
  or do nothing.

This means that when a  is clicked, the browser creates a second "synthetic" click event on the associated <input> element, in order to toggle its state.

The reason divClicked is triggered twice, is because the first event which comes from the  bubbles up to the
, and also the second, synthetic click event bubbles up to the
.

Title: Javascript click event triggers twice

Body:
In the following snippet, why does divClicked() trigger twice when the  is clicked, but only once when <input> is clicked?

function divClicked(_index) {
  console.log("div click event");
}

function inputClicked(_index) {
  console.log("input click event");
}

  <input id="1_1" name="group_1" type="radio" value="1" onclick="inputClicked(1)" />
  label

Note: I want to know why this happens, not a "quick fix" like: put onclick() on label.

Body:
This happens because of what the HTML spec describes at 4.10.4:

For example, on platforms where clicking a checkbox label checks the
  checkbox, clicking the label in the following snippet could trigger
  the user agent to run synthetic click activation steps on the input
  element, as if the element itself had been triggered by the user:

<label><input type=checkbox name=lost> Lost</label>

On other platforms, the behavior might be just to focus the control,
  or do nothing.

This means that when a <label> is clicked, the browser creates a second "synthetic" click event on the associated <input> element, in order to toggle its state.

The reason divClicked is triggered twice, is because the first event which comes from the <label> bubbles up to the <div>, and also the second, synthetic click event bubbles up to the <div>.


问:
Using old version of JSON when the JSON is updated and the page is refreshed
I have question about JSON and JavaScript. So through web page I update JSON file and then save it to the server. Then I go to the page where there must be listed the information from the JSON but it visualisates the old information of the JSON even after refreshing the page. Only when I open a new window of web browser then it list the latest JSON. I search for any cache but there is nothing and don't know where is the problem. So how to visualisate the updated JSON after refreshing page?

I am fethching the information by jQuery:

```<code>$.getJSON("json2.json", function(json) {
console.log(json[0]); // this will show the info it in firebug console
var count = Object.keys(json).length;
console.log(count);
for(var i=0; i<count; i++){}});
</code>```

This is no the full code but i can't publish it all because it so long.

答:
This is probably due to browser cache, since this is the same filename.

Add this before your $.getJSON(...:

```<code>$.ajaxSetup({
    cache:false
});
</code>```

;)

Body:
I have question about JSON and JavaScript. So through web page I update JSON file and then save it to the server. Then I go to the page where there must be listed the information from the JSON but it visualisates the old information of the JSON even after refreshing the page. Only when I open a new window of web browser then it list the latest JSON. I search for any cache but there is nothing and don't know where is the problem. So how to visualisate the updated JSON after refreshing page?

I am fethching the information by jQuery:

$.getJSON("json2.json", function(json) {
console.log(json[0]); // this will show the info it in firebug console
var count = Object.keys(json).length;
console.log(count);
for(var i=0; i<count; i++){}});

This is no the full code but i can't publish it all because it so long.

Body:
This is probably due to browser cache, since this is the same filename.

Add this before your $.getJSON(...:

$.ajaxSetup({
    cache:false
});

;)


问:
why my javascript code dosen't work(about search and filter bar)
```<code><!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="utf-8">
   <title>a1</title>
   <link rel="stylesheet" href="a1.css" />
   <script src="a1.js"></script>
</head>
<body>
<form id = "gallary" method="get" action="">
<div id="searchBox">
  <input type="text" id="searchBar" placeholder="Search titles" />
<input type="submit" id="searchBtn" value="search" onclick="searchFunction()"/>

  <select name="genre" id ="filterBar">
    <option>Genre</option>
    <option>Baroque</option>
    <option>Mannerism</option>
    <option>Neo-classicism</option>
    <option>Realisim</option>
    <option>Romanticism</option>
  </select>
  <input type="submit" id = "filterBtn" value="filter" onclick =
"filterFunction()"  />
</div>
</form>
<div id="artistBox">
  <table>
    <caption>Paintings</caption>

    <thead>
      <tr>
        <th></th>
        <th>Title</th>
        <th>Artist</th>
        <th>Year</th>
        <th>Genre</th>
      </tr>
    </thead>

    <tbody id="tbody">
      <tr>
        <td><input type="checkbox" name="paintingname" /><img
src="05030.jpg"/></td>
        <td>Death of Marat</td>
        <td>David, Jacques-Louis</td>
        <td>1793</td>
        <td>Romanticism</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="paintingname" /><img
src="120010.jpg"/></td>
        <td>Potrait of Eleanor of Toledo</td>
        <td>Bronzino, Agnolo</td>
        <td>1545</td>
        <td>Mannerism</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="paintingname" /><img
src="07020.jpg"/></td>
        <td>Liberty leading the people</td>
        <td>Delacroix, Eugene</td>
        <td>1830</td>
        <td>Romanticism</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="paintingname" /><img
src="13030.jpg"/></td>
        <td>Arrangement in Grey and Black</td>
        <td>Whistler, James Abbott</td>
        <td>1871</td>
        <td>Realisim</td>
      </tr>
      <tr>
        <td><input type="checkbox" name="paintingname" /><img
src="06010.jpg"/></td>
        <td>Mademoiselle Caroline Riviere</td>
        <td>Ingres, Jean-Auguste</td>
        <td>1806</td>
        <td>Neo-classicism</td>
      </tr>
    </tbody>

  </table>

</div>
</body>
</html>

enter code here
</code>```

above is my HTML code.
the searchBar is for searcing titles(the second column of tbody), the filter is for filtering genres(the fourth column of tbody).

I want to search and filter some specific content form the table and use on-click to trigger my functions but it didn't work. Can anyone help me?

```<code>var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementByTagName("tr");
var td;

var filter = document.getElementById("filterBar").value;

function makeGreen(inputDiv){
    inputDiv.style.backgroundColor = "green";
}

function searchFunction(){

    for (var i = 0; i < tr.length; i++) {
        td = tr[i].getElementByTagName("td")[1];
        if(td.innerHTML.toUpperCase() == input){
            makeGreen(tr[i]);
        }
    };
}
function filterFunction(){
for (var i = 0; i < tr.length; i++) {
    td = tr[i].getElementByTagName("td")[4];
    if(td.innerHTML == input){
        tr[i].style.display = "";
    }else{
        tr[i].style.display = "none";
    }
 }
</code>```

答:
You are setting the values of 'input', 'tbody','tr', and 'td' at the start of the script.  These get evaluated when the script is loaded but destroyed when the the script file is finished loading.  That is the "searchFunction" does not know about the values of these tags.

Consider the updated code: (see it in action at: Plunker)

```<code><script type="text/javascript">
  function makeGreen(inputDiv){
      inputDiv.style.backgroundColor = "green";
  }

  function searchFunction(){
      var input = document.getElementById("searchBar").value.toUpperCase();
      var input = document.getElementById("searchBar").value.toUpperCase();
      var tbody = document.getElementById("tbody");
      var tr = tbody.getElementsByTagName("tr");
      console.log(input);
      for (var i = 0; i < tr.length; i++) {
          td = tr[i].getElementsByTagName("td")[1];
          var filter = document.getElementById("filterBar").value;

          if(td.innerHTML.toUpperCase() == input){
              makeGreen(tr[i]);
          }
      };
  }
  function filterFunction(){
    var input = document.getElementById("searchBar").value.toUpperCase();
    var tbody = document.getElementById("tbody");
          var tr = tbody.getElementsByTagName("tr");
      for (var i = 0; i < tr.length; i++) {
      td = tr[i].getElementsByTagName("td")[4];
      if(td.innerHTML == input){
          tr[i].style.display = "";
      }else{
          tr[i].style.display = "none";
      }
    } // <-- Missing
 }
</script>
</code>```

Body:
<!DOCTYPE html>

   <meta charset="utf-8">
   <title>a1</title>
   <link rel="stylesheet" href="a1.css" />

<form id = "gallary" method="get" action="">

  <input type="text" id="searchBar" placeholder="Search titles" />
<input type="submit" id="searchBtn" value="search" onclick="searchFunction()"/>

  <select name="genre" id ="filterBar">
    <option>Genre</option>
    <option>Baroque</option>
    <option>Mannerism</option>
    <option>Neo-classicism</option>
    <option>Realisim</option>
    <option>Romanticism</option>
  </select>
  <input type="submit" id = "filterBtn" value="filter" onclick =
"filterFunction()"  />

</form>

Paintings

        Title
        Artist
        Year
        Genre

        <input type="checkbox" name="paintingname" />
        Death of Marat
        David, Jacques-Louis
        1793
        Romanticism

        <input type="checkbox" name="paintingname" />
        Potrait of Eleanor of Toledo
        Bronzino, Agnolo
        1545
        Mannerism

        <input type="checkbox" name="paintingname" />
        Liberty leading the people
        Delacroix, Eugene
        1830
        Romanticism

        <input type="checkbox" name="paintingname" />
        Arrangement in Grey and Black
        Whistler, James Abbott
        1871
        Realisim

        <input type="checkbox" name="paintingname" />
        Mademoiselle Caroline Riviere
        Ingres, Jean-Auguste
        1806
        Neo-classicism

enter code here

above is my HTML code.
the searchBar is for searcing titles(the second column of tbody), the filter is for filtering genres(the fourth column of tbody).

I want to search and filter some specific content form the table and use on-click to trigger my functions but it didn't work. Can anyone help me?

var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementByTagName("tr");
var td;

var filter = document.getElementById("filterBar").value;

function makeGreen(inputDiv){
    inputDiv.style.backgroundColor = "green";
}

function searchFunction(){

    for (var i = 0; i < tr.length; i++) {
        td = tr[i].getElementByTagName("td")[1];
        if(td.innerHTML.toUpperCase() == input){
            makeGreen(tr[i]);
        }
    };
}
function filterFunction(){
for (var i = 0; i < tr.length; i++) {
    td = tr[i].getElementByTagName("td")[4];
    if(td.innerHTML == input){
        tr[i].style.display = "";
    }else{
        tr[i].style.display = "none";
    }
 }

Body:
You are setting the values of 'input', 'tbody','tr', and 'td' at the start of the script.  These get evaluated when the script is loaded but destroyed when the the script file is finished loading.  That is the "searchFunction" does not know about the values of these tags.

Consider the updated code: (see it in action at: Plunker)

<script type="text/javascript">
  function makeGreen(inputDiv){
      inputDiv.style.backgroundColor = "green";
  }

  function searchFunction(){
      var input = document.getElementById("searchBar").value.toUpperCase();
      var input = document.getElementById("searchBar").value.toUpperCase();
      var tbody = document.getElementById("tbody");
      var tr = tbody.getElementsByTagName("tr");
      console.log(input);
      for (var i = 0; i < tr.length; i++) {
          td = tr[i].getElementsByTagName("td")[1];
          var filter = document.getElementById("filterBar").value;

          if(td.innerHTML.toUpperCase() == input){
              makeGreen(tr[i]);
          }
      };
  }
  function filterFunction(){
    var input = document.getElementById("searchBar").value.toUpperCase();
    var tbody = document.getElementById("tbody");
          var tr = tbody.getElementsByTagName("tr");
      for (var i = 0; i < tr.length; i++) {
      td = tr[i].getElementsByTagName("td")[4];
      if(td.innerHTML == input){
          tr[i].style.display = "";
      }else{
          tr[i].style.display = "none";
      }
    } // <-- Missing
 }
</script>


问:
Macro written in Excel 2010 not working in Excel 2013
I have written a simple macro to force end users to view an EULA and then click a command button to accept the terms. On clicking the tabs for the workbook open allowing the user to work through the book. This works fine in Excel 2010 and all previous version but not in Excel 2013.

I get this error:

This is the code:

```<code>Sub OpenSheets()
'
' OpenSheets Macro
'

'
    Sheets("EULA").Select
    Sheets("Infection_Worksheet").Visible = True
    Sheets("Infection_Worksheet").Select
    Sheets("Exit_Site_Infection_Chart").Visible = True
    Sheets("Exit_Site_Infection_Chart").Select
    Sheets("Peritonitis_Chart").Visible = True
    Sheets("Exit_Site_Infection_Chart").Select
    Sheets("%_Pts_peritonitis_free").Visible = True
    Sheets("%_Pts_peritonitis_free").Select
    Sheets("Pt_numbers").Visible = True
    Sheets("Pt_numbers").Select
    Sheets("Results").Visible = True
    Sheets("Results").Select
    Sheets("Instructions").Visible = True
    End Sub
</code>```

Does anyone have any suggestions?

答:
Underscores represent continuation to the next line in VBA.

Try this Sheets("Infection" & Chr(97) & "Worksheet").Visible = True

etc etc etc

Body:
I have written a simple macro to force end users to view an EULA and then click a command button to accept the terms. On clicking the tabs for the workbook open allowing the user to work through the book. This works fine in Excel 2010 and all previous version but not in Excel 2013.

I get this error:

This is the code:

Sub OpenSheets()
'
' OpenSheets Macro
'

'
    Sheets("EULA").Select
    Sheets("Infection_Worksheet").Visible = True
    Sheets("Infection_Worksheet").Select
    Sheets("Exit_Site_Infection_Chart").Visible = True
    Sheets("Exit_Site_Infection_Chart").Select
    Sheets("Peritonitis_Chart").Visible = True
    Sheets("Exit_Site_Infection_Chart").Select
    Sheets("%_Pts_peritonitis_free").Visible = True
    Sheets("%_Pts_peritonitis_free").Select
    Sheets("Pt_numbers").Visible = True
    Sheets("Pt_numbers").Select
    Sheets("Results").Visible = True
    Sheets("Results").Select
    Sheets("Instructions").Visible = True
    End Sub

Does anyone have any suggestions?


问:
Using REST API with jQuery Easyautocomplete plugin
I'm having trouble getting the easyautocomplete plugin to connect to my data source and pull the title of each object within the JSON. A sample of the JSON looks like this:

```<code>data: [{
       id: "1",
       title: "bob",
       permalink: "/user/folder/bob",
       type: "user"
}]
</code>```

I'm making the call to my REST API and trying to get the title value, which I'll also need to get the type of each object as well.

```<code>var q = $("#global-search").val();
var options = {
    url: "https://search.domain-name.com?q=" + q,

    getValue: "title",

    list: {
        match: {
            enabled: true
        }
    }
};

$("#global-search").easyAutocomplete(options);
</code>```

The only error I'm getting is: Uncaught TypeError: Cannot read property 'indexOf' of undefined.

The url structure for the search requires that it be the base url http://search.domain-name.com with a query parameter of ?q= for the search term.

how can I fix this so that my request is actually sent and receives a response as well as searches by the type and title of in each object of the data array returned?

This is my current fiddle: JSFIDDLE

答:
If I were you,
1. I will Check the url to know is that working properly.
=> Using Chrome Debuging tool and see network i/o will be helpful.
=> write console.log to find the problem.

the code looks okay but when I checked the jsfiddle. The "input id="provider-remote" "  and your jquery id were different, you may check it.

Sometime, jsfiddle does not support external url through https => http might be helpful for debuging.

Good Luck

Body:
I'm having trouble getting the easyautocomplete plugin to connect to my data source and pull the title of each object within the JSON. A sample of the JSON looks like this:

data: [{
       id: "1",
       title: "bob",
       permalink: "/user/folder/bob",
       type: "user"
}]

I'm making the call to my REST API and trying to get the title value, which I'll also need to get the type of each object as well.

var q = $("#global-search").val();
var options = {
    url: "https://search.domain-name.com?q=" + q,

    getValue: "title",

    list: {
        match: {
            enabled: true
        }
    }
};

$("#global-search").easyAutocomplete(options);

The only error I'm getting is: Uncaught TypeError: Cannot read property 'indexOf' of undefined.

The url structure for the search requires that it be the base url http://search.domain-name.com with a query parameter of ?q= for the search term.

how can I fix this so that my request is actually sent and receives a response as well as searches by the type and title of in each object of the data array returned?

This is my current fiddle: JSFIDDLE


问:
Jython - using Pygments in Java project
I'm trying to use Pygments in Java project by including Jython.jar. In my Java project I have src/main/python source directory where I placed pygments files into pygments folder so they end up on the classpath. Now I created highlighter.py file in the src/main/python with the following content:

```<code>import sys
sys.path.append('WEB-INF/classes')
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

class Highlighter:
    def colorize(code, lexername):
        lexer = get_lexer_by_name(lexername, stripall=True)
        formatter = HtmlFormatter(linenos=True, cssclass="source")
        return highlight(code, lexer, formatter)
</code>```

Then I defined Java interface Highlighter.java

```<code>public interface Highlighter {
    String colorize(String rawText, String lexer);
}
</code>```

And lastly I created factory class that uses PythonInterpreter to expose highlighter.py as a Jython object as described here

Now, when I run this line of code

```<code>Highlighter hl = (Highlighter) jf.getJythonObject(Highlighter.class.getName(),
       "WEB-INF/classes/highlighter.py");
</code>```

I get PyException as follows

```<code>Traceback (most recent call last):
File "WEB-INF/classes/highlighter.py", line 3, in
  from pygments import highlight
LookupError: no codec search functions registered: can't find encoding
</code>```

This occurs if I use Jython v. 2.5.0. In 2.1 I had to copy Jython/Lib directory under src/main/python but then I end up missing IOString module

Or maybe there's a better way to achieve what I'm trying to achieve? I'm curious if anyone was able to use Pygments in Java project.  I would greatly appreciate any suggestions

答:
All right. I figured it out. Made few beginner errors but if you are wondering how to make Pygments work in your Java project here's full tutorial link

Highlights:

Using bare jython.jar is insufficient.

Adding Jython/Lib to your classpath doesn't work. I ended up unjarring jython.jar and adding Lib directory + all pygments files to the resulting structure and then jarring it up again

Factory example form the link above is convoluted. Much better way is to use Jython book chapter 10

For examples of changed highlighter.py, Highlighter.java and HighlighterFactory.java see the tutorial

Title: Jython - using Pygments in Java project

Body:
I'm trying to use Pygments in Java project by including Jython.jar. In my Java project I have src/main/python source directory where I placed pygments files into pygments folder so they end up on the classpath. Now I created highlighter.py file in the src/main/python with the following content:

import sys
sys.path.append('WEB-INF/classes')
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

class Highlighter:
    def colorize(code, lexername):
        lexer = get_lexer_by_name(lexername, stripall=True)
        formatter = HtmlFormatter(linenos=True, cssclass="source")
        return highlight(code, lexer, formatter)

Then I defined Java interface Highlighter.java

public interface Highlighter {
    String colorize(String rawText, String lexer);
}

And lastly I created factory class that uses PythonInterpreter to expose highlighter.py as a Jython object as described here

Now, when I run this line of code

Highlighter hl = (Highlighter) jf.getJythonObject(Highlighter.class.getName(),
       "WEB-INF/classes/highlighter.py");

I get PyException as follows

Traceback (most recent call last):
File "WEB-INF/classes/highlighter.py", line 3, in
  from pygments import highlight
LookupError: no codec search functions registered: can't find encoding

This occurs if I use Jython v. 2.5.0. In 2.1 I had to copy Jython/Lib directory under src/main/python but then I end up missing IOString module

Or maybe there's a better way to achieve what I'm trying to achieve? I'm curious if anyone was able to use Pygments in Java project.  I would greatly appreciate any suggestions


问:
Is there a way to disable predictive text off for the entire ios app like UIAppearance protocol?
The autocorrection / predictive text feature is generally not desired in the app. I'd like to make a user preference if they would like to disable it for the app but not require them to turn it off across the phone. Is there a way to do this? The documentation doesn't speak to this at all or maybe it does and I just got lost. </p>

答:
You can do it by assigning the property autocorrectionType to false in every textfield that you have.

You can subclass UITextField class and use it in every view controller that you want.

You can use Method Swizzling in order to auto set this property for UITextField class


问:
How to stack animations in Small Basic
I have been trying to simulate jumping in Small Basic, which I had originally though to be simple but is trickier than I expected. Whenever I try to use animations (or move) in a for loop the program always seems to put whatever delay I have assigned at the start followed by a single animation/move. For example:

```<code>GraphicsWindow.Height = 480
GraphicsWindow.Width = 640

pX = 300
pY = 220

GraphicsWindow.KeyDown = KeyPressed

player = Shapes.AddEllipse(40, 40)
Shapes.Move(player, 300, 220)

Sub KeyPressed
  If GraphicsWindow.LastKey = "Space" Then
    For i = 1 To 10
      pY = pY - (10 - i)
      Shapes.Move(player, pX, pY)
      Program.Delay(100)
    EndFor
  EndIf
EndSub
</code>```

I would expect this program to increase the circles why position at a decreasing rate, but instead it waits 1 second (the total number of milliseconds in the loop) and then moves up the whole way at once. How can I achieve what I want and fix this?

答:
+Matthew has the cause right. The threading in Small Basic is a little weird and unpredictable, and yes... the thread with the move command won't see the move requests until after the key press event has completed.

Here is an version of your code with the move placed into the main thread:

```<code>GraphicsWindow.Height = 480
GraphicsWindow.Width = 640

pX = 300
pY = 220

GraphicsWindow.KeyDown = KeyPressed

player = Shapes.AddEllipse(40, 40)
Shapes.Move(player, 300, 220)

top:
If moving = "true" then
  For i = 1 To 10
    pY = pY - (10 - i)
    Shapes.Move(player, pX, pY)
    Program.Delay(100)
  EndFor
  moving = "false"
endif
Goto top

Sub KeyPressed
  If GraphicsWindow.LastKey = "Space" Then
    moving = "true"
  EndIf
EndSub
</code>```

Title: How to stack animations in Small Basic

Body:
I have been trying to simulate jumping in Small Basic, which I had originally though to be simple but is trickier than I expected. Whenever I try to use animations (or move) in a for loop the program always seems to put whatever delay I have assigned at the start followed by a single animation/move. For example:

GraphicsWindow.Height = 480
GraphicsWindow.Width = 640

pX = 300
pY = 220

GraphicsWindow.KeyDown = KeyPressed

player = Shapes.AddEllipse(40, 40)
Shapes.Move(player, 300, 220)

Sub KeyPressed
  If GraphicsWindow.LastKey = "Space" Then
    For i = 1 To 10
      pY = pY - (10 - i)
      Shapes.Move(player, pX, pY)
      Program.Delay(100)
    EndFor
  EndIf
EndSub

I would expect this program to increase the circles why position at a decreasing rate, but instead it waits 1 second (the total number of milliseconds in the loop) and then moves up the whole way at once. How can I achieve what I want and fix this?

Body:
+Matthew has the cause right. The threading in Small Basic is a little weird and unpredictable, and yes... the thread with the move command won't see the move requests until after the key press event has completed.

Here is an version of your code with the move placed into the main thread:

GraphicsWindow.Height = 480
GraphicsWindow.Width = 640

pX = 300
pY = 220

GraphicsWindow.KeyDown = KeyPressed

player = Shapes.AddEllipse(40, 40)
Shapes.Move(player, 300, 220)

top:
If moving = "true" then
  For i = 1 To 10
    pY = pY - (10 - i)
    Shapes.Move(player, pX, pY)
    Program.Delay(100)
  EndFor
  moving = "false"
endif
Goto top

Sub KeyPressed
  If GraphicsWindow.LastKey = "Space" Then
    moving = "true"
  EndIf
EndSub


问:
Is this possible to create many form designs and swap between them?
I've just started building up a simple game in Visual Studio using c# (It is my first low difficulty game). As I open it , it shows me a background image and 2 buttons, "Play" and "Instructions."and I want the form to get changed as I click the play button and open a new menu interface , like : " Game Difficulty / Character Appearence "(those 2 are buttons) , with a new background image. When I click one of them, another menu, etc.
    Can I create multiple designs( Form1.cs[Design1/2/3]) for my from and swap between them ? If not, then how can I do something similar ? </p>

答:
In my opinion, the easiest way would be to make each menu a "User Control" that is the size of the main form, and then you can add a user control for whichever menu you want to show up as you go along.

For example, in the solution explorer I would create a folder and name it "Menus". Then I would create a new "User Control" in there. Copy the Width and Height of the form it will be placed on and apply that to the new control. Then you can add in all the buttons and images you like. Once you're finished, in your main form, you can add the "main-menu" control you made in the designer. For any submenus you want, create user controls for them too. Then, if you want a submenu to show up, capture a click event for the button you want and programmatically add it to the parent form using FindForm().

Pretend that DifficultyScreenControl is the screen that shows up after I click a play button located in my main-menu user control.

Inside of a menu user control

```<code>private void PlayButton_Click(object sender, EventArgs e)
{
    DifficultyScreenControl DiffScr = new DifficultyScreen();
    this.FindForm().Controls.Add(DiffScr);
}
</code>```

Also it is a good idea to either Dispose() or remove these screens one they can't be revisited again as it can free up resources being taken up by them.

Feel free to ask me questions or comment on things to change!

Body:
In my opinion, the easiest way would be to make each menu a "User Control" that is the size of the main form, and then you can add a user control for whichever menu you want to show up as you go along.

For example, in the solution explorer I would create a folder and name it "Menus". Then I would create a new "User Control" in there. Copy the Width and Height of the form it will be placed on and apply that to the new control. Then you can add in all the buttons and images you like. Once you're finished, in your main form, you can add the "main-menu" control you made in the designer. For any submenus you want, create user controls for them too. Then, if you want a submenu to show up, capture a click event for the button you want and programmatically add it to the parent form using FindForm().

Pretend that DifficultyScreenControl is the screen that shows up after I click a play button located in my main-menu user control.

Inside of a menu user control

private void PlayButton_Click(object sender, EventArgs e)
{
    DifficultyScreenControl DiffScr = new DifficultyScreen();
    this.FindForm().Controls.Add(DiffScr);
}

Also it is a good idea to either Dispose() or remove these screens one they can't be revisited again as it can free up resources being taken up by them.

Feel free to ask me questions or comment on things to change!


问:
Error: GET 404 (Not found) error for images, but the images are showing up fine
I am creating a MEAN app with images in one of my models. When the page loads, the images are rendering fine on the page but in my console I am getting this error about them: GET http://localhost:3000/%7B%7Bitem.photo_url%7D%7D 404 (Not Found)  and in my terminal thats running npm and mongod: GET /%7B%7Bitem.photo_url%7D%7D 404 1.999 ms - 2083

I'm unsure what's causing this error, as on the front-end it seems to be fine. Any advice would be appreciated! Thank you!

```<code> .controller("IndexController", [ "$scope", 'items',
 function($scope, items)
   { $scope.items = items.items
     $scope.addItem = function(){
    items.create({
      title: $scope.title,
      photo_url: $scope.photo_url,
      maker: $scope.maker,
      description: $scope.description,
      price: $scope.price })
    $scope.title = '';
    $scope.photo_url = '';
    $scope.maker = '';
    $scope.description = '';
    $scope.price = '';
    $scope.upvotes = '';
   }
}];

 <h2>Style Review</h2>
 <div ng-repeat="item in items | orderBy: '-upvotes'">
    <span class="glyphicon glyphicon-heart-empty" ng-
    click="increaseUpvotes(item)"> </span>
    {{item.upvotes}}

    <p>{{item.title}}</p>
    <a href="#/items/{{item._id}}"><img class="indexImage" src="
        {{item.photo_url}}" alt="item image"/></a>
</div>
</code>```

答:
I'm think %7B%7Bitem.photo_url%7D%7D it's a bad address.
Please check in console.log() url of image
%7B%7 - its not mean about file name
Bitem.photo_url this is var I think
Please paste some code for this problem

Body:
I am creating a MEAN app with images in one of my models. When the page loads, the images are rendering fine on the page but in my console I am getting this error about them: GET http://localhost:3000/%7B%7Bitem.photo_url%7D%7D 404 (Not Found)  and in my terminal thats running npm and mongod: GET /%7B%7Bitem.photo_url%7D%7D 404 1.999 ms - 2083

I'm unsure what's causing this error, as on the front-end it seems to be fine. Any advice would be appreciated! Thank you!

 .controller("IndexController", [ "$scope", 'items',
 function($scope, items)
   { $scope.items = items.items
     $scope.addItem = function(){
    items.create({
      title: $scope.title,
      photo_url: $scope.photo_url,
      maker: $scope.maker,
      description: $scope.description,
      price: $scope.price })
    $scope.title = '';
    $scope.photo_url = '';
    $scope.maker = '';
    $scope.description = '';
    $scope.price = '';
    $scope.upvotes = '';
   }
}];

Style Review

    {{item.upvotes}}

{{item.title}}


问:
Joining tables in Rails through relation table
I have three classes; User, Feed, and Entries. Users have one or more Feeds and Feeds have one or more Entries:

```<code>class Feed < ActiveRecord::Base
  has_many :entries
  has_many :feeds_users
  has_many :users, :through => :feeds_users, :class_name => "User"
end

Class User < ActiveRecord::Base
  has_many :feeds_users
  has_many :feeds, :through => :feeds_users, :class_name => "Feed"
end

class Entry < ActiveRecord:Base
  belongs_to :feed
end
</code>```

The User and Feed classes are related through a third table:

```<code>class FeedsUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :feed
end
</code>```

Now, my problem is that I need to get a certain user's feeds and each feed's latest n entries. I'm fiddling with something like this:

```<code>u = User.first
Feed.joins(:entries, :users).where(:entries => { :created_at => (Time.now-2.days)..Time.now }, :users => u)
</code>```

My problem here is that this generates some SQL that tries to query "users" on the table "feeds" - which doesn't exist.

How do I go about creating a correct query that can give me all feeds and their latest 10 entries for a given user?

答:
Take out has_many :feeds_users. :feeds_users shouldn't be a model.

You should keep the table, but some Rails magic goes on behind the scenes. If you have a table named feeds and a table named users, Rails derives the table name of the look-up unless you specify it differently.

For your example:

```<code>Class Feed < ActiveRecord::Base
  has_many :users
end

Class User < ActiveRecord::Base
  has_many :feeds
end
</code>```

It will look for the relationship in the users_feeds table. If it looked like this:

```<code>Class Feed < ActiveRecord::Base
  belongs_to :user
end

Class User < ActiveRecord::Base
  has_many :feeds
end
</code>```

It would look for the relationship in the user_feeds table.

It's linguistically correct, as many users will have many feeds in the first example, and one user will have many feeds in the second example. That's also a good indicator of whether your relation logic is correct.

It also sounds like you need the has_and_belongs_to_many relationship instead of just has_many.

For a complete run-down on all forms of model associations, check out the guide.

Body:
I have three classes; User, Feed, and Entries. Users have one or more Feeds and Feeds have one or more Entries:

class Feed < ActiveRecord::Base
  has_many :entries
  has_many :feeds_users
  has_many :users, :through => :feeds_users, :class_name => "User"
end

Class User < ActiveRecord::Base
  has_many :feeds_users
  has_many :feeds, :through => :feeds_users, :class_name => "Feed"
end

class Entry < ActiveRecord:Base
  belongs_to :feed
end

The User and Feed classes are related through a third table:

class FeedsUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :feed
end

Now, my problem is that I need to get a certain user's feeds and each feed's latest n entries. I'm fiddling with something like this:

u = User.first
Feed.joins(:entries, :users).where(:entries => { :created_at => (Time.now-2.days)..Time.now }, :users => u)

My problem here is that this generates some SQL that tries to query "users" on the table "feeds" - which doesn't exist.

How do I go about creating a correct query that can give me all feeds and their latest 10 entries for a given user?

Body:
Take out has_many :feeds_users. :feeds_users shouldn't be a model.

You should keep the table, but some Rails magic goes on behind the scenes. If you have a table named feeds and a table named users, Rails derives the table name of the look-up unless you specify it differently.

For your example:

Class Feed < ActiveRecord::Base
  has_many :users
end

Class User < ActiveRecord::Base
  has_many :feeds
end

It will look for the relationship in the users_feeds table. If it looked like this:

Class Feed < ActiveRecord::Base
  belongs_to :user
end

Class User < ActiveRecord::Base
  has_many :feeds
end

It would look for the relationship in the user_feeds table.

It's linguistically correct, as many users will have many feeds in the first example, and one user will have many feeds in the second example. That's also a good indicator of whether your relation logic is correct.

It also sounds like you need the has_and_belongs_to_many relationship instead of just has_many.

For a complete run-down on all forms of model associations, check out the guide.


问:
Why am I suddenly getting an NPE on counters in Flying Saucer?
I have an html template that I have been using with Flying Saucer PDF since last November.  I rebuilt the project recently and suddenly the same HTML and the same code is throwing an NPE.  I narrowed it down to the page counters.  When I remove them it works.  Here is a sample of my html that demonstrates the issue.

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

        Order Status

        Page

 of

Hello World

```

<p>I am sending that as the payload to a small webservice that uses flying saucer to render it and send it back.  This is my code in the service:</p>

<pre class="lang-java prettyprint-override"><code>@RequestMapping(value="/render", method= RequestMethod.POST)
public void renderPdf(@RequestBody String xhtmlContent, HttpServletResponse response) {

    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(xhtmlContent);
    renderer.layout(); //ERROR HAPPENS HERE

    try  {
        response.addHeader("Content-disposition", "attachment;filename=invoice.pdf");
        response.setContentType("application/x-octet-stream");
        renderer.createPDF(response.getOutputStream());
    } catch (Exception e) {
        logger.error("Error creating pdf: ", e);
    }

}
</code>```

And I get the following stack trace:

```<code>java.lang.NullPointerException: null
        at org.xhtmlrenderer.layout.breaker.Breaker.getLanguage(Breaker.java:136) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.breaker.Breaker.getBreakPointsProvider(Breaker.java:124) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.breaker.Breaker.doBreakText(Breaker.java:147) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.breaker.Breaker.breakText(Breaker.java:112) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.InlineBoxing.layoutText(InlineBoxing.java:848) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.InlineBoxing.layoutContent(InlineBoxing.java:201) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutInlineChildren(BlockBox.java:983) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:964) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:321) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:299) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:90) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:967) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:321) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:299) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:90) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:967) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:321) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:299) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:90) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:967) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.pdf.ITextRenderer.layout(ITextRenderer.java:229) ~[flying-saucer-pdf-9.1.4.jar:na]
        at com.byrne.pdfprinter.pdf.PdfController.renderPdf(PdfController.java:26) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_112]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_112]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_112]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_112]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_112]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_112]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_112]
</code>```

Again, let me reiterate, this code worked before I tried to rebuild it.  I did not change my flying saucer version, but I was using RELEASE as my version in Maven.  So just to ensure there weren't issues I specified concrete version numbers going back to the date when it worked and a little before and it still happens.

As I post this I'm tracing through the source but haven't found anything yet.

答:
The version 9.1.5 of flying saucer project fixed the problem.
The 9.1.4 is to blame.</p>

Body:
I have an html template that I have been using with Flying Saucer PDF since last November.  I rebuilt the project recently and suddenly the same HTML and the same code is throwing an NPE.  I narrowed it down to the page counters.  When I remove them it works.  Here is a sample of my html that demonstrates the issue.

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

        Order Status

        Page

 of

Hello World

I am sending that as the payload to a small webservice that uses flying saucer to render it and send it back.  This is my code in the service:

@RequestMapping(value="/render", method= RequestMethod.POST)
public void renderPdf(@RequestBody String xhtmlContent, HttpServletResponse response) {

    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(xhtmlContent);
    renderer.layout(); //ERROR HAPPENS HERE

    try  {
        response.addHeader("Content-disposition", "attachment;filename=invoice.pdf");
        response.setContentType("application/x-octet-stream");
        renderer.createPDF(response.getOutputStream());
    } catch (Exception e) {
        logger.error("Error creating pdf: ", e);
    }

}

And I get the following stack trace:

java.lang.NullPointerException: null
        at org.xhtmlrenderer.layout.breaker.Breaker.getLanguage(Breaker.java:136) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.breaker.Breaker.getBreakPointsProvider(Breaker.java:124) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.breaker.Breaker.doBreakText(Breaker.java:147) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.breaker.Breaker.breakText(Breaker.java:112) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.InlineBoxing.layoutText(InlineBoxing.java:848) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.InlineBoxing.layoutContent(InlineBoxing.java:201) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutInlineChildren(BlockBox.java:983) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:964) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:321) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:299) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:90) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:967) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:321) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:299) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:90) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:967) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:321) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:299) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:90) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:967) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:847) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:776) ~[flying-saucer-core-9.1.4.jar:na]
        at org.xhtmlrenderer.pdf.ITextRenderer.layout(ITextRenderer.java:229) ~[flying-saucer-pdf-9.1.4.jar:na]
        at com.byrne.pdfprinter.pdf.PdfController.renderPdf(PdfController.java:26) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_112]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_112]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_112]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_112]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_112]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_112]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.4.jar:8.5.4]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_112]

Again, let me reiterate, this code worked before I tried to rebuild it.  I did not change my flying saucer version, but I was using RELEASE as my version in Maven.  So just to ensure there weren't issues I specified concrete version numbers going back to the date when it worked and a little before and it still happens.

As I post this I'm tracing through the source but haven't found anything yet.