问:
My broadcastreceiver is not registering in a multithreading app
I'm trying to work with a socket output stream. I want to launch it from inside a broad cast receiver.... I believe the socket is working since the client is always receiving a null value.... But the broadcast listener seems to not be working. I seem it's not even registering as even a simple Toast inside it is not working.

I tried to use a broadcast receiver class and registered it via the Manifest. I worked but I don't want that since :

broadcast registered via manifest stay alive even after shuting down the application

I need to use some Main UI class variable/methods/inner class (here for now, that class is ServerReplyThread). Therefore a separate class for the broadcast receiver isn't going to help me much...

Below is my code ; can you help me fix that ?

```<code>public class MainActivity extends AppCompatActivity {

    public ServerSocket serverSocket;

    public ServerSocket getServerSocket() {
        return serverSocket;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnDemarrer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Thread socketServerThread = new Thread(new SocketServerThread());
                socketServerThread.start();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        MainActivity.this.registerReceiver(smsReceived, filter);
        sendBroadcast(new Intent("android.provider.Telephony.SMS_RECEIVED"));
    }

    @Override
    public void onPause() {
        MainActivity.this.unregisterReceiver(smsReceived);
        super.onPause();
    }

    private class SocketServerThread extends Thread {

        static final int SocketServerPORT = 7777;

        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(SocketServerPORT);

                while (true) {
                    Socket socket = serverSocket.accept();

                    SocketServerReceiveThread socketServerReplyThread
                            = new SocketServerReceiveThread(socket);
                    socketServerReplyThread.run();
                }
            } catch (IOException e) {
                e.printStackTrace();
    }}}

    private class SocketServerReceiveThread  extends Thread {

        private Socket hostThreadSocket;

        SocketServerReceiveThread(Socket socket) {
            hostThreadSocket = socket;
        }

        @Override
        public void run() {
            try{
                InputStream is = hostThreadSocket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(is);

                //Launch USSD query

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

    private class SocketServerReplyThread  extends Thread {

        private Socket hostThreadSocket;
        private String sms;
        SocketServerReplyThread(Socket socket, String sms) {
            hostThreadSocket = socket;
            this.sms = sms;
        }

        @Override
        public void run() {
            try{

                OutputStream os = hostThreadSocket.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);

                MyClass myclass = new MyClass();
                myclass.setSms(sms);
                oos.writeObject(dt2);
                hostThreadSocket.close();

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

    BroadcastReceiver smsReceived = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().
                    equals("android.provider.Telephony.SMS_RECEIVED")) {
                StringBuilder sb = new StringBuilder();
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Object[] pdus = (Object[])
                            bundle.get("pdus");
                    for (Object pdu : pdus) {
                        SmsMessage smsMessage =
                                SmsMessage.createFromPdu
                                        ((byte[]) pdu);
                        sb.append("body - " + smsMessage.
                                getDisplayMessageBody());
                    }

                    Toast.makeText(context,sb.toString(),Toast.LENGTH_LONG); //This is not popping up

                    try {
                        Socket socket = getServerSocket().accept();
                        SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(socket,sb.toString());
                        socketServerReplyThread.run();
                    } catch (IOException e) {
                        e.printStackTrace();
    }}}}};

}
</code>```

Below are the permissions of my Manifest

```<code><!-- TELEPHONY SETTINGS-->
    <uses-feature
        android:name="android.hardware.telephony"
        android:required="true" />

    <!-- Permission needed to read TelephoneManager data -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- END -->

    <!-- Permissions to dial -->
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.CALL_PRIVILEGED" />
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />

    <!-- END -->

    <!-- SMS permissions -->
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />

    <!-- END -->
<!-- END OF TELEPHONY SETTINGS-->
</code>```

答:
When the SMS came your app is in foreground/visible to user ? If not in foreground/visible you want receive it as you are unregistering receiver in onPause(). If you like to receive it always define receiver in the AndroidMainfes.xml file.
You can register/unregister in onStart() and onStop() of activity life cycle</p>

Body:
I'm trying to work with a socket output stream. I want to launch it from inside a broad cast receiver.... I believe the socket is working since the client is always receiving a null value.... But the broadcast listener seems to not be working. I seem it's not even registering as even a simple Toast inside it is not working.

I tried to use a broadcast receiver class and registered it via the Manifest. I worked but I don't want that since :

broadcast registered via manifest stay alive even after shuting down the application

I need to use some Main UI class variable/methods/inner class (here for now, that class is ServerReplyThread). Therefore a separate class for the broadcast receiver isn't going to help me much...

Below is my code ; can you help me fix that ?

public class MainActivity extends AppCompatActivity {

    public ServerSocket serverSocket;

    public ServerSocket getServerSocket() {
        return serverSocket;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnDemarrer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Thread socketServerThread = new Thread(new SocketServerThread());
                socketServerThread.start();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        MainActivity.this.registerReceiver(smsReceived, filter);
        sendBroadcast(new Intent("android.provider.Telephony.SMS_RECEIVED"));
    }

    @Override
    public void onPause() {
        MainActivity.this.unregisterReceiver(smsReceived);
        super.onPause();
    }

    private class SocketServerThread extends Thread {

        static final int SocketServerPORT = 7777;

        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(SocketServerPORT);

                while (true) {
                    Socket socket = serverSocket.accept();

                    SocketServerReceiveThread socketServerReplyThread
                            = new SocketServerReceiveThread(socket);
                    socketServerReplyThread.run();
                }
            } catch (IOException e) {
                e.printStackTrace();
    }}}

    private class SocketServerReceiveThread  extends Thread {

        private Socket hostThreadSocket;

        SocketServerReceiveThread(Socket socket) {
            hostThreadSocket = socket;
        }

        @Override
        public void run() {
            try{
                InputStream is = hostThreadSocket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(is);

                //Launch USSD query

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

    private class SocketServerReplyThread  extends Thread {

        private Socket hostThreadSocket;
        private String sms;
        SocketServerReplyThread(Socket socket, String sms) {
            hostThreadSocket = socket;
            this.sms = sms;
        }

        @Override
        public void run() {
            try{

                OutputStream os = hostThreadSocket.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);

                MyClass myclass = new MyClass();
                myclass.setSms(sms);
                oos.writeObject(dt2);
                hostThreadSocket.close();

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

    BroadcastReceiver smsReceived = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().
                    equals("android.provider.Telephony.SMS_RECEIVED")) {
                StringBuilder sb = new StringBuilder();
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Object[] pdus = (Object[])
                            bundle.get("pdus");
                    for (Object pdu : pdus) {
                        SmsMessage smsMessage =
                                SmsMessage.createFromPdu
                                        ((byte[]) pdu);
                        sb.append("body - " + smsMessage.
                                getDisplayMessageBody());
                    }

                    Toast.makeText(context,sb.toString(),Toast.LENGTH_LONG); //This is not popping up

                    try {
                        Socket socket = getServerSocket().accept();
                        SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(socket,sb.toString());
                        socketServerReplyThread.run();
                    } catch (IOException e) {
                        e.printStackTrace();
    }}}}};

}

Below are the permissions of my Manifest

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

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

    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.CALL_PRIVILEGED" />
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />


来源: stackexchange

问:
Horizontal List that wraps without overlapping
I'm trying to create a list (UL) which is displayed horizontally. Each item has some padding around it. The problem I'm having is that when the list gets to the end of the line and starts wrapping to the next line, it doesn't render low enough and starts overlapping the first line. Can someone help me figure out how to get the wrapping to go on to the next line without overlapping?

Here's the CSS

```<code>.letterlist ul {
   margin: 0; padding: 0;
    list-style-type: none; list-style-image: none;
}

.letterlist li
{
    display:inline;
}

.letterlist li a
{
    margin: 4px;
    color:#eee;
    padding: 10px 20px;
    background:#3c66ad;
    font-size:16px;
    font-weight: bold;
    border-radius: 5px;
}
</code>```

Here's the HTML

```<code><p>
<ul class="letterlist">
    <li><a href="/list/A">A</a></li>
    <li><a href="/list/B">B</a></li>
    <li><a href="/list/C">C</a></li>
    <li><a href="/list/D">D</a></li>
    <li><a href="/list/E">E</a></li>
    <li><a href="/list/F">F</a></li>
    <li><a href="/list/G">G</a></li>
    <li><a href="/list/H">H</a></li>
    <li><a href="/list/I">I</a></li>
    <li><a href="/list/J">J</a></li>
    <li><a href="/list/K">K</a></li>
    <li><a href="/list/L">L</a></li>
    <li><a href="/list/M">M</a></li>
    <li><a href="/list/N">N</a></li>
    <li><a href="/list/O">O</a></li>
    <li><a href="/list/P">P</a></li>
    <li><a href="/list/Q">Q</a></li>
    <li><a href="/list/R">R</a></li>
    <li><a href="/list/S">S</a></li>
    <li><a href="/list/T">T</a></li>
    <li><a href="/list/U">U</a></li>
    <li><a href="/list/V">V</a></li>
    <li><a href="/list/W">W</a></li>
    <li><a href="/list/X">X</a></li>
    <li><a href="/list/Y">Y</a></li>
    <li><a href="/list/Z">Z</a></li>
</ul>
</p>
</code>```

I'm using blueprint CSS if that matters.

答:
You can either float all the li elements or give them display: inline-block, then give them some top and bottom margin:

```<code>.letterlist li {
    float: left;
       /* or */
    display: inline-block;

    margin: 20px 0;
}
</code>```

See: http://www.jsfiddle.net/yijiang/z8Gfe/ for a simple example. And by the way, ul elements are not valid in p paragraphs

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create a list (UL) which is displayed horizontally. Each item has some padding around it. The problem I'm having is that when the list gets to the end of the line and starts wrapping to the next line, it doesn't render low enough and starts overlapping the first line. Can someone help me figure out how to get the wrapping to go on to the next line without overlapping?

Here's the CSS

.letterlist ul {
   margin: 0; padding: 0;
    list-style-type: none; list-style-image: none;
}

.letterlist li
{
    display:inline;
}

.letterlist li a
{
    margin: 4px;
    color:#eee;
    padding: 10px 20px;
    background:#3c66ad;
    font-size:16px;
    font-weight: bold;
    border-radius: 5px;
}

Here's the HTML

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W

X

Y

Z

I'm using blueprint CSS if that matters.

Body:
You can either float all the li elements or give them display: inline-block, then give them some top and bottom margin:

.letterlist li {
    float: left;
       /* or */
    display: inline-block;

    margin: 20px 0;
}

See: http://www.jsfiddle.net/yijiang/z8Gfe/ for a simple example. And by the way, ul elements are not valid in p paragraphs


问:
Liferay 7- Theme does not appear correctly in IE9
Many of styles are not applied and pages looked weird in IE9, because IE has CSS limitation. The problem is that i can't modify css because it is generated with Liferay. </p>

答: IE9 indeed has limited support, however, as you can create your own theme, you can change the css that is generated. </p>

ContentLicense: CC BY-SA 3.0


问:
Accept multiple files in parameter using args python
I need to be able to import and manipulate multiple text files in the function parameter. I figured using *args in the function parameter would work, but I get an error about tuples and strings.

```<code>def open_file(*filename):
   file = open(filename,'r')
   text = file.read().strip(punctuation).lower()
   print(text)

open_file('Strawson.txt','BigData.txt')
ERROR: expected str, bytes or os.PathLike object, not tuple
</code>```

How do I do this the right way?

答:
When you use the *args syntax in a function parameter list it allows you to call the function with multiple arguments that will appear as a tuple to your function. So to perform a process on each of those arguments you need to create a loop. Like this:

```<code>from string import punctuation

# Make a translation table to delete punctuation
no_punct = dict.fromkeys(map(ord, punctuation))

def open_file(*filenames):
    for filename in filenames:
        print('FILE', filename)
        with open(filename) as file:
            text = file.read()
        text = text.translate(no_punct).lower()
        print(text)
        print()

#test

open_file('Strawson.txt', 'BigData.txt')
</code>```

I've also included a dictionary no_punct that can be used to remove all punctuation from the text. And I've used a with statement so each file will get closed automatically.

If you want the function to "return" the processed contents of each file, you can't just put return into the loop because that tells the function to exit. You could save the file contents into a list, and return that at the end of the loop. But a better option is to turn the function into a generator. The Python yield keyword makes that simple. Here's an example to get you started.

```<code>def open_file(*filenames):
    for filename in filenames:
        print('FILE', filename)
        with open(filename) as file:
            text = file.read()
        text = text.translate(no_punct).lower()
        yield text

def create_tokens(*filenames):
    tokens = []
    for text in open_file(*filenames):
        tokens.append(text.split())
    return tokens

files = '1.txt','2.txt','3.txt'
tokens = create_tokens(*files)
print(tokens)
</code>```

Note that I removed the word.strip(punctuation).lower() stuff from create_tokens: it's not needed because we're already removing all punctuation and folding the text to lower-case inside open_file.

We don't really need two functions here. We can combine everything into one:

```<code>def create_tokens(*filenames):
    for filename in filenames:
        #print('FILE', filename)
        with open(filename) as file:
            text = file.read()
        text = text.translate(no_punct).lower()
        yield text.split()

tokens = list(create_tokens('1.txt','2.txt','3.txt'))
print(tokens)
</code>```

Body:
I need to be able to import and manipulate multiple text files in the function parameter. I figured using *args in the function parameter would work, but I get an error about tuples and strings.

def open_file(*filename):
   file = open(filename,'r')
   text = file.read().strip(punctuation).lower()
   print(text)

open_file('Strawson.txt','BigData.txt')
ERROR: expected str, bytes or os.PathLike object, not tuple

How do I do this the right way?

Body:
When you use the *args syntax in a function parameter list it allows you to call the function with multiple arguments that will appear as a tuple to your function. So to perform a process on each of those arguments you need to create a loop. Like this:

from string import punctuation

# Make a translation table to delete punctuation
no_punct = dict.fromkeys(map(ord, punctuation))

def open_file(*filenames):
    for filename in filenames:
        print('FILE', filename)
        with open(filename) as file:
            text = file.read()
        text = text.translate(no_punct).lower()
        print(text)
        print()

#test

open_file('Strawson.txt', 'BigData.txt')

I've also included a dictionary no_punct that can be used to remove all punctuation from the text. And I've used a with statement so each file will get closed automatically.

If you want the function to "return" the processed contents of each file, you can't just put return into the loop because that tells the function to exit. You could save the file contents into a list, and return that at the end of the loop. But a better option is to turn the function into a generator. The Python yield keyword makes that simple. Here's an example to get you started.

def open_file(*filenames):
    for filename in filenames:
        print('FILE', filename)
        with open(filename) as file:
            text = file.read()
        text = text.translate(no_punct).lower()
        yield text

def create_tokens(*filenames):
    tokens = []
    for text in open_file(*filenames):
        tokens.append(text.split())
    return tokens

files = '1.txt','2.txt','3.txt'
tokens = create_tokens(*files)
print(tokens)

Note that I removed the word.strip(punctuation).lower() stuff from create_tokens: it's not needed because we're already removing all punctuation and folding the text to lower-case inside open_file.

We don't really need two functions here. We can combine everything into one:

def create_tokens(*filenames):
    for filename in filenames:
        #print('FILE', filename)
        with open(filename) as file:
            text = file.read()
        text = text.translate(no_punct).lower()
        yield text.split()

tokens = list(create_tokens('1.txt','2.txt','3.txt'))
print(tokens)


问:
No response from MediaWiki API using jQuery
I've tried to get some content from Wikipedia as JSON:

```<code>$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json", function(data) {
    doSomethingWith(data);
});
</code>```

But I got nothing in response. If I paste to the browser's adress bar, something like

```<code>http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles=jQuery&format=json
</code>```

I get the expected content. What's wrong?

答:
One option to perform CORS request instead of JSONP is to explicitly include parameter origin=* in request url, for example:

var title = "jQuery";

$.getJSON("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&origin=*", function(data) {
    console.log(data.query.pages);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I've tried to get some content from Wikipedia as JSON:

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json", function(data) {
    doSomethingWith(data);
});

But I got nothing in response. If I paste to the browser's adress bar, something like

http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles=jQuery&format=json

I get the expected content. What's wrong?

Body:
One option to perform CORS request instead of JSONP is to explicitly include parameter origin=* in request url, for example:

var title = "jQuery";

$.getJSON("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&origin=*", function(data) {
    console.log(data.query.pages);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
How to insert multiple rows at once laravel 5.3
I want to insert an array with an id : blade.php
enter image description here

```<code><tr>
<td class="text-left">{{$count}}</td>
<td class="text-left"><img src="{{ asset('/' . $data->image_file) }}" class="img-circle" width="35px" height="35px"/></td>
<td class="text-left">{{$data->student_id}}</td>
<td class="text-left">
    {{ App\Models\student_subject:: where('id', '=', $subject)->value('sub_name') }}
</td>

<td class="text-left"> <input type="text" class="form-control"  placeholder="Mark" name="sub_mark[]" max="100" data-parsley-max="100" required="" data-parsley-required-message ="Subject Mark is required" data-parsley-trigger="change focusout"> </td>

<td class="text-left"> <input type="text" class="form-control" placeholder="Class Test Mark" name="ct_mark[]" max="20" data-parsley-max="20" required="" data-parsley-required-message ="CT Mark is required" data-parsley-trigger="change focusout"> </td>
</code>```

you can see all code in here
enter link description here

when I tried to submit the form , it insert rows with same id..
enter image description here

here is my controller

```<code>public function PostAddResult(Request $request) {
$student_id= $request->input('student_id');
$sub_name= $request->input('sub_name');
$class_name= Session::get('class_name');
$exam_id= Session::get('exam_name');

$sub_mark= $request->input('sub_mark');
$ct_mark= $request->input('ct_mark');

 $i = 0;
 foreach($sub_mark as $marks){

    $student_res = new student_results();
    $student_res->student_id = $student_id;
    $student_res->class_name = $class_name;
    $student_res->sub_name = $sub_name;
    $student_res->sub_mark = $marks;
    $student_res->ct_mark = $ct_mark[$i];
    $student_res->exam_id = $exam_id;
    $student_res->save();

 }

 $notification = array(
            'message'=>'Student Marks Add Successfully',
            'alert-type'=>'success',
        );

return redirect('/addResult')->with($notification);

}
</code>```

答:
You want to get separate student IDs and subject names for each record, so change this:

```<code><input type="hidden" name="student_id" value="{{ $data->student_id }}">
<input type="hidden" name="sub_name" value="{{ $subject }}">
</code>```

To:

```<code><input type="hidden" name="student_id[]" value="{{ $data->student_id }}">
<input type="hidden" name="sub_name[]" value="{{ $subject }}">
</code>```

Then you'll be able to iterate over marks, subject names and student IDs:

```<code>for ($i = 0; $i < count($sub_mark); $i++) {
    $student_res = new student_results();
    $student_res->student_id = $student_id[$i];
    $student_res->class_name = $class_name;
    $student_res->sub_name = $sub_name[$i];
    $student_res->sub_mark = $sub_mark[$i];
    $student_res->ct_mark = $ct_mark[$i];
    $student_res->exam_id = $exam_id;
    $student_res->save();
 }
</code>```

Body:
I want to insert an array with an id : blade.php
enter image description here

{{$count}}
image_file) }}" class="img-circle" width="35px" height="35px"/>
{{$data->student_id}}

    {{ App\Models\student_subject:: where('id', '=', $subject)->value('sub_name') }}

 <input type="text" class="form-control"  placeholder="Mark" name="sub_mark[]" max="100" data-parsley-max="100" required="" data-parsley-required-message ="Subject Mark is required" data-parsley-trigger="change focusout">

 <input type="text" class="form-control" placeholder="Class Test Mark" name="ct_mark[]" max="20" data-parsley-max="20" required="" data-parsley-required-message ="CT Mark is required" data-parsley-trigger="change focusout">

you can see all code in here
enter link description here

when I tried to submit the form , it insert rows with same id..
enter image description here

here is my controller

public function PostAddResult(Request $request) {
$student_id= $request->input('student_id');
$sub_name= $request->input('sub_name');
$class_name= Session::get('class_name');
$exam_id= Session::get('exam_name');

$sub_mark= $request->input('sub_mark');
$ct_mark= $request->input('ct_mark');

 $i = 0;
 foreach($sub_mark as $marks){

    $student_res = new student_results();
    $student_res->student_id = $student_id;
    $student_res->class_name = $class_name;
    $student_res->sub_name = $sub_name;
    $student_res->sub_mark = $marks;
    $student_res->ct_mark = $ct_mark[$i];
    $student_res->exam_id = $exam_id;
    $student_res->save();

 }

 $notification = array(
            'message'=>'Student Marks Add Successfully',
            'alert-type'=>'success',
        );

return redirect('/addResult')->with($notification);

}

Body:
You want to get separate student IDs and subject names for each record, so change this:

<input type="hidden" name="student_id" value="{{ $data->student_id }}">
<input type="hidden" name="sub_name" value="{{ $subject }}">

To:

<input type="hidden" name="student_id[]" value="{{ $data->student_id }}">
<input type="hidden" name="sub_name[]" value="{{ $subject }}">

Then you'll be able to iterate over marks, subject names and student IDs:

for ($i = 0; $i < count($sub_mark); $i++) {
    $student_res = new student_results();
    $student_res->student_id = $student_id[$i];
    $student_res->class_name = $class_name;
    $student_res->sub_name = $sub_name[$i];
    $student_res->sub_mark = $sub_mark[$i];
    $student_res->ct_mark = $ct_mark[$i];
    $student_res->exam_id = $exam_id;
    $student_res->save();
 }


问:
Minimisation using the nlminb R-function
I would like to find the 4-dimensional vector that minimises some function f which depends on 4 variables. The first three variables take on strictly positive values; the fourth one is unconstrained.
To do this, I would like to use R. I have tried to apply the nlminb function with lower=c(0.001, 0.001, 0.001, -Inf) as one of its optional argument. The procedure does converge but it turns out that the proposed solution does not satisfy the constraint !
I have an alternative solution that consists of using an exponential transformation. However, I would appreciate to figure out why R returns a solution that does not meet my requirements.

Any comment will be appreciated,
Thanks,
Marco

答:
It would be very difficult for me to provide that function here. The reason is that it depends on a number of pre-defined stuff.
Anyway, I am not sure to understand why this occurs but I have realized that my function sometimes returns NaN due to very very large numbers. Actually, I have some doubt about convergence.
On the other hand, I have made some modifications and the alternative solution seems to work well.
As a conclusion, I think that the problem came from my function, not from nlminb.

Best,
Marco


问:
Mysterious NullPointerException when calling execute() on SwingWorker
I am making this JavaFX mass calculator, that essentially consists of a button that executes a SwingWorker background thread to calculate certain ratios or factors or whatnot.

I've realized that for my factor and prime factor calculations (when I try to find all the factors and prime factors of a number the user inputs), I get this NullPointerException after the calculation has been performed about 3-5 times.

Here's the script that executes when the button is clicked:

```<code>public static longCalculationThread calculationThread;

//Called by the calculate button
@FXML
void callCalculation(ActionEvent event) throws IOException, InterruptedException {

    Long number = 0L;
    Long lowerBound = 0L;
    Long higherBound = 0L;

    try {
        //Bunch of input verification logic here. The logic here also creates the variables for the thread bundle

        //Enabling progress UI since no errors were encoundered...
        excelPane.setVisible(false);
        progressPane.setDisable(false);
        progressPane.setVisible(true);

        //Preparing threadBundle, which is just a bunch of fields out into a data holding class [not shown]

        calculationThread = new longCalculationThread(threadBundle);
        calculationThread.execute();
        System.gc(); //For the objects of the previous calculationThread
    }
}
</code>```

And here's how the longCalculationThread is structured:

```<code>package PrimusForPC;

public class longCalculationThread extends SwingWorker<Void, Void> {

private ArrayList<Long> longResults = new ArrayList<>();
private ArrayList<String> stringResults = new ArrayList<>();

private calculationHolder.calculationType type;
private JFXProgressBar progressBar;
private Text progressText;
private GridView<String> answerGridView;
private Pane mainPane, progressPane;
private long mainNumber, lowerNum, upperNum;
private boolean shouldExport;
private ExcelWriter.spreadsheetTypes exportType;
private int excelExportLimit;
private JFXButton calcButton;
private Menu selectionMenu;

private static double acceptableAccuracy = 0.004; //The degree of accuracty for pi and phi couples
public static final double PHI = 1.6180339887498948482045;

public boolean shouldDie; //Called externally to kill the thread. Hasn't been implemented yet

longCalculationThread(threadArgumentBundle bundle){
    progressBar = bundle.progressBar;
    answerGridView = bundle.answerGridView;
    type = bundle.type;
    mainNumber = bundle.primaryNumber;
    upperNum = bundle.upperNum;
    lowerNum = bundle.lowerNum;
    progressText = bundle.progressText;
    mainPane = bundle.mainPane;
    progressPane = bundle.progressPane;
    exportType = bundle.exportType;
    shouldExport = bundle.shouldExport;
    excelExportLimit = bundle.excelExportLimit;
    calcButton = bundle.button;
    selectionMenu = bundle.selectionMenu;
}

@Override
public Void doInBackground(){
    System.out.println("Thread started " + Thread.currentThread().getName());
    Platform.runLater(new Runnable() {
    @Override
    public void run() {
        progressBar.isIndeterminate();
        progressBar.progressProperty().setValue(0);
        calcButton.setDisable(true);
        selectionMenu.setDisable(true);
      }
    });

    switch (type){
        case factors:
            findfactors();
            break;
        case primeFactors:
            findPrimeFactors();
            break;
        case primesUpToX:
            findPrimesUpToX();
            break;
//Bunch of other cases here...
    }
    try {
        publishResults();
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(longCalculationThread.class.getName()).log(Level.SEVERE, null, ex);
    }
    reEndableInterface();
    System.gc();
    System.out.println("Thread ended " + Thread.currentThread().getName() + "\n");
    return null;
}

static private long getSquareRoot (long number){
    //For calculations square root only matters for larger numbers
    //for numbers below 5 it doesn't really matter
    if (number > 5){
        number =  (long) Math.ceil(Math.sqrt(number));
    }
return number;
}

private void findfactors(){
    progressText.setText("Finding factors...");
    long root = getSquareRoot(mainNumber);
    double incrementValue = 1/(double)root;
      for (long divisor = 1; divisor <= root; divisor++) {
       setProgressBar(progressBar.getProgress() + incrementValue);
       if (mainNumber % divisor == 0) {
           longResults.add(divisor);
           longResults.add((mainNumber/divisor));
       }
   }
}

private void findPrimeFactors(){
    findfactors();
    progressText.setText("Separating prime factors from composite factors...");
    progressBar.progressProperty().set(0);
    double incrementValue = 1/(double)longResults.size();
    ArrayList <Long> realResults = new ArrayList<>();
    for (long factor: longResults){
       if (isPrime(factor)) realResults.add(factor);
       setProgressBar(progressBar.getProgress() + incrementValue);
    }

    longResults = realResults;
}

static boolean isPrime(long number){
    if (number == 1) return false;
    if (number == 2 || number == 3 || number == 5) return true;
    long root = getSquareRoot(number);
    for (int divisor = 2; divisor <= root; divisor++)
        if (number % divisor == 0) return false;
    return true;
}

private void publishResults() throws IOException, InterruptedException{

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                answerGridView.getItems().setAll(stringResults);
              }
            });

//To make UI interface useable again
private void reEndableInterface(){
     Platform.runLater(new Runnable() {
            @Override
            public void run() {
                progressPane.setDisable(true);
                progressPane.setVisible(false);
                mainPane.setDisable(false);
                mainPane.setVisible(true);
                calcButton.setDisable(false);
                System.out.println("Button enabled " + Thread.currentThread().getName());
                selectionMenu.setDisable(false);
              }
            });
}
</code>```

I'm not exactly sure where this NullPointerException is coming from, or why it seems to only surface when I'm using the "find factors" or "find prime factors" calculations. Here is a look at the error log (sorry it's so long, didn't know where to cut off).

```<code>Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.sun.javafx.text.PrismTextLayout.addTextRun(PrismTextLayout.java:755)
at com.sun.javafx.text.GlyphLayout.addTextRun(GlyphLayout.java:140)
at com.sun.javafx.text.GlyphLayout.breakRuns(GlyphLayout.java:312)
at com.sun.javafx.text.PrismTextLayout.buildRuns(PrismTextLayout.java:770)
at com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1021)
at com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
at com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
at javafx.scene.text.Text.getLogicalBounds(Text.java:358)
at javafx.scene.text.Text.impl_computeGeomBounds(Text.java:1168)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.updateTxBounds(Node.java:3641)
at javafx.scene.Node.getTransformedBounds(Node.java:3424)
at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1724)
at javafx.scene.Parent.updateCachedBounds(Parent.java:1588)
at javafx.scene.Parent.recomputeBounds(Parent.java:1527)
at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1380)
at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.updateTxBounds(Node.java:3641)
at javafx.scene.Node.getTransformedBounds(Node.java:3424)
at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1724)
at javafx.scene.Parent.updateCachedBounds(Parent.java:1588)
at javafx.scene.Parent.recomputeBounds(Parent.java:1527)
at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1380)
at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.updateTxBounds(Node.java:3641)
at javafx.scene.Node.getTransformedBounds(Node.java:3424)
at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1724)
at javafx.scene.Parent.updateCachedBounds(Parent.java:1588)
at javafx.scene.Parent.recomputeBounds(Parent.java:1527)
at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1380)
at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.impl_intersectsBounds(Node.java:5013)
at javafx.scene.layout.Region.impl_pickNodeLocal(Region.java:2931)
at javafx.scene.Node.impl_pickNode(Node.java:4912)
at javafx.scene.layout.Region.impl_pickNodeLocal(Region.java:2936)
at javafx.scene.Node.impl_pickNode(Node.java:4912)
at javafx.scene.Scene$MouseHandler.pickNode(Scene.java:3899)
at javafx.scene.Scene$MouseHandler.access$1600(Scene.java:3485)
at javafx.scene.Scene.pick(Scene.java:1942)
at javafx.scene.Scene.access$6700(Scene.java:159)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3799)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
</code>```

And then at the end the console just spams:

```<code>    java.lang.ArrayIndexOutOfBoundsException
</code>```

indefinitely.

As I said, I really don't know why this is happening. The calculation works for the first few times, then this error occurs and freezes the application, requiring a complete restart.

答:
Thanks to the people who commented my question - the links revealed the problem!

I was using a SwingWorker because I wanted to be able to influence the UI thread directly (since Program.runLater can flood the UI thread if called repeatedly and frequently).

It turns out SwingWorkers can't have that functionality in JavaFX, so me trying to affect the UI thread directly was causing those errors. So, I went back to using a Thread, and used the throttling logic that was provided by the link in the comments. That allowed me to use Program.runLater in a Thread without flooding the UI thread.

Body:
I am making this JavaFX mass calculator, that essentially consists of a button that executes a SwingWorker background thread to calculate certain ratios or factors or whatnot.

I've realized that for my factor and prime factor calculations (when I try to find all the factors and prime factors of a number the user inputs), I get this NullPointerException after the calculation has been performed about 3-5 times.

Here's the script that executes when the button is clicked:

public static longCalculationThread calculationThread;

//Called by the calculate button
@FXML
void callCalculation(ActionEvent event) throws IOException, InterruptedException {

    Long number = 0L;
    Long lowerBound = 0L;
    Long higherBound = 0L;

    try {
        //Bunch of input verification logic here. The logic here also creates the variables for the thread bundle

        //Enabling progress UI since no errors were encoundered...
        excelPane.setVisible(false);
        progressPane.setDisable(false);
        progressPane.setVisible(true);

        //Preparing threadBundle, which is just a bunch of fields out into a data holding class [not shown]

        calculationThread = new longCalculationThread(threadBundle);
        calculationThread.execute();
        System.gc(); //For the objects of the previous calculationThread
    }
}

And here's how the longCalculationThread is structured:

package PrimusForPC;

public class longCalculationThread extends SwingWorker<Void, Void> {

private ArrayList<Long> longResults = new ArrayList<>();
private ArrayList<String> stringResults = new ArrayList<>();

private calculationHolder.calculationType type;
private JFXProgressBar progressBar;
private Text progressText;
private GridView<String> answerGridView;
private Pane mainPane, progressPane;
private long mainNumber, lowerNum, upperNum;
private boolean shouldExport;
private ExcelWriter.spreadsheetTypes exportType;
private int excelExportLimit;
private JFXButton calcButton;
private Menu selectionMenu;

private static double acceptableAccuracy = 0.004; //The degree of accuracty for pi and phi couples
public static final double PHI = 1.6180339887498948482045;

public boolean shouldDie; //Called externally to kill the thread. Hasn't been implemented yet

longCalculationThread(threadArgumentBundle bundle){
    progressBar = bundle.progressBar;
    answerGridView = bundle.answerGridView;
    type = bundle.type;
    mainNumber = bundle.primaryNumber;
    upperNum = bundle.upperNum;
    lowerNum = bundle.lowerNum;
    progressText = bundle.progressText;
    mainPane = bundle.mainPane;
    progressPane = bundle.progressPane;
    exportType = bundle.exportType;
    shouldExport = bundle.shouldExport;
    excelExportLimit = bundle.excelExportLimit;
    calcButton = bundle.button;
    selectionMenu = bundle.selectionMenu;
}

@Override
public Void doInBackground(){
    System.out.println("Thread started " + Thread.currentThread().getName());
    Platform.runLater(new Runnable() {
    @Override
    public void run() {
        progressBar.isIndeterminate();
        progressBar.progressProperty().setValue(0);
        calcButton.setDisable(true);
        selectionMenu.setDisable(true);
      }
    });

    switch (type){
        case factors:
            findfactors();
            break;
        case primeFactors:
            findPrimeFactors();
            break;
        case primesUpToX:
            findPrimesUpToX();
            break;
//Bunch of other cases here...
    }
    try {
        publishResults();
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(longCalculationThread.class.getName()).log(Level.SEVERE, null, ex);
    }
    reEndableInterface();
    System.gc();
    System.out.println("Thread ended " + Thread.currentThread().getName() + "\n");
    return null;
}

static private long getSquareRoot (long number){
    //For calculations square root only matters for larger numbers
    //for numbers below 5 it doesn't really matter
    if (number > 5){
        number =  (long) Math.ceil(Math.sqrt(number));
    }
return number;
}

private void findfactors(){
    progressText.setText("Finding factors...");
    long root = getSquareRoot(mainNumber);
    double incrementValue = 1/(double)root;
      for (long divisor = 1; divisor <= root; divisor++) {
       setProgressBar(progressBar.getProgress() + incrementValue);
       if (mainNumber % divisor == 0) {
           longResults.add(divisor);
           longResults.add((mainNumber/divisor));
       }
   }
}

private void findPrimeFactors(){
    findfactors();
    progressText.setText("Separating prime factors from composite factors...");
    progressBar.progressProperty().set(0);
    double incrementValue = 1/(double)longResults.size();
    ArrayList <Long> realResults = new ArrayList<>();
    for (long factor: longResults){
       if (isPrime(factor)) realResults.add(factor);
       setProgressBar(progressBar.getProgress() + incrementValue);
    }

    longResults = realResults;
}

static boolean isPrime(long number){
    if (number == 1) return false;
    if (number == 2 || number == 3 || number == 5) return true;
    long root = getSquareRoot(number);
    for (int divisor = 2; divisor <= root; divisor++)
        if (number % divisor == 0) return false;
    return true;
}

private void publishResults() throws IOException, InterruptedException{

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                answerGridView.getItems().setAll(stringResults);
              }
            });

//To make UI interface useable again
private void reEndableInterface(){
     Platform.runLater(new Runnable() {
            @Override
            public void run() {
                progressPane.setDisable(true);
                progressPane.setVisible(false);
                mainPane.setDisable(false);
                mainPane.setVisible(true);
                calcButton.setDisable(false);
                System.out.println("Button enabled " + Thread.currentThread().getName());
                selectionMenu.setDisable(false);
              }
            });
}

I'm not exactly sure where this NullPointerException is coming from, or why it seems to only surface when I'm using the "find factors" or "find prime factors" calculations. Here is a look at the error log (sorry it's so long, didn't know where to cut off).

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.sun.javafx.text.PrismTextLayout.addTextRun(PrismTextLayout.java:755)
at com.sun.javafx.text.GlyphLayout.addTextRun(GlyphLayout.java:140)
at com.sun.javafx.text.GlyphLayout.breakRuns(GlyphLayout.java:312)
at com.sun.javafx.text.PrismTextLayout.buildRuns(PrismTextLayout.java:770)
at com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1021)
at com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
at com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
at javafx.scene.text.Text.getLogicalBounds(Text.java:358)
at javafx.scene.text.Text.impl_computeGeomBounds(Text.java:1168)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.updateTxBounds(Node.java:3641)
at javafx.scene.Node.getTransformedBounds(Node.java:3424)
at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1724)
at javafx.scene.Parent.updateCachedBounds(Parent.java:1588)
at javafx.scene.Parent.recomputeBounds(Parent.java:1527)
at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1380)
at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.updateTxBounds(Node.java:3641)
at javafx.scene.Node.getTransformedBounds(Node.java:3424)
at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1724)
at javafx.scene.Parent.updateCachedBounds(Parent.java:1588)
at javafx.scene.Parent.recomputeBounds(Parent.java:1527)
at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1380)
at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.updateTxBounds(Node.java:3641)
at javafx.scene.Node.getTransformedBounds(Node.java:3424)
at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1724)
at javafx.scene.Parent.updateCachedBounds(Parent.java:1588)
at javafx.scene.Parent.recomputeBounds(Parent.java:1527)
at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1380)
at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078)
at javafx.scene.Node.updateGeomBounds(Node.java:3577)
at javafx.scene.Node.getGeomBounds(Node.java:3530)
at javafx.scene.Node.getLocalBounds(Node.java:3478)
at javafx.scene.Node.impl_intersectsBounds(Node.java:5013)
at javafx.scene.layout.Region.impl_pickNodeLocal(Region.java:2931)
at javafx.scene.Node.impl_pickNode(Node.java:4912)
at javafx.scene.layout.Region.impl_pickNodeLocal(Region.java:2936)
at javafx.scene.Node.impl_pickNode(Node.java:4912)
at javafx.scene.Scene$MouseHandler.pickNode(Scene.java:3899)
at javafx.scene.Scene$MouseHandler.access$1600(Scene.java:3485)
at javafx.scene.Scene.pick(Scene.java:1942)
at javafx.scene.Scene.access$6700(Scene.java:159)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3799)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)

And then at the end the console just spams:

    java.lang.ArrayIndexOutOfBoundsException

indefinitely.

As I said, I really don't know why this is happening. The calculation works for the first few times, then this error occurs and freezes the application, requiring a complete restart.


问:
Trying to test onChange function of react component form
So I have a Signup component that renders a form with a simple text field and submit function. On entering text in the field the 'address' attribute should be updated. In my test I'm trying to assert that the onChange function is called but stubbing the function using jest. However when I try and simulate the change I get the error:

TypeError: result.simulate(...) is not a function

If I remove the .bind(this) is gets to the point where it's setting the state in the function but this is undefined.

Here is my code:

```<code>import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
  }

  render() {
    return (
      <div>
      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>
      </div>
    );
  }
}

export default Signup;
</code>```

And my test:

```<code>test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy"
    const onChange = jest.fn()
    const wrapper = shallow(<Signup onChange={onChange} />)
    const result = wrapper.find('#address')
    result.simulate('change', { target: { value: {value} } })('change');
    expect(onChange.called).toBe.true
  })
</code>```

答:
You try spy for onChange from props, but in your component no has any props.

Component's methods and component props are different things.

You need call this.props.onChange inside this.onChange.

```<code>import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
      // Call onChange callback
      this.props.onChange();
  }

  render() {
    return (
      <div>
      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>
      </div>
    );
  }
}
</code>```

And some fix in your test

```<code>test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy";
    const onChange = jest.fn();
    const wrapper = shallow(<Signup onChange={onChange} />);
    const result = wrapper.find('#address');
    result.simulate('change', {target: {value}});
    expect(onChange.called).toBe(true);
});
</code>```

Body:
So I have a Signup component that renders a form with a simple text field and submit function. On entering text in the field the 'address' attribute should be updated. In my test I'm trying to assert that the onChange function is called but stubbing the function using jest. However when I try and simulate the change I get the error:

TypeError: result.simulate(...) is not a function

If I remove the .bind(this) is gets to the point where it's setting the state in the function but this is undefined.

Here is my code:

import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
  }

  render() {
    return (

      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>

    );
  }
}

export default Signup;

And my test:

test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy"
    const onChange = jest.fn()
    const wrapper = shallow(<Signup onChange={onChange} />)
    const result = wrapper.find('#address')
    result.simulate('change', { target: { value: {value} } })('change');
    expect(onChange.called).toBe.true
  })

Body:
You try spy for onChange from props, but in your component no has any props.

Component's methods and component props are different things.

You need call this.props.onChange inside this.onChange.

import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
      // Call onChange callback
      this.props.onChange();
  }

  render() {
    return (
      <div>
      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>
      </div>
    );
  }
}

And some fix in your test

test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy";
    const onChange = jest.fn();
    const wrapper = shallow(<Signup onChange={onChange} />);
    const result = wrapper.find('#address');
    result.simulate('change', {target: {value}});
    expect(onChange.called).toBe(true);
});


问:
Safely Handling Concurrent Memcache save in AppEngine
I have in my application a lot of threads trying to put the same key in memcache. What I need to do is, once a thread managed to put that key then no other thread should put that key again.

I've come across some mechanisms provided by memCache, like putIFUnTouched which I was trying to use like this:

```<code>IdentifiableValue value = memCache.getIdentifiable("item_id");
mc.putIfUnTouched("item_id", null, "user_id");
</code>```

But it gives me this Exception: oldValue mustn't be null.

I also found CAS and I'm now confused which one of those I need to use in such situation.

Thanks in advance.

答:
I found the answer:</p>

```<code>memCache.put("key", "object", Expiration.byDeltaSeconds(10000), MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
</code>```

Body:
I have in my application a lot of threads trying to put the same key in memcache. What I need to do is, once a thread managed to put that key then no other thread should put that key again.

I've come across some mechanisms provided by memCache, like putIFUnTouched which I was trying to use like this:

IdentifiableValue value = memCache.getIdentifiable("item_id");
mc.putIfUnTouched("item_id", null, "user_id");

But it gives me this Exception: oldValue mustn't be null.

I also found CAS and I'm now confused which one of those I need to use in such situation.

Thanks in advance.

Body:
I found the answer:

memCache.put("key", "object", Expiration.byDeltaSeconds(10000), MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);


问:
Firefox Extension API - permissions.request may only be called from a user input handler?
I'm using the Firefox permissions API documented HERE

I'm having a problem with the request method, wherein all of my permissions requests result in:

Error: permissions.request may only be called from a user input handler

You can produce this in firefox by debugging any addon or extension and entering browser.permissions.request({origins: ["https://google.com/*"]}) into the console.

I find it hard to swallow that a permissions request must always have a user input event callback in the parent stack trace.  I'm using Vue.js, and my Permissions are due to user interaction, but my user interactions are decoupled from the events they trigger.

What counts as a user input handler?

Why does it work like this?

Is there a good work-around?

答:
Is there a good work-around"

I'd like to add onto Andrew's answer with some code examples.

As it turns out, promise chains destroy the browser's notion of what is and isn't triggered by a user input handler.  Take the code below, for example:

```<code>document.getElementById('foo').addEventListener('click', event => {
  browser.permissions.request({origins: ["https://google.com/*"]})
})
</code>```

This code works as expected.  I originally assumed that it was Vue.js's unique event handling framework that was eating my "browser events", such as when you do

.  This actually works just fine, as long as you put your permissions request in somefunc.

Now it gets fun.  If you replace your permissions request with a promise that resolves and then does a permissions request, VIOLA!

```<code>Promise.resolve('foobar').then(foobar => {
    browser.permissions.request({origins: ["https://google.com/*"]})
})
</code>```

Results in:

Error: permissions.request may only be called from a user input handler

Why does this happen?

I'm going to guess it has to do with stack traces.  Firefox can't detect that a permission came from a stack with a user input event at the root if the permissions request happens in a promise chain.

I consider this to be a pretty egregious design choice.  My app is large (>4K LoC) and to keep it simple I rely on promise chains to keep the spaghetti away.  This has crippled my ability to write clean code, and as a result, I've moved from asking for optional_permissions and then prompting the user for permissions only when needed to just being overly permissive at the time of installation.

GG, Firefox.

Body:
Is there a good work-around"

I'd like to add onto Andrew's answer with some code examples.

As it turns out, promise chains destroy the browser's notion of what is and isn't triggered by a user input handler.  Take the code below, for example:

document.getElementById('foo').addEventListener('click', event => {
  browser.permissions.request({origins: ["https://google.com/*"]})
})

This code works as expected.  I originally assumed that it was Vue.js's unique event handling framework that was eating my "browser events", such as when you do <div @click="somefunc"></div>.  This actually works just fine, as long as you put your permissions request in somefunc.

Now it gets fun.  If you replace your permissions request with a promise that resolves and then does a permissions request, VIOLA!

Promise.resolve('foobar').then(foobar => {
    browser.permissions.request({origins: ["https://google.com/*"]})
})

Results in:

Error: permissions.request may only be called from a user input handler

Why does this happen?

I'm going to guess it has to do with stack traces.  Firefox can't detect that a permission came from a stack with a user input event at the root if the permissions request happens in a promise chain.

I consider this to be a pretty egregious design choice.  My app is large (>4K LoC) and to keep it simple I rely on promise chains to keep the spaghetti away.  This has crippled my ability to write clean code, and as a result, I've moved from asking for optional_permissions and then prompting the user for permissions only when needed to just being overly permissive at the time of installation.

GG, Firefox.


问:
corrupted .docx document after downloading asp.net C#
I am trying to export a aspx page with image in it into a word document. When I try to achieve this with .doc format then broken image appears on the word doc. I tried downloading it in .docx format but after modifying code for .docx, it give me file corrupted error while opening. Below is my code:

```<code><body>
        <form id="form1" runat="server">
           <asp:Panel ID="tblReport" runat="server">
          <div class="boxed1a">
                    <img class="images4" src="Images/Penguins.jpg" width="640" height="45" />
                    <table class="tb3">
                    <tr>
                    <td>Leasehold & Functional Programs</td>

                    </tr>
                    <tr>
                    <td>N/A</td>

                    </tr>
                    <tr>
                    <td>Acquis Maint & Renov</td>

                    </tr>
                    </table>

                </div>
    </asp:Panel>
            <asp:Button runat="server" ID="btnExport" Text="Export" OnClick="btnExport_Click" />
        </form>
    </body>

    protected void btnExport_Click(object sender, EventArgs e)
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";

                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AppendHeader("content-disposition", "attachment;  filename=report.docx");

                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                tblReport.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
</code>```

Please let me know how can achieve this with .docx format.

答:
HTML Text writer is not a right way to create Word document in .net.

You could use the following code to create a simple word document and take reference from the link https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.aspx.

The above link will help you to create an efficient word document in .net.

```<code> Microsoft.Office.Interop.Word._Application objWord;
 object oMissing = System.Reflection.Missing.Value;
 object oEndOfDoc = "\\endofdoc";
 FolderBrowserDialog ff = new FolderBrowserDialog();
 ff.ShowDialog();
 string filename = "Sample";
 Microsoft.Office.Interop.Word._Document objDoc;
 objWord = new Microsoft.Office.Interop.Word.Application();
 objWord.Visible = true;
 objDoc = objWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
 Microsoft.Office.Interop.Word.Range wrdRng = objDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
 wrdRng.Text = "Simple Word";
 this.Close();
 string fp = ff.SelectedPath + "\\" + filename + ".docx";
 objDoc.SaveAs2(fp);
</code>```

Hope this helps!

Body:
I am trying to export a aspx page with image in it into a word document. When I try to achieve this with .doc format then broken image appears on the word doc. I tried downloading it in .docx format but after modifying code for .docx, it give me file corrupted error while opening. Below is my code:

        <form id="form1" runat="server">
           <asp:Panel ID="tblReport" runat="server">

                    Leasehold & Functional Programs

                    N/A

                    Acquis Maint & Renov

    </asp:Panel>
            <asp:Button runat="server" ID="btnExport" Text="Export" OnClick="btnExport_Click" />
        </form>

    protected void btnExport_Click(object sender, EventArgs e)
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";

                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AppendHeader("content-disposition", "attachment;  filename=report.docx");

                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                tblReport.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }

Please let me know how can achieve this with .docx format.

Body:
HTML Text writer is not a right way to create Word document in .net.

You could use the following code to create a simple word document and take reference from the link https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.aspx.

The above link will help you to create an efficient word document in .net.

 Microsoft.Office.Interop.Word._Application objWord;
 object oMissing = System.Reflection.Missing.Value;
 object oEndOfDoc = "\\endofdoc";
 FolderBrowserDialog ff = new FolderBrowserDialog();
 ff.ShowDialog();
 string filename = "Sample";
 Microsoft.Office.Interop.Word._Document objDoc;
 objWord = new Microsoft.Office.Interop.Word.Application();
 objWord.Visible = true;
 objDoc = objWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
 Microsoft.Office.Interop.Word.Range wrdRng = objDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
 wrdRng.Text = "Simple Word";
 this.Close();
 string fp = ff.SelectedPath + "\\" + filename + ".docx";
 objDoc.SaveAs2(fp);

Hope this helps!


问:
How to design an ASP.NET MVC site for caching with Velocity?
I'm coming from the LAMP world, where the "cache everything" mentality is prevalent.  Everything is put in memcache.

I'm starting a new project with ASP.NET MVC and SQL Server.  I'll probably go with LINQ to SQL or maybe Entity Framework.  Are there design decisions I need to make now for caching, or is it easy enough to start using Velocity if that becomes necessary?  Just to be clear, I'm talking about Microsoft's Velocity cache and not the Apache Velocity template engine.

I'm hoping that I can ignore caching for the moment, because learning C#, ASP.NET MVC, LINQ, IIS, SQL Server, and becoming proficient in VS is keeping my plate full.

答:
@dswatic: Many thanks.  It looks like I can add caching later on with minimal pain.  Here's an important warning from that site though:

"If you use the Object Relational Designer to generate your LINQ to SQL classes then your LINQ to SQL classes will not be serializable. To work around this problem, I built my LINQ to SQL classes by hand."

Only serializable objects can be cached with Velocity.

Thanks again.

OwnerDisplayName: Bob

LastEditorDisplayName: Ben Alpert


问:
Why `minimum (1, 2)` returns 2 in Haskell?
Why minimum (1, 2) is 2 in Haskell?

My test result in GHCi,

```<code>GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> minimum (1, 2)
2
</code>```

Shouldn't it return 1?

答:
The reason for this behaviour is twofold:

Since the FTP, the functions like minimum or length (these are catamorphisms, i.e. functions which simmer down a container structure to a single value) don't just operate on lists anymore, but on general Foldable instances. That's very useful, for instance you can directly calculate the minimum of an array, map or trie without first having to convert it to a list. (Prior to the FTP, your expression would have just been a type error, because the argument is not a list but a tuple.)

Tuples are functors, and specifically, they are functors in the second argument. This allows doing stuff like

```<code>Prelude> fmap (+1) <$> [("Bla",2), ("blub",3)]
[("Bla",3),("blub",4)]
</code>```

That it's the second argument arises from the fact that (a,b) is actually syntactic sugar for ((,) a) b, i.e. we're dealing with the ((,)a) functor here. This is the only possible way you can make a Haskell tuple functor instance!
IMHO, having that instance at all isn't really a good feature though†, because tuples are supposed to be in a sense symmetric between there elements. Well, Haskell tuples aren't symmetric, they are “containers containing one polymorphic element”, namely the second one.

That wouldn't too bad by itself, but tuples also have a Foldable instance: once you decide that a tuple is a container for the second element specifically, it's natural to also want to run catamorphisms on it. They're not very exciting catamorphisms, working only ever on one element, and in particular it's really confusing that even if the first element has the same type, the catamorphism just ignores it. But oh well, here we are.

†The proper way to write the above is IMO second (+1) <$> [("Bla",2), ("blub",3)], using second from Control.Arrow, which is equivalent to fmap on tuples but avoids the confusion between the two elements. (Also, it's more general, but not in a way that would make a difference for most applications: it can be used with general arrows, not just with functions.)

Body:
Why minimum (1, 2) is 2 in Haskell?

My test result in GHCi,

GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> minimum (1, 2)
2

Shouldn't it return 1?

Body:
The reason for this behaviour is twofold:

Since the FTP, the functions like minimum or length (these are catamorphisms, i.e. functions which simmer down a container structure to a single value) don't just operate on lists anymore, but on general Foldable instances. That's very useful, for instance you can directly calculate the minimum of an array, map or trie without first having to convert it to a list. (Prior to the FTP, your expression would have just been a type error, because the argument is not a list but a tuple.)

Tuples are functors, and specifically, they are functors in the second argument. This allows doing stuff like

Prelude> fmap (+1) <$> [("Bla",2), ("blub",3)]
[("Bla",3),("blub",4)]

That it's the second argument arises from the fact that (a,b) is actually syntactic sugar for ((,) a) b, i.e. we're dealing with the ((,)a) functor here. This is the only possible way you can make a Haskell tuple functor instance!
IMHO, having that instance at all isn't really a good feature though†, because tuples are supposed to be in a sense symmetric between there elements. Well, Haskell tuples aren't symmetric, they are “containers containing one polymorphic element”, namely the second one.

That wouldn't too bad by itself, but tuples also have a Foldable instance: once you decide that a tuple is a container for the second element specifically, it's natural to also want to run catamorphisms on it. They're not very exciting catamorphisms, working only ever on one element, and in particular it's really confusing that even if the first element has the same type, the catamorphism just ignores it. But oh well, here we are.

†The proper way to write the above is IMO second (+1) <$> [("Bla",2), ("blub",3)], using second from Control.Arrow, which is equivalent to fmap on tuples but avoids the confusion between the two elements. (Also, it's more general, but not in a way that would make a difference for most applications: it can be used with general arrows, not just with functions.)


问:
How different is NodeJs Architecture?
Have some questions regarding NodeJs Architecture:

It says although NodeJs is single threaded, internally it uses libuv library's thread pool? Is it right?

All non-blocking requests handled by main thread and all blocking requests handled by libuv thread pool? While some says there is nothing like main thread. Right or misconception?

If yes, then what happen if thread pool size is 4 and blocking requests are
Request no 5 have to be wait until thread is available? Is it right?

if point 3 is the case, then how NodeJs is different from Java if blocking requests count exceeds thread pool size?

答:
1.
In general, both libuv and v8 are allowed to use (and in fact use) threads.

As a rule of thumb, note that a single threaded JavaScript runtime environment doesn't mean that the underlying libraries cannot use threads.

2.
You can refer to the documentation of libuv to know what will be dispatched on threads.

I cite it:

File system operations

DNS functions

User specified code via uv_queue_work()

3.
It is said that you can queue work on the thread pool.

So, yes, if you queue more work that what you can schedule, requests are going to wait their turn to run.

4.
A thread pool is a concept that abstracts away from the language.

At the end of the day, libuv and thus node are well targeted for I/O bound applications where you do a lot of networking and the API clearly states it.

Title: How different is NodeJs Architecture?


问:
Haskell: Combinations (list of list)
I have a list of subjects and weekdays, on which the subject is taught.

```<code>subjectDays = [("maths", ["mon", "tue"]),
               ("science", ["mon", "wed"])]
</code>```

Now I would like to generate a list of combinations.
The result should look like as follows.

```<code>combinations = [[("maths", "mon"), ("science", "mon")],
                [("maths", "mon"), ("science", "wed")]
                -- etc.
               ]
</code>```

Could anyone please help me to write a function in Haskell to produce the above result?

Thank you very much in advance.

答:
From the comment below, I now realize that you want another output than the one I initially understood.

Essentially, you want each sublist to contain each subject (exactly once), paired with one of its days. If we still take combinations as defined below (the "wrong" output) we realize that we want to take the "cartesian product" of all the lists inside combinations. This cartesian product can be obtained using Control.Monad.sequence.

```<code>wantedCombinations = sequence combinations
</code>```

Here's a hint.

First, write a function to expand a single pair of yours into a list.

```<code>combs :: (a,[b]) -> [(a,b)]
combs (subject, days) = ...
</code>```

This could be solved using a list comprehension, for instance. Or map.

Then, we can apply combs to each pair in the list

```<code>combinations = map combs subjectDays
</code>```

Title: Haskell: Combinations (list of list)

Body:
I have a list of subjects and weekdays, on which the subject is taught.

subjectDays = [("maths", ["mon", "tue"]),
               ("science", ["mon", "wed"])]

Now I would like to generate a list of combinations.
The result should look like as follows.

combinations = [[("maths", "mon"), ("science", "mon")],
                [("maths", "mon"), ("science", "wed")]
                -- etc.
               ]

Could anyone please help me to write a function in Haskell to produce the above result?

Thank you very much in advance.

Body:
From the comment below, I now realize that you want another output than the one I initially understood.

Essentially, you want each sublist to contain each subject (exactly once), paired with one of its days. If we still take combinations as defined below (the "wrong" output) we realize that we want to take the "cartesian product" of all the lists inside combinations. This cartesian product can be obtained using Control.Monad.sequence.

wantedCombinations = sequence combinations

Here's a hint.

First, write a function to expand a single pair of yours into a list.

combs :: (a,[b]) -> [(a,b)]
combs (subject, days) = ...

This could be solved using a list comprehension, for instance. Or map.

Then, we can apply combs to each pair in the list

combinations = map combs subjectDays


问:
How to consume rest service with basic auth from angular 4
Hi present i am developing angular 4 application. In this we have to consume rest service with basic authorization. so please help how to consume rest service with basic auth.

thanks in advance.

答:
Presently i am using the following style

```<code>let headers = new Headers();
headers.append('Authorization', 'Basic bWFoZXNoazptYWhlc2g=');
let opts = new RequestOptions();
opts.headers = headers;

this.http.get('http://localhost:8080/job/Library%20Manager/api/json?USER=a150fadfe99325644f45a2768c2d4d40&pretty=true',opts).subscribe(data => {

  console.log("sample for testing::::"+data);
});
</code>```

i am getting authentication error but getting success response when i tried from all types of rest clients like postman, onsomnia.

i tried for different rest services also. getting same type problem for all rest services i have tried.

Body:
Presently i am using the following style

let headers = new Headers();
headers.append('Authorization', 'Basic bWFoZXNoazptYWhlc2g=');
let opts = new RequestOptions();
opts.headers = headers;

this.http.get('http://localhost:8080/job/Library%20Manager/api/json?USER=a150fadfe99325644f45a2768c2d4d40&pretty=true',opts).subscribe(data => {

  console.log("sample for testing::::"+data);
});

i am getting authentication error but getting success response when i tried from all types of rest clients like postman, onsomnia.

i tried for different rest services also. getting same type problem for all rest services i have tried.


问:
Display Grid does not work in Polymer correctly
I'm trying to make an responsive Grid which changes the order of elements when the container gets resized.

If the container gets bigger, then an element from the second row only gets in the row abouve if there is enough space. If there is not enough space the space between the elements gets bigger until the element from the second row can fit inside the first row.

Here is a working example how it's realized without Polymer

But the Problem is if I embed this inside a custom Polymer element. The space between two elements does not change. Is there any solution to this Problem?

Here is my Polymer-Element:

```<code><link rel="import" href="../../bower_components/polymer/polymer-element.html">

<dom-module id="test-element">
    <template>
        <style>
            .container {
                min-height: 400px;
                display: grid;
                grid-template-columns: repeat(auto-fill, 60px);
                justify-content: space-around;
                align-items: center;
                align-content: start;
            }

            .item {
                flex: 0 0 auto;
                margin: 5px;
                width: 50px;
                height: 50px;
                background-color: green;
            }
        </style>
        <div class="container">
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
            <div class="item"></div>
        </div>
    </template>
    <script>
        class TestElement extends Polymer.Element {
            static get is() {
                return 'test-element';
            }

        }
        window.customElements.define(TestElement.is, TestElement);
    </script>
</dom-module>
</code>```

答:
Perhaps your issue is that you haven't set a display style on the host element:

Custom elements are display: inline by default, so setting their width or height will have no effect. This often comes as a surprise to developers and may cause issues related to laying out the page. Unless you prefer an inline display, you should always set a default display value.

Source: Custom Element Best Practices, Web Fundamentals

I'm using Polymer 3 but it shouldn't really make any difference:

```<code>import {Element as PolymerElement} from './node_modules/@polymer/polymer/polymer-element.js';

class TestElement extends PolymerElement {
  static get template() {
    return `
      <style>
        :host {
          display: block;
        }
        .container {
          min-height: 400px;
          display: grid;
          grid-template-columns: repeat(auto-fill, 60px);
          justify-content: space-around;
          align-items: center;
          align-content: start;
        }
        .item {
          flex: 0 0 auto;
          margin: 5px;
          width: 50px;
          height: 50px;
          background-color: green;
        }
      </style>
      <div class="container">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
      </div>
    `;
  }
}

customElements.define('test-element', TestElement);
</code>```

Then "run it":

```<code><html>
  <head>
    <script type="module" src="./test-element.js"></script>
  </head>
  <body>
    <test-element id="test"></test-element>
  </body>
</html>
</code>```

This is what I'm seeing:

Body:
I'm trying to make an responsive Grid which changes the order of elements when the container gets resized.

If the container gets bigger, then an element from the second row only gets in the row abouve if there is enough space. If there is not enough space the space between the elements gets bigger until the element from the second row can fit inside the first row.

Here is a working example how it's realized without Polymer

But the Problem is if I embed this inside a custom Polymer element. The space between two elements does not change. Is there any solution to this Problem?

Here is my Polymer-Element:

<link rel="import" href="../../bower_components/polymer/polymer-element.html">

<dom-module id="test-element">
    <template>

    </template>

</dom-module>

Body:
Perhaps your issue is that you haven't set a display style on the host element:

Custom elements are display: inline by default, so setting their width or height will have no effect. This often comes as a surprise to developers and may cause issues related to laying out the page. Unless you prefer an inline display, you should always set a default display value.

Source: Custom Element Best Practices, Web Fundamentals

I'm using Polymer 3 but it shouldn't really make any difference:

import {Element as PolymerElement} from './node_modules/@polymer/polymer/polymer-element.js';

class TestElement extends PolymerElement {
  static get template() {
    return `
      <style>
        :host {
          display: block;
        }
        .container {
          min-height: 400px;
          display: grid;
          grid-template-columns: repeat(auto-fill, 60px);
          justify-content: space-around;
          align-items: center;
          align-content: start;
        }
        .item {
          flex: 0 0 auto;
          margin: 5px;
          width: 50px;
          height: 50px;
          background-color: green;
        }
      </style>
      <div class="container">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
      </div>
    `;
  }
}

customElements.define('test-element', TestElement);

Then "run it":

<html>
  <head>
    <script type="module" src="./test-element.js"></script>
  </head>
  <body>
    <test-element id="test"></test-element>
  </body>
</html>

This is what I'm seeing:


问:
Encapsulation concept
I have problem with concept and implementation of encapsulation.

Can someone explain it to me?

答:
link text

I always explain it to people is think of yourself as an object. Other people can see your height, they can see if your smiling, but your inner thoughts, maybe the reason while your smiling, only you know.

Title: Encapsulation concept


问:
Intersection and union of ArrayLists in Java
Are there any methods to do so? I was looking but couldn't find any.

Another question: I need these methods so I can filter files.
Some are AND filters and some are OR filters (like in set theory), so I need to filter according to all files and the unite/intersects ArrayLists that holds those files.

Should I use a different data structure to hold the files? Is there anything else that would offer a better runtime?

答:
You can use commons-collections4 CollectionUtils</p>

```<code>Collection<Integer> collection1 = Arrays.asList(1, 2, 4, 5, 7, 8);
Collection<Integer> collection2 = Arrays.asList(2, 3, 4, 6, 8);

Collection<Integer> intersection = CollectionUtils.intersection(collection1, collection2);
System.out.println(intersection); // [2, 4, 8]

Collection<Integer> union = CollectionUtils.union(collection1, collection2);
System.out.println(union); // [1, 2, 3, 4, 5, 6, 7, 8]

Collection<Integer> subtract = CollectionUtils.subtract(collection1, collection2);
System.out.println(subtract); // [1, 5, 7]
</code>```

Body:
You can use commons-collections4 CollectionUtils

Collection<Integer> collection1 = Arrays.asList(1, 2, 4, 5, 7, 8);
Collection<Integer> collection2 = Arrays.asList(2, 3, 4, 6, 8);

Collection<Integer> intersection = CollectionUtils.intersection(collection1, collection2);
System.out.println(intersection); // [2, 4, 8]

Collection<Integer> union = CollectionUtils.union(collection1, collection2);
System.out.println(union); // [1, 2, 3, 4, 5, 6, 7, 8]

Collection<Integer> subtract = CollectionUtils.subtract(collection1, collection2);
System.out.println(subtract); // [1, 5, 7]