问:
Passing Integer among activity in Android
I am creating a quiz app. the code pasted down is the second activity of the app. But it stated the int point = 0, and the finalpoints is not stated because it depends on the answers in the quiz.
However do i pass whatever answer in this activity is passed to the next one and the next. </p>

<p>here is the code for the activity2: </p>

```<code> package com.example.android.questionme;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {
    Intent intent = getIntent();

    int point = 0;
    int finalpoints;

    RadioButton option1forQ1;
    RadioButton option2forQ1;
    RadioButton option1forQ2;
    RadioButton option2forQ2;
    RadioButton option3forQ2;
    RadioButton option4forQ2;
    RadioButton option1forQ3;
    RadioButton option2forQ3;
    RadioButton option3forQ3;
    RadioButton option1forQ4;
    RadioButton option2forQ4;
    RadioButton option3forQ4;
    RadioButton option4forQ4;
    RadioButton option1forQ5;
    RadioButton option2forQ5;
    RadioButton option3forQ5;
    RadioButton option4forQ5;
    CheckBox option1forQ6;
    CheckBox option2forQ6;
    CheckBox option3forQ6;
    CheckBox option4forQ6;
    RadioButton option1forQ7;
    RadioButton option2forQ7;
    RadioButton option3forQ7;
    RadioButton option4forQ7;
    RadioButton option1forQ8;
    RadioButton option2forQ8;
    RadioButton option3forQ8;

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

        option1forQ1 = (RadioButton) findViewById(R.id.right_answer_for_Q1);
        option2forQ1 = (RadioButton) findViewById(R.id.wrong_answer_for_Q1);
        option1forQ2 = (RadioButton) findViewById(R.id.question_two_right_answer);
        option2forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer0);
        option3forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer1);
        option4forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer2);
        option1forQ3 = (RadioButton) findViewById(R.id.question_three_right_answer);
        option2forQ3 = (RadioButton) findViewById(R.id.question_three_wrong_answer0);
        option3forQ3 = (RadioButton) findViewById(R.id.question_three_wrong_answer1);
        option1forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer0);
        option2forQ4 = (RadioButton) findViewById(R.id.question_four_right_answer);
        option3forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer1);
        option4forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer2);
        option1forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer0);
        option2forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer1);
        option3forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer2);
        option4forQ5 = (RadioButton) findViewById(R.id.question_five_right_answer);
        option1forQ6 = (CheckBox) findViewById(R.id.question_six_right_answer);
        option2forQ6 = (CheckBox) findViewById(R.id.question_six_wrong_answer);
        option3forQ6 = (CheckBox) findViewById(R.id.question_six_wrong_answer1);
        option4forQ6 = (CheckBox) findViewById(R.id.question_six_right_answer1);
        option1forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer);
        option2forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer1);
        option3forQ7 = (RadioButton) findViewById(R.id.question_seven_right_answer);
        option4forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer2);
        option1forQ8 = (RadioButton) findViewById(R.id.question_eight_wrong_answer);
        option2forQ8 = (RadioButton) findViewById(R.id.question_eight_right_answer);
        option3forQ8 = (RadioButton) findViewById(R.id.question_eight_wrong_answer2);
    }
    public void onYesRadioButtonClicked (View view){
        Intent intent = new Intent(this, Main3Activity.class);
        boolean option1forQ1IsChecked = option1forQ1.isChecked();
        boolean option2forQ1IsChecked = option2forQ1.isChecked();
        if (option1forQ1IsChecked) {
            point *= 2;
            startActivity(intent);
            Toast.makeText(this, "Good Start"+ "2 Points", Toast.LENGTH_SHORT).show();
        }
        else
        if (option2forQ1IsChecked) {
            point -= 1;
        }
    }
    public void onNoRadioButtonClicked (View view){
        boolean option2forQ1IsChecked = option2forQ1.isChecked();
        if (option2forQ1IsChecked){
        Toast.makeText(this, "Wrong Answer, You can Google about Google on Google"
                , Toast.LENGTH_SHORT).show();
        }
}
}
</code>```

答: Before launching your intent, pass extras. This question is a duplicate and there already exists a detailed solution: How do I pass data between Activities in Android application?</p>

Body:
I am creating a quiz app. the code pasted down is the second activity of the app. But it stated the int point = 0, and the finalpoints is not stated because it depends on the answers in the quiz.
However do i pass whatever answer in this activity is passed to the next one and the next.

here is the code for the activity2:

 package com.example.android.questionme;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {
    Intent intent = getIntent();

    int point = 0;
    int finalpoints;

    RadioButton option1forQ1;
    RadioButton option2forQ1;
    RadioButton option1forQ2;
    RadioButton option2forQ2;
    RadioButton option3forQ2;
    RadioButton option4forQ2;
    RadioButton option1forQ3;
    RadioButton option2forQ3;
    RadioButton option3forQ3;
    RadioButton option1forQ4;
    RadioButton option2forQ4;
    RadioButton option3forQ4;
    RadioButton option4forQ4;
    RadioButton option1forQ5;
    RadioButton option2forQ5;
    RadioButton option3forQ5;
    RadioButton option4forQ5;
    CheckBox option1forQ6;
    CheckBox option2forQ6;
    CheckBox option3forQ6;
    CheckBox option4forQ6;
    RadioButton option1forQ7;
    RadioButton option2forQ7;
    RadioButton option3forQ7;
    RadioButton option4forQ7;
    RadioButton option1forQ8;
    RadioButton option2forQ8;
    RadioButton option3forQ8;

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

        option1forQ1 = (RadioButton) findViewById(R.id.right_answer_for_Q1);
        option2forQ1 = (RadioButton) findViewById(R.id.wrong_answer_for_Q1);
        option1forQ2 = (RadioButton) findViewById(R.id.question_two_right_answer);
        option2forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer0);
        option3forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer1);
        option4forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer2);
        option1forQ3 = (RadioButton) findViewById(R.id.question_three_right_answer);
        option2forQ3 = (RadioButton) findViewById(R.id.question_three_wrong_answer0);
        option3forQ3 = (RadioButton) findViewById(R.id.question_three_wrong_answer1);
        option1forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer0);
        option2forQ4 = (RadioButton) findViewById(R.id.question_four_right_answer);
        option3forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer1);
        option4forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer2);
        option1forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer0);
        option2forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer1);
        option3forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer2);
        option4forQ5 = (RadioButton) findViewById(R.id.question_five_right_answer);
        option1forQ6 = (CheckBox) findViewById(R.id.question_six_right_answer);
        option2forQ6 = (CheckBox) findViewById(R.id.question_six_wrong_answer);
        option3forQ6 = (CheckBox) findViewById(R.id.question_six_wrong_answer1);
        option4forQ6 = (CheckBox) findViewById(R.id.question_six_right_answer1);
        option1forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer);
        option2forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer1);
        option3forQ7 = (RadioButton) findViewById(R.id.question_seven_right_answer);
        option4forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer2);
        option1forQ8 = (RadioButton) findViewById(R.id.question_eight_wrong_answer);
        option2forQ8 = (RadioButton) findViewById(R.id.question_eight_right_answer);
        option3forQ8 = (RadioButton) findViewById(R.id.question_eight_wrong_answer2);
    }
    public void onYesRadioButtonClicked (View view){
        Intent intent = new Intent(this, Main3Activity.class);
        boolean option1forQ1IsChecked = option1forQ1.isChecked();
        boolean option2forQ1IsChecked = option2forQ1.isChecked();
        if (option1forQ1IsChecked) {
            point *= 2;
            startActivity(intent);
            Toast.makeText(this, "Good Start"+ "2 Points", Toast.LENGTH_SHORT).show();
        }
        else
        if (option2forQ1IsChecked) {
            point -= 1;
        }
    }
    public void onNoRadioButtonClicked (View view){
        boolean option2forQ1IsChecked = option2forQ1.isChecked();
        if (option2forQ1IsChecked){
        Toast.makeText(this, "Wrong Answer, You can Google about Google on Google"
                , Toast.LENGTH_SHORT).show();
        }
}
}


来源: stackexchange

问:
How can I autoflush a Perl 6 filehande?
There are a couple of answers for Perl 6 back in its Parrot days and they don't seem to work currently:

This is Rakudo version 2017.04.3 built on MoarVM version 2017.04-53-g66c6dda
  implementing Perl 6.c.

The answer to Does perl6 enable “autoflush” by default? says it's enabled by default (but that was 2011).

Here's a program I was playing with:

```<code>$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";
</code>```

And its output, which is an unfortunate order:

```<code>2. This is standard out
1. This is an error
</code>```

So maybe I need to turn it on. There's How could I disable autoflush? which mentions an autoflush method:

```<code>$*ERR.autoflush = True;
$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";
</code>```

But that doesn't work:

No such method 'autoflush' for invocant of type 'IO::Handle'

I guess I could fake this myself by making my IO class that flushes after every output. For what it's worth, it's the lack of this feature that prevented me from using Perl 6 for a particular task today.

As a secondary question, why doesn't Perl 6 have this now, especially when it looks like it used to have it? How would you persaude a Perl 5 person this isn't an issue?

答:
Rakudo doesn't support autoflush (yet). There's a note in 5to6-perlvar under the $OUTPUT_AUTOFLUSH entry.

raiph posted a comment elsewhere with a #perl6 IRC log search showing that people keep recommending autoflush and some other people keep saying it's not implemented. Since it's not a documented method (although flush is), I suppose we'll have to live without for a bit.

ContentLicense: CC BY-SA 3.0

Title: How can I autoflush a Perl 6 filehande?

Body:
There are a couple of answers for Perl 6 back in its Parrot days and they don't seem to work currently:

This is Rakudo version 2017.04.3 built on MoarVM version 2017.04-53-g66c6dda
  implementing Perl 6.c.

The answer to Does perl6 enable “autoflush” by default? says it's enabled by default (but that was 2011).

Here's a program I was playing with:

$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";

And its output, which is an unfortunate order:

2. This is standard out
1. This is an error

So maybe I need to turn it on. There's How could I disable autoflush? which mentions an autoflush method:

$*ERR.autoflush = True;
$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";

But that doesn't work:

No such method 'autoflush' for invocant of type 'IO::Handle'

I guess I could fake this myself by making my IO class that flushes after every output. For what it's worth, it's the lack of this feature that prevented me from using Perl 6 for a particular task today.

As a secondary question, why doesn't Perl 6 have this now, especially when it looks like it used to have it? How would you persaude a Perl 5 person this isn't an issue?


问:
Why is 08 not a valid integer literal in Java?
Why is 08 considered an out of range int but 07 and below are not?

答:
In Java, if you are defining an int with a leading '0' denotes that you are defining a number in Octal.

int a = 08 is giving out of range error because there is no any number '8' in Octal. Octal provides 0-7 numbers only.

If you define a = 07 then it's not giving out of range error because the numbers '0' and '7' are within the Octal's range.


问:
JS not working. What is wrong?
I have this code:

window.store = {
        localStoreSupport: function() {
            try {
                return 'localStorage' in window && window['localStorage'] !== null;
            } catch (e) {
                return false;
            }
        },
        set: function(name,value,days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }
            else {
                var expires = "";
            }
            if( this.localStoreSupport() ) {
                localStorage.setItem(name, value);
            }
            else {
                document.cookie = name+"="+value+expires+"; path=/";
            }
        },
        get: function(name) {
            if( this.localStoreSupport() ) {
                var ret = localStorage.getItem(name);
                //console.log(typeof ret);
                switch (ret) {
                  case 'true':
                      return true;
                  case 'false':
                      return false;
                  default:
                      return ret;
                }
            }
            else {
                var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                for(var i=0;i < ca.length;i++) {
                    var c = ca[i];
                    while (c.charAt(0)==' ') c = c.substring(1,c.length);
                    if (c.indexOf(nameEQ) == 0) {
                        ret = c.substring(nameEQ.length,c.length);
                        switch (ret) {
                          case 'true':
                              return true;
                          case 'false':
                              return false;
                          default:
                              return ret;
                        }
                    }
                }
                return null;
            }
        },
        del: function(name) {
            if( this.localStoreSupport() ) {
                localStorage.removeItem(name);
            }
            else {
                this.set(name,"",-1);
            }
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    <input id="a" placeholder="Var Name" /><br>
    <input id="b" placeholder="Var Value" /><br>
    <button onclick="n()">Save this var</button><br>
    <br><br>
    <input id="s" placeholder="Var to show" /><br>
    <button onclick="m()">Get the var's</button>
    <br><br>
    <input id="v" placeholder="var's to delete" /><br>
    <button onclick="del()">Delete var's</button>
    </body>
    </html></code>```

Why isn't it working? It isn't saving the inputs, it keeps returning "null".
Could anyone give me a tip on what i did wrong here? I can't figure it out. It worked before, i did some minor changes but i don't know what i did anymore. Thanks in advance!

答:
What i found out after some testing is that in get: function(name) in the if( this.localStoreSupport() ) block the variable ret should be like this:

```<code>var ret = localStorage.getItem(name.value);
</code>```

and then everything should work like its supposed to.

Click-> jsfiddle

Title: JS not working. What is wrong?

Body:
I have this code:

window.store = {
        localStoreSupport: function() {
            try {
                return 'localStorage' in window && window['localStorage'] !== null;
            } catch (e) {
                return false;
            }
        },
        set: function(name,value,days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }
            else {
                var expires = "";
            }
            if( this.localStoreSupport() ) {
                localStorage.setItem(name, value);
            }
            else {
                document.cookie = name+"="+value+expires+"; path=/";
            }
        },
        get: function(name) {
            if( this.localStoreSupport() ) {
                var ret = localStorage.getItem(name);
                //console.log(typeof ret);
                switch (ret) {
                  case 'true':
                      return true;
                  case 'false':
                      return false;
                  default:
                      return ret;
                }
            }
            else {
                var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                for(var i=0;i < ca.length;i++) {
                    var c = ca[i];
                    while (c.charAt(0)==' ') c = c.substring(1,c.length);
                    if (c.indexOf(nameEQ) == 0) {
                        ret = c.substring(nameEQ.length,c.length);
                        switch (ret) {
                          case 'true':
                              return true;
                          case 'false':
                              return false;
                          default:
                              return ret;
                        }
                    }
                }
                return null;
            }
        },
        del: function(name) {
            if( this.localStoreSupport() ) {
                localStorage.removeItem(name);
            }
            else {
                this.set(name,"",-1);
            }
        }
    }

<!DOCTYPE html>

    <title></title>

    <input id="a" placeholder="Var Name" />

    <input id="b" placeholder="Var Value" />

    <button onclick="n()">Save this var</button>

    <input id="s" placeholder="Var to show" />

    <button onclick="m()">Get the var's</button>

    <input id="v" placeholder="var's to delete" />

    <button onclick="del()">Delete var's</button>

Why isn't it working? It isn't saving the inputs, it keeps returning "null".
Could anyone give me a tip on what i did wrong here? I can't figure it out. It worked before, i did some minor changes but i don't know what i did anymore. Thanks in advance!

Body:
What i found out after some testing is that in get: function(name) in the if( this.localStoreSupport() ) block the variable ret should be like this:

var ret = localStorage.getItem(name.value);

and then everything should work like its supposed to.

Click-> jsfiddle


问:
How drag and drop of files is done?
as in winamp or vlc player, how to do a file drag and drop? i mean i want to know what sort of coding goes into application? i want to know for c++</p>

答:
edit after I posted this, the question was edited to qualify as C++; I'm going to leave this answer here for reference only.

"what sort off coding goes into application":

That depends hugely on the platform and language. For example, here are examples for Windows via C#/.NET or VB/.NET. For C++, Delphi, etc - the tricks will be different.

OwnerDisplayName: kasperasky

ContentLicense: CC BY-SA 2.5

Title: How drag and drop of files is done?

LastEditorDisplayName: PhiLho

OwnerDisplayName: Marc Gravell

LastEditorDisplayName: Marc Gravell


问:
problem with conditional switch
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

```<code><?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>
</code>```

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

答:
It would almost seem that this is a bolean conversion issue.

The first case statement will evaluate to anything other than 0, so that will not hit.

But the second case statement will evaluate to false, which should be 0 which is equal to what you have set $totaltime to.

Title: problem with conditional switch

Body:
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

<?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)


问:
Problems loading mnist in tensorflow on Mac OS
Please help, I encountered the following errors while attempting to download the MNIST dataset with Tensorflow.

```<code>Using TensorFlow backend.
Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1400, in connect
    server_hostname=server_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 401, in wrap_socket
    _context=self, _session=session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 808, in __init__
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1061, in do_handshake
    self._sslobj.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/utils/data_utils.py", line 207, in get_file
    urlretrieve(origin, fpath, dl_progress)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 248, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)>
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "/Users/lorin/Applications/miniconda3/envs/udemy/mnist_keras.py", line 13, in <module>
    (X_train, y_train), (X_test, y_test) = mnist.load_data('/lib/python3.6/site-packages/keras/datasetsmnist.py')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/datasets/mnist.py", line 15, in load_data
    path = get_file(path, origin='https://s3.amazonaws.com/img-datasets/mnist.npz')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/utils/data_utils.py", line 209, in get_file
    raise Exception(error_msg.format(origin, e.errno, e.reason))
Exception: URL fetch failure on https://s3.amazonaws.com/img-datasets/mnist.npz: None -- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
</code>```

Process finished with exit code enter code here

答:
I suggest you install TensorFlow in a separate virtualenv.

Follow the following steps here: Installing TensorFlow with virtualenv

And always remember to activate the virtualenv environment each time you use TensorFlow in a new shell by running:

   $ source ~/<target_directory>/bin/activate

Body:
Please help, I encountered the following errors while attempting to download the MNIST dataset with Tensorflow.

Using TensorFlow backend.
Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1400, in connect
    server_hostname=server_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 401, in wrap_socket
    _context=self, _session=session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 808, in __init__
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1061, in do_handshake
    self._sslobj.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/utils/data_utils.py", line 207, in get_file
    urlretrieve(origin, fpath, dl_progress)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 248, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/lorin/Applications/miniconda3/envs/udemy/mnist_keras.py", line 13, in <module>
    (X_train, y_train), (X_test, y_test) = mnist.load_data('/lib/python3.6/site-packages/keras/datasetsmnist.py')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/datasets/mnist.py", line 15, in load_data
    path = get_file(path, origin='https://s3.amazonaws.com/img-datasets/mnist.npz')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/utils/data_utils.py", line 209, in get_file
    raise Exception(error_msg.format(origin, e.errno, e.reason))
Exception: URL fetch failure on https://s3.amazonaws.com/img-datasets/mnist.npz: None -- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Process finished with exit code enter code here


问:
Import all modules from a directory at once [NODE]
```<code>MyApp
├── main.js
└── modules
    ├── a.js
    ├── b.js
    ├── c.js
    ├── d.js
    ├── e.js
</code>```

In my NodeJS app, how can I import all my custom modules (a,b,c,d,e) in my main.js file at once?

I have long list of modules and I dont want to import them all separately.

答:
You can  dynamically import each module.

const fs = require('fs');

fs
  .readdirSync(`${__dirname}/modules`)
  .filter(file => (file.slice(-3) === '.js'))
  .forEach((file) => {
    require(`./modules/${file}`)
  });```

Body:
MyApp
├── main.js
└── modules
    ├── a.js
    ├── b.js
    ├── c.js
    ├── d.js
    ├── e.js

In my NodeJS app, how can I import all my custom modules (a,b,c,d,e) in my main.js file at once?

I have long list of modules and I dont want to import them all separately.


问:
Java HiLo Game - Can't Generate New Guesses
SORRY I know there are other posts on this game, but my question is specific. I just started learning Java and threw together this HiLo game, but I am struggling to get 2 things down -

1) If a user wants to play again, how do I get it to generate a new pick? Right now if you play again, you get the same pick
2) If a user chooses to abort the game, I am not getting the message to generate

Help me pretty please, I'm new and vulnerable to Java!

```<code>package lab4;

import java.util.Scanner;
import java.util.Random;

public class hilo
{

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //randomly pick a number between 1-100
        Random rand = new Random();
        int pick = rand.nextInt(100) + 1;
        int count = 0;
        boolean play = true;

        //prompt user to guess
        Scanner scan = new Scanner(System.in);
        System.out.println("*---------------------------------*");
        System.out.println("* Guess a number between 1-100:   *");
        System.out.println("* (enter \"0\" to end at any time)  *");
        System.out.println("*---------------------------------*");
        int guess = scan.nextInt();

        //on each guess, say if too low or too high
        while (play = true)
        {
            while (guess != pick && guess !=0)
            {

                if (guess < pick)
                {
                    count++;
                    System.out.println("Higher...");
                    System.out.println(pick);
                    guess = scan.nextInt();
                }

                else if (guess > pick)
                {
                    count++;
                    System.out.println("Lower...");
                    System.out.println(pick);
                    guess = scan.nextInt();
                }

            }

            if (guess == pick)
            {
                System.out.println("You got it! It only took you " + count + " guesses.");
                System.out.println("Want to play again?");
                System.out.println("* Guess a number between 1-100:   *");
                System.out.println("* (enter \"0\" to end at any time)  *");
                guess = scan.nextInt();
                if (guess != 0)
                    play = true;
                else
                    play = false;
            }
        }

        if (play = false || guess == 0)
        {
            System.out.println("Bummer. See you next time!");
        }

     }
}
</code>```

答:
Two little things,

```<code>int pick = rand.nextInt(100) + 1;
// ...

//on each guess, say if too low or too high
while (play = true)
{
</code>```

One = is assignment, two == is equality. So while (play == true) (which is verbose) or while (play). And then move pick into the loop.

```<code>// int pick = rand.nextInt(100) + 1;
// ...
while (play) {
    int pick = rand.nextInt(100) + 1;
</code>```

And that should fix both problems.

Body:
SORRY I know there are other posts on this game, but my question is specific. I just started learning Java and threw together this HiLo game, but I am struggling to get 2 things down -

1) If a user wants to play again, how do I get it to generate a new pick? Right now if you play again, you get the same pick
2) If a user chooses to abort the game, I am not getting the message to generate

Help me pretty please, I'm new and vulnerable to Java!

package lab4;

import java.util.Scanner;
import java.util.Random;

public class hilo
{

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //randomly pick a number between 1-100
        Random rand = new Random();
        int pick = rand.nextInt(100) + 1;
        int count = 0;
        boolean play = true;

        //prompt user to guess
        Scanner scan = new Scanner(System.in);
        System.out.println("*---------------------------------*");
        System.out.println("* Guess a number between 1-100:   *");
        System.out.println("* (enter \"0\" to end at any time)  *");
        System.out.println("*---------------------------------*");
        int guess = scan.nextInt();

        //on each guess, say if too low or too high
        while (play = true)
        {
            while (guess != pick && guess !=0)
            {

                if (guess < pick)
                {
                    count++;
                    System.out.println("Higher...");
                    System.out.println(pick);
                    guess = scan.nextInt();
                }

                else if (guess > pick)
                {
                    count++;
                    System.out.println("Lower...");
                    System.out.println(pick);
                    guess = scan.nextInt();
                }

            }

            if (guess == pick)
            {
                System.out.println("You got it! It only took you " + count + " guesses.");
                System.out.println("Want to play again?");
                System.out.println("* Guess a number between 1-100:   *");
                System.out.println("* (enter \"0\" to end at any time)  *");
                guess = scan.nextInt();
                if (guess != 0)
                    play = true;
                else
                    play = false;
            }
        }

        if (play = false || guess == 0)
        {
            System.out.println("Bummer. See you next time!");
        }

     }
}

Body:
Two little things,

int pick = rand.nextInt(100) + 1;
// ...

//on each guess, say if too low or too high
while (play = true)
{

One = is assignment, two == is equality. So while (play == true) (which is verbose) or while (play). And then move pick into the loop.

// int pick = rand.nextInt(100) + 1;
// ...
while (play) {
    int pick = rand.nextInt(100) + 1;

And that should fix both problems.


问:
Dropwizard AssetsBundle and Angular 2 path
I am using dropwizard AssetsBundle serving Angular 2 application.
Now, angular 2 app path has following pattern:
http://host.com/base/route,
where http://host.com/base has to be rerouted to http://host.com/base/index.html, and "route" part to be parsed and handled by Angular client side code.

Unfortunately AssetsBundle can't find any resources by http://host.com/base/route path, and returns 404 error instead of rerouting request to http://host.com/base/index.html.

Any idea how to handle this?
I can write my own AssetsBundle to handle this situation, but would like to avoid it if there is any workaround.

Thank you.

答:
From the discussion at Dropwizard usergroup, it is possible to use IndexPageBundle plugin to achieve this:

Usergoup thread: https://groups.google.com/forum/#!topic/dropwizard-user/a8Gikq_0wcg

Code example: https://gitlab.com/linagora/petals-cockpit/blob/master/cockpit/src/main/java/org/ow2/petals/cockpit/PetalsCockpitApplication.java

```<code>@Override
public void initialize(@Nullable Bootstrap<PetalsCockpitConfiguration> bootstrap) {
    assert bootstrap != null;

    super.initialize(bootstrap);

    // TODO this is not the best because every new prefix must be added... if not, the static asset servlet will
    // take over instead of returning index.html
    // Improve when https://github.com/palantir/dropwizard-index-page/issues/38 is fixed
    bootstrap.addBundle(new IndexPageBundle("frontend/index.html",
            ImmutableSet.of("/", "/index.html", "/setup", "/login", "/workspaces", "/workspaces/*")));
    // no index file parameter because index is served by IndexPageBundle
    bootstrap.addBundle(new AssetsBundle("/frontend", "/", null));
}
</code>```

Body:
From the discussion at Dropwizard usergroup, it is possible to use IndexPageBundle plugin to achieve this:

Usergoup thread: https://groups.google.com/forum/#!topic/dropwizard-user/a8Gikq_0wcg

Code example: https://gitlab.com/linagora/petals-cockpit/blob/master/cockpit/src/main/java/org/ow2/petals/cockpit/PetalsCockpitApplication.java

@Override
public void initialize(@Nullable Bootstrap<PetalsCockpitConfiguration> bootstrap) {
    assert bootstrap != null;

    super.initialize(bootstrap);

    // TODO this is not the best because every new prefix must be added... if not, the static asset servlet will
    // take over instead of returning index.html
    // Improve when https://github.com/palantir/dropwizard-index-page/issues/38 is fixed
    bootstrap.addBundle(new IndexPageBundle("frontend/index.html",
            ImmutableSet.of("/", "/index.html", "/setup", "/login", "/workspaces", "/workspaces/*")));
    // no index file parameter because index is served by IndexPageBundle
    bootstrap.addBundle(new AssetsBundle("/frontend", "/", null));
}


问:
Xcode project - sync remote repository from github to Mac
I am working on a project at work and would like to work on it at home as well. I synced the Xcode project to a remote repository to github from my work's mac. I am wondering how I can get a copy on my home's mac and sync it so that I will be able to push commits and pull?</p>

答:
A simple

```<code>git clone https://....yourRepositoriy/ongithub
</code>```

You have to run this with git installed from the Terminal

Should work and copy all files to your local machine

Body:
A simple

git clone https://....yourRepositoriy/ongithub

You have to run this with git installed from the Terminal

Should work and copy all files to your local machine


问:
R gzfile output is incomplete
I am trying to get gz output from a data.frame in R.
I used the following script:

```<code>write.table(res,file = gzfile(newfile,open="wb"),quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)
</code>```

But the output is incomplete.
However if I don't use gzfile(), the output is ok. For example:

```<code>write.table(res,file =newfile,quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)
</code>```

The output is not big, just 9 MB in gz form.I don't find the reason on internet.I wonder why this could happern.
Thanks!

答:
You are creating a connection and opening it, but you never close it.  It won't be complete until closed.

There are two solutions:

Don't open the connection, let write.table open it:

```<code>write.table(res,file = gzfile(newfile),quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)
</code>```

Or, save it in a variable, and close it explicitly:

```<code>con <- gzfile(newfile, "wb")
write.table(res,file = con,quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)
close(con)
</code>```

Title: R gzfile output is incomplete

Body:
I am trying to get gz output from a data.frame in R.
I used the following script:

write.table(res,file = gzfile(newfile,open="wb"),quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)

But the output is incomplete.
However if I don't use gzfile(), the output is ok. For example:

write.table(res,file =newfile,quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)

The output is not big, just 9 MB in gz form.I don't find the reason on internet.I wonder why this could happern.
Thanks!

Body:
You are creating a connection and opening it, but you never close it.  It won't be complete until closed.

There are two solutions:

Don't open the connection, let write.table open it:

write.table(res,file = gzfile(newfile),quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)

Or, save it in a variable, and close it explicitly:

con <- gzfile(newfile, "wb")
write.table(res,file = con,quote = FALSE,sep="\t",row.names = FALSE,col.names = FALSE)
close(con)


问:
while loop is not giving expected results
i am learning python 3.6
while writing my script i come across a problem:

below are my codes

```<code>from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
    loop = 6

list1()

print("""-------------------------------------""")
</code>```

but problem is whenever i enter the defined names it works fine but when i enter the wrong name it stops, but what i want it should keep me asking "please enter valid name " until i enter valid name.
any suggestion. python 3.6

intend space is given here to give enter code

答:
You can assign 5 to loop in the else and move up the assignment of 6 to the same variable:

```<code>from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    loop = 6

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
        loop = 5

list1()

print("""-------------------------------------""")
</code>```

Anyway, it is a nice idea improving the name of this variable and the value. It would be better use a boolean variable here with a name like isInvalidName. So you while would be: while isInvalidName:

Body:
i am learning python 3.6
while writing my script i come across a problem:

below are my codes

from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
    loop = 6

list1()

print("""-------------------------------------""")

but problem is whenever i enter the defined names it works fine but when i enter the wrong name it stops, but what i want it should keep me asking "please enter valid name " until i enter valid name.
any suggestion. python 3.6

intend space is given here to give enter code

Body:
You can assign 5 to loop in the else and move up the assignment of 6 to the same variable:

from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    loop = 6

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
        loop = 5

list1()

print("""-------------------------------------""")

Anyway, it is a nice idea improving the name of this variable and the value. It would be better use a boolean variable here with a name like isInvalidName. So you while would be: while isInvalidName:


问:
Regex to split a hashtag into words
I am trying to come up with a regex which will correctly split a hashtag into its words. For example:

XP => XP

ACar => A Car

GoodCar => Good Car

OnceUponATime => Once Upon A Time

LoveXP => Love XP

AppleVsXP => Apple Vs XP

JamesBond007 => James Bond 007

Edit:
I have tried

```<code>expanded = ' '.join(re.findall(r"[A-Z][^A-Z]*", self.text))
</code>```

What is a a more robust way which will address all the use cases above?

答:
You can define several patterns to match what's considered a separate word - an uppercase character followed by a series of lowercase characters, a series of digits, a series of uppercase characters not followed by lowercase characters, etc. -  and then just cycle it over your string:

```<code>import re

pattern = re.compile(r"[A-Z][a-z]+|\d+|[A-Z]+(?![a-z])")

def split_hashtag(tag):
    return pattern.findall(tag)
</code>```

If you test it with your tags:

```<code>test_tags = ["XP", "ACar", "GoodCar", "OnceUponATime", "LoveXP", "AppleVsXP", "JamesBond007"]
for tag in test_tags:
    print("{} => {}".format(tag, " ".join(split_hashtag(tag))))
</code>```

You get:

```XP => XP
ACar => A Car
GoodCar => Good Car
OnceUponATime => Once Upon A Time
LoveXP => Love XP
AppleVsXP => Apple Vs XP
JamesBond007 => James Bond 007```

Title: Regex to split a hashtag into words

Body:
I am trying to come up with a regex which will correctly split a hashtag into its words. For example:

XP => XP

ACar => A Car

GoodCar => Good Car

OnceUponATime => Once Upon A Time

LoveXP => Love XP

AppleVsXP => Apple Vs XP

JamesBond007 => James Bond 007

Edit:
I have tried

expanded = ' '.join(re.findall(r"[A-Z][^A-Z]*", self.text))

What is a a more robust way which will address all the use cases above?

Body:
You can define several patterns to match what's considered a separate word - an uppercase character followed by a series of lowercase characters, a series of digits, a series of uppercase characters not followed by lowercase characters, etc. -  and then just cycle it over your string:

import re

pattern = re.compile(r"[A-Z][a-z]+|\d+|[A-Z]+(?![a-z])")

def split_hashtag(tag):
    return pattern.findall(tag)

If you test it with your tags:

test_tags = ["XP", "ACar", "GoodCar", "OnceUponATime", "LoveXP", "AppleVsXP", "JamesBond007"]
for tag in test_tags:
    print("{} => {}".format(tag, " ".join(split_hashtag(tag))))

You get:

XP => XP
ACar => A Car
GoodCar => Good Car
OnceUponATime => Once Upon A Time
LoveXP => Love XP
AppleVsXP => Apple Vs XP
JamesBond007 => James Bond 007


问:
jQuery browser detection?
Is there a good way to detect if the user's browser is Internet Explorer using jQuery?

I have an issue with PNG graphics using IE and want to swap them for GIF's only if the user is viewing the site with IE.

答:
I realise this isn't an answer  - but I can't really post this in a comment!

If you're going to use javascript this code fixes the png issue with ie6. I haven't used it much, but afaik you need a transparent gif image called x.gif and it does the rest automatically.

```<code>// JavaScript Document

var supersleight    = function() {

    var root = false;
    var applyPositioning = true;

    // Path to a transparent GIF image
    var shim            = 'x.gif';

    // RegExp to match above GIF image name
    var shim_pattern    = /x\.gif$/i;

    var fnLoadPngs = function() {
        if (root) {
            root = document.getElementById(root);
        }else{
            root = document;
        }
        for (var i = root.all.length - 1, obj = null; (obj = root.all[i]); i--) {
            // background pngs
            if (obj.currentStyle.backgroundImage.match(/\.png/i) !== null) {
                bg_fnFixPng(obj);
            }
            // image elements
            if (obj.tagName=='IMG' && obj.src.match(/\.png$/i) !== null){
                el_fnFixPng(obj);
            }
            // apply position to 'active' elements
            if (applyPositioning && (obj.tagName=='A' || obj.tagName=='INPUT') && obj.style.position === ''){
                obj.style.position = 'relative';
            }
        }
    };

    var bg_fnFixPng = function(obj) {
        var mode = 'scale';
        var bg  = obj.currentStyle.backgroundImage;
        var src = bg.substring(5,bg.length-2);
        if (obj.currentStyle.backgroundRepeat == 'no-repeat') {
            mode = 'crop';
        }
        obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
        obj.style.backgroundImage = 'url('+shim+')';
    };

    var el_fnFixPng = function(img) {
        var src = img.src;
        img.style.width = img.width + "px";
        img.style.height = img.height + "px";
        img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
        img.src = shim;
    };

    var addLoadEvent = function(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            };
        }
    };

    return {
        init: function() {
            addLoadEvent(fnLoadPngs);
        },

        limitTo: function(el) {
            root = el;
        },

        run: function() {
            fnLoadPngs();
        }
    };
}();

// limit to part of the page ... pass an ID to limitTo:
// supersleight.limitTo('header');

supersleight.init();
</code>```

Title: jQuery browser detection?

Body:
I realise this isn't an answer  - but I can't really post this in a comment!

If you're going to use javascript this code fixes the png issue with ie6. I haven't used it much, but afaik you need a transparent gif image called x.gif and it does the rest automatically.

// JavaScript Document

var supersleight    = function() {

    var root = false;
    var applyPositioning = true;

    // Path to a transparent GIF image
    var shim            = 'x.gif';

    // RegExp to match above GIF image name
    var shim_pattern    = /x\.gif$/i;

    var fnLoadPngs = function() {
        if (root) {
            root = document.getElementById(root);
        }else{
            root = document;
        }
        for (var i = root.all.length - 1, obj = null; (obj = root.all[i]); i--) {
            // background pngs
            if (obj.currentStyle.backgroundImage.match(/\.png/i) !== null) {
                bg_fnFixPng(obj);
            }
            // image elements
            if (obj.tagName=='IMG' && obj.src.match(/\.png$/i) !== null){
                el_fnFixPng(obj);
            }
            // apply position to 'active' elements
            if (applyPositioning && (obj.tagName=='A' || obj.tagName=='INPUT') && obj.style.position === ''){
                obj.style.position = 'relative';
            }
        }
    };

    var bg_fnFixPng = function(obj) {
        var mode = 'scale';
        var bg  = obj.currentStyle.backgroundImage;
        var src = bg.substring(5,bg.length-2);
        if (obj.currentStyle.backgroundRepeat == 'no-repeat') {
            mode = 'crop';
        }
        obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
        obj.style.backgroundImage = 'url('+shim+')';
    };

    var el_fnFixPng = function(img) {
        var src = img.src;
        img.style.width = img.width + "px";
        img.style.height = img.height + "px";
        img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
        img.src = shim;
    };

    var addLoadEvent = function(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            };
        }
    };

    return {
        init: function() {
            addLoadEvent(fnLoadPngs);
        },

        limitTo: function(el) {
            root = el;
        },

        run: function() {
            fnLoadPngs();
        }
    };
}();

// limit to part of the page ... pass an ID to limitTo:
// supersleight.limitTo('header');

supersleight.init();


答:
When you creating an Intent to next activity, call:

```<code>yourIntent.putExtra("points", finalpoints);
</code>```

and put your finalpoints variable to it and then in next activity retrieve it using:

```<code>points = getIntent().getIntExtra("points");
</code>```

Here is a good example, but with a string. However, the approach is same.
https://developer.android.com/training/basics/firstapp/starting-activity.html

Title: Passing Integer among activity in Android

Body:
I am creating a quiz app. the code pasted down is the second activity of the app. But it stated the int point = 0, and the finalpoints is not stated because it depends on the answers in the quiz.
However do i pass whatever answer in this activity is passed to the next one and the next.

here is the code for the activity2:

 package com.example.android.questionme;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {
    Intent intent = getIntent();

    int point = 0;
    int finalpoints;

    RadioButton option1forQ1;
    RadioButton option2forQ1;
    RadioButton option1forQ2;
    RadioButton option2forQ2;
    RadioButton option3forQ2;
    RadioButton option4forQ2;
    RadioButton option1forQ3;
    RadioButton option2forQ3;
    RadioButton option3forQ3;
    RadioButton option1forQ4;
    RadioButton option2forQ4;
    RadioButton option3forQ4;
    RadioButton option4forQ4;
    RadioButton option1forQ5;
    RadioButton option2forQ5;
    RadioButton option3forQ5;
    RadioButton option4forQ5;
    CheckBox option1forQ6;
    CheckBox option2forQ6;
    CheckBox option3forQ6;
    CheckBox option4forQ6;
    RadioButton option1forQ7;
    RadioButton option2forQ7;
    RadioButton option3forQ7;
    RadioButton option4forQ7;
    RadioButton option1forQ8;
    RadioButton option2forQ8;
    RadioButton option3forQ8;

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

        option1forQ1 = (RadioButton) findViewById(R.id.right_answer_for_Q1);
        option2forQ1 = (RadioButton) findViewById(R.id.wrong_answer_for_Q1);
        option1forQ2 = (RadioButton) findViewById(R.id.question_two_right_answer);
        option2forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer0);
        option3forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer1);
        option4forQ2 = (RadioButton) findViewById(R.id.question_two_wrong_answer2);
        option1forQ3 = (RadioButton) findViewById(R.id.question_three_right_answer);
        option2forQ3 = (RadioButton) findViewById(R.id.question_three_wrong_answer0);
        option3forQ3 = (RadioButton) findViewById(R.id.question_three_wrong_answer1);
        option1forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer0);
        option2forQ4 = (RadioButton) findViewById(R.id.question_four_right_answer);
        option3forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer1);
        option4forQ4 = (RadioButton) findViewById(R.id.question_four_wrong_answer2);
        option1forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer0);
        option2forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer1);
        option3forQ5 = (RadioButton) findViewById(R.id.question_five_wrong_answer2);
        option4forQ5 = (RadioButton) findViewById(R.id.question_five_right_answer);
        option1forQ6 = (CheckBox) findViewById(R.id.question_six_right_answer);
        option2forQ6 = (CheckBox) findViewById(R.id.question_six_wrong_answer);
        option3forQ6 = (CheckBox) findViewById(R.id.question_six_wrong_answer1);
        option4forQ6 = (CheckBox) findViewById(R.id.question_six_right_answer1);
        option1forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer);
        option2forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer1);
        option3forQ7 = (RadioButton) findViewById(R.id.question_seven_right_answer);
        option4forQ7 = (RadioButton) findViewById(R.id.question_seven_wrong_answer2);
        option1forQ8 = (RadioButton) findViewById(R.id.question_eight_wrong_answer);
        option2forQ8 = (RadioButton) findViewById(R.id.question_eight_right_answer);
        option3forQ8 = (RadioButton) findViewById(R.id.question_eight_wrong_answer2);
    }
    public void onYesRadioButtonClicked (View view){
        Intent intent = new Intent(this, Main3Activity.class);
        boolean option1forQ1IsChecked = option1forQ1.isChecked();
        boolean option2forQ1IsChecked = option2forQ1.isChecked();
        if (option1forQ1IsChecked) {
            point *= 2;
            startActivity(intent);
            Toast.makeText(this, "Good Start"+ "2 Points", Toast.LENGTH_SHORT).show();
        }
        else
        if (option2forQ1IsChecked) {
            point -= 1;
        }
    }
    public void onNoRadioButtonClicked (View view){
        boolean option2forQ1IsChecked = option2forQ1.isChecked();
        if (option2forQ1IsChecked){
        Toast.makeText(this, "Wrong Answer, You can Google about Google on Google"
                , Toast.LENGTH_SHORT).show();
        }
}
}

Body:
When you creating an Intent to next activity, call:

yourIntent.putExtra("points", finalpoints);

and put your finalpoints variable to it and then in next activity retrieve it using:

points = getIntent().getIntExtra("points");

Here is a good example, but with a string. However, the approach is same.
https://developer.android.com/training/basics/firstapp/starting-activity.html


问:
div animate not working jquery
HTML

```<code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>
</head>

<body>
  <div id="top1">
    <div class="inside1">
      <div class="nested_inside1"> MY HAPPY PLACES </div>
    </div>
    <div class="inside2">
      <div class="nested_inside2"> CLUMSSY BEACHES
      </div>
    </div>
    <div class="inside3">
      <div class="nested_inside3"> REGULAR APPLES </div>
    </div>
    <div class="inside4">
      <div class="nested_inside4"> LUSTY BRUSHES </div>
    </div>
    <div class="inside5">
      <div class="nested_inside5"> ECSTATIC DIMENSIONS </div>
    </div>
    <div class="inside6">
      <div class="nested_inside6"> CURLY HILLS </div>
    </div>
    <div class="inside7">
      <div class="nested_inside7"> SHINY WATER </div>
    </div>
    <div class="inside8">
      <div class="nested_inside8"> COOL BOATS </div>
    </div>
    <div class="inside9">
      <div class="nested_inside9"> CRUNCHY CLUSHTERS </div>
    </div>
    <script type="text/javascript" src="myscript2.js"></script>
</body>

</html>
</code>```

JavaScript

```<code>$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});
</code>```

答:
This can't work since you dont' have a class nested_inside but nested_inside1, ensted_inside2 ... and so on... you have to remove the numbers

adapt it like this for each and every one:

```<code><div class="inside7">
  <div class="nested_inside"> SHINY WATER </div>
</div>
</code>```

and you also need to inlcude jquery in your head:

```<code><script src="path/to/jquery.js"></script>
</code>```

adapt your code like this:

```<code> $(document).ready(function() {
  $("#top1").on("mouseover", ".nested_inside", function() {
     $(this).animate({
    "top": "-10px"
    });
  });
 });
</code>```

and your CSS like this:

```<code>.nested_inside {
  position: relative;
}
</code>```

working fiddle: https://jsfiddle.net/jnb7p14o/2/

Title: div animate not working jquery

Body:
HTML

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>

 MY HAPPY PLACES

 CLUMSSY BEACHES

 REGULAR APPLES

 LUSTY BRUSHES

 ECSTATIC DIMENSIONS

 CURLY HILLS

 SHINY WATER

 COOL BOATS

 CRUNCHY CLUSHTERS

JavaScript

$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});

Body:
This can't work since you dont' have a class nested_inside but nested_inside1, ensted_inside2 ... and so on... you have to remove the numbers

adapt it like this for each and every one:

<div class="inside7">
  <div class="nested_inside"> SHINY WATER </div>
</div>

and you also need to inlcude jquery in your head:

<script src="path/to/jquery.js"></script>

adapt your code like this:

 $(document).ready(function() {
  $("#top1").on("mouseover", ".nested_inside", function() {
     $(this).animate({
    "top": "-10px"
    });
  });
 });

and your CSS like this:

.nested_inside {
  position: relative;
}

working fiddle: https://jsfiddle.net/jnb7p14o/2/


问:
run for-loop for large numbers in python
```<code> for i in range(1000000000):
 print(i)
</code>```

This snippet gives memory error than How to run this loop. Any suggestions on how to run it.Thanks.

```<code>>>>MemoryError
</code>```

UPDATE:
Actually I was trying something like this:

```<code>arr = []

for i in xrange(1000000000):
    arr.append(i*i)
print(max(set(arr)))
</code>```

I don't know how to deal with such large numbers.

答:
Using xrange instead of range should solve your problem

But what is the difference?

For the most part, they are the exact same. They both generate a list of integers. However, range returns a list object whereas xrange returns a xrange object.

Basically xrange doesn't generate a static list at runtime...instead it generates the values as you need them , which prevents memory error.

Happy coding!

Body:
 for i in range(1000000000):
 print(i)

This snippet gives memory error than How to run this loop. Any suggestions on how to run it.Thanks.

>>>MemoryError

UPDATE:
Actually I was trying something like this:

arr = []

for i in xrange(1000000000):
    arr.append(i*i)
print(max(set(arr)))

I don't know how to deal with such large numbers.


问:
Applying "Automatic" number formatting / number formatting reset
Is it possible to apply the 'Automatic' number format programmatically through GAS?  My issue is that as I write columns of numbers, Sheets seems to attempt to apply appropriate formatting, but gets it wrong sometimes. That is, particular small integers (1 sometimes) will be formatted as dates.  The range is being written in one myRange.setValues() method and I can't see any pattern to the mistakes and therefore don't see any way to prevent the surprise mis-formatting.

But, when I select the range in sheets and just click "Automatic" on the number format menu all returns to normal.  It doesn't help to click that upfront as the writing of data somehow resets the format.

Despite the long-winded intro, my question is very simple: how to programmatically apply "Automatic" number formatting.  I'm thinking this is very basic, especially since google and searches here have been no help.

My current fallback solution is to use myRange.setNumberFormat("0") as the format for the whole range. This is not ideal as some numbers are very large and are easier to read in scientific notation. There are also some text strings in the range, but these format properly regardless of format applied.  I also would prefer to avoid having to iterate through the data and test for values to determine the best format, when it's just a couple clicks in the user interface.

答:
I use copyFormatToRange to copy/apply Automatic format:

```<code>var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var source_cell = sheet.getRange("A1");//A1: cell having automatic format
source_cell.copyFormatToRange(sheet,1,1,2,2);//copy format of cell A1 to cell A2
</code>```

You can write an API that opens another spreadsheet, read any cell that having the automatic format.

```<code>var ss = SpreadsheetApp.openById(SpreadsheetId);//Id of another spreadsheet
</code>```

Then use copyFormatToRange to your wanted cell.

ContentLicense: CC BY-SA 4.0

Body:
I use copyFormatToRange to copy/apply Automatic format:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var source_cell = sheet.getRange("A1");//A1: cell having automatic format
source_cell.copyFormatToRange(sheet,1,1,2,2);//copy format of cell A1 to cell A2

You can write an API that opens another spreadsheet, read any cell that having the automatic format.

var ss = SpreadsheetApp.openById(SpreadsheetId);//Id of another spreadsheet

Then use copyFormatToRange to your wanted cell.


问:
why is my page loading so slowly?
My website: http://jgyboatparty.com/

is loading horrifically slow  and I cant figure out why. I have compressed the images as much as possible and made the video file available as a webm, and yet with a fresh reload the page is taken minutes to load!

Am i missing something here, as for some reason when I look at when elements are loaded, some of the images dont even start loading until 30 seconds in. This all means that my loader goes on for a while. (I have a wait until images loaded function)

Any advice would be much appreciated :)

答:
Open your broswer's dev tools and find out.

Browsers only allow 4 (max) concurrent downloads from 1 domain. So while the browser is downloading those, it blocks the others.

Move your scrips/ images to a sub domain or a cdn or just do something listed in the post below.

Get number of concurrent requests by browser

Title: why is my page loading so slowly?


问:
Deploying PhoneGap Applications to Web instead of to App Store
I've built a web platform where one small feature allows users to contribute data to the system. Now that smartphones are so common, I want to build an app that allows people to submit some information, along with a camera photo and their GPS location.

As our users use varying phones, I'd like to build a single universal app to accomplish that task. I found PhoneGap online for that very purpose, but I have a question: can PhoneGap applications be deployed to the web instead of to app stores? By that, I'm asking whether camera and geolocation functionality will still work if the HTML and Javascript files are placed on a web server.

If not, I've also seen JQTouch. Can I use JQTouch instead for such camera and GPS functionality?

答:
yes, you can deploy phonegap apps with the market.

At least, if it's not an iPhone.

You should still compile the applications and make the user download them.

jQTouch is just for the GUI, much like sencha and jQuery Mobile.

HTML5 would give you a gps functionality, but that doesn't work on most phones yet (symbian and BB and WP make up about 50% of the market if not more).


问:
How to generate totals of fields from related model records
I'm trying to work out how to generate totals of fields from related model records.

Example: I have 2 Google Drive Table models (Projects & Stages) with a relation where 1 Project can have many Stages. The Stages model has a number of fields, one of which is Budget.

I'm trying work out how to display a Total Project Budget, which is the sum of the Budget fields of the Stages related to each Project.

I'm really stuck on getting this to work and wondering if I need to create a client script, server script, or calculated model, or if there's an easy way to do this directly within a binding.

Here is a link to a bunch of screen-grabs of what I'm trying to build, the UI and setup in App Maker:

https://www.dropbox.com/sh/wt00virvn88puyi/AACy7-fPLYFF1H9uFkvEuvgTa?dl=0

答:
I got it working by creating the following client script, after studying Andrey's suggestion & link (thanks!). I call the script whenever the totals need recalculating (i.e. onValueChange of existing Stages, and onAttach/Detach for new or deleted Stages. Works nicely.</p>

```<code>function updateProjectTotals() {
    var currentProject = app.datasources.Projects.item;
    var totals = {ProjectName:currentProject.ProjectName, Stages:0, Progress:0, Budget:0};
    var stages = currentProject.Stages;
    stages.forEach(function(item){
        totals.Progress += item.StageProgress;
        totals.Budget += item.StageBudget;
    });
    totals.Stages = stages.length;
    totals.Progress = (totals.Progress/totals.Stages);
    var record = app.datasources.Projects.item;
    record.ProjectProgress = totals.Progress;
    record.ProjectBudget = totals.Budget;
}
</code>```

Body:
I got it working by creating the following client script, after studying Andrey's suggestion & link (thanks!). I call the script whenever the totals need recalculating (i.e. onValueChange of existing Stages, and onAttach/Detach for new or deleted Stages. Works nicely.

function updateProjectTotals() {
    var currentProject = app.datasources.Projects.item;
    var totals = {ProjectName:currentProject.ProjectName, Stages:0, Progress:0, Budget:0};
    var stages = currentProject.Stages;
    stages.forEach(function(item){
        totals.Progress += item.StageProgress;
        totals.Budget += item.StageBudget;
    });
    totals.Stages = stages.length;
    totals.Progress = (totals.Progress/totals.Stages);
    var record = app.datasources.Projects.item;
    record.ProjectProgress = totals.Progress;
    record.ProjectBudget = totals.Budget;
}


答:
Just assign a new value for pick variable in your if condition where you test the equality of guess and pick

```<code>if (guess == pick)
{
  System.out.println("You got it! It only took you " + count + " guesses.");
  System.out.println("Want to play again?");
  System.out.println("* Guess a number between 1-100:   *");
  System.out.println("* (enter \"0\" to end at any time)  *");
  guess = scan.nextInt();

  pick = rand.nextInt(100) + 1; // new value

  if (guess != 0)
    play = true;
  else
    play = false;
}
</code>```

Title: Java HiLo Game - Can't Generate New Guesses

Body:
SORRY I know there are other posts on this game, but my question is specific. I just started learning Java and threw together this HiLo game, but I am struggling to get 2 things down -

1) If a user wants to play again, how do I get it to generate a new pick? Right now if you play again, you get the same pick
2) If a user chooses to abort the game, I am not getting the message to generate

Help me pretty please, I'm new and vulnerable to Java!

package lab4;

import java.util.Scanner;
import java.util.Random;

public class hilo
{

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //randomly pick a number between 1-100
        Random rand = new Random();
        int pick = rand.nextInt(100) + 1;
        int count = 0;
        boolean play = true;

        //prompt user to guess
        Scanner scan = new Scanner(System.in);
        System.out.println("*---------------------------------*");
        System.out.println("* Guess a number between 1-100:   *");
        System.out.println("* (enter \"0\" to end at any time)  *");
        System.out.println("*---------------------------------*");
        int guess = scan.nextInt();

        //on each guess, say if too low or too high
        while (play = true)
        {
            while (guess != pick && guess !=0)
            {

                if (guess < pick)
                {
                    count++;
                    System.out.println("Higher...");
                    System.out.println(pick);
                    guess = scan.nextInt();
                }

                else if (guess > pick)
                {
                    count++;
                    System.out.println("Lower...");
                    System.out.println(pick);
                    guess = scan.nextInt();
                }

            }

            if (guess == pick)
            {
                System.out.println("You got it! It only took you " + count + " guesses.");
                System.out.println("Want to play again?");
                System.out.println("* Guess a number between 1-100:   *");
                System.out.println("* (enter \"0\" to end at any time)  *");
                guess = scan.nextInt();
                if (guess != 0)
                    play = true;
                else
                    play = false;
            }
        }

        if (play = false || guess == 0)
        {
            System.out.println("Bummer. See you next time!");
        }

     }
}

Body:
Just assign a new value for pick variable in your if condition where you test the equality of guess and pick

if (guess == pick)
{
  System.out.println("You got it! It only took you " + count + " guesses.");
  System.out.println("Want to play again?");
  System.out.println("* Guess a number between 1-100:   *");
  System.out.println("* (enter \"0\" to end at any time)  *");
  guess = scan.nextInt();

  pick = rand.nextInt(100) + 1; // new value

  if (guess != 0)
    play = true;
  else
    play = false;
}


问:
Make mapped out portion of a div transparent

I want to make something like this in the above image with just 2 divs and an img. I actually did the one above but I have to use about 6 divs.

Is there a way of making a mapped out area of the parent div transparent with CSS or JavaScript.

NB: The middle square div is draggable and resizable.

答:
I've used three div in this snippet: a background image div, a background overlay (for the tint), and a cropped region.

The cropped region has the same background-image set as the background image div, but the background position is set to the negative div position values.

const cropDiv = document.querySelector(".croppedRegion");

let setCropRegion = function(x1, y1, x2, y2) {
  cropDiv.style.backgroundPositionX = `${-x1}px`;
  cropDiv.style.backgroundPositionY = `${-y1}px`;
  cropDiv.style.width = `${x2-x1}px`;
  cropDiv.style.height = `${y2-y1}px`;
  cropDiv.style.left = `${x1}px`;
  cropDiv.style.top = `${y1}px`;
}

setCropRegion(10, 10, 240, 240);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin:0px;
}

.backgroundImg {
  width:250px;
  height:250px;
  background-image: url('https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG');

  position:relative;
}

.backgroundOverlay {
  margin:0px;
  padding:0px;
  width:100%;
  height:100%;
  background-color:rgba(255,255,255,0.6);
}

.croppedRegion {
  width:110px;
  height:80px;
  background-image: url('https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG');

  background-size:250px 250px;
  background-position:-80px -90px;
  position:absolute;
  top:90px;
  left:80px;
}</code>```

```

Body:
I've used three div in this snippet: a background image div, a background overlay (for the tint), and a cropped region.

The cropped region has the same background-image set as the background image div, but the background position is set to the negative div position values.

const cropDiv = document.querySelector(".croppedRegion");

let setCropRegion = function(x1, y1, x2, y2) {
  cropDiv.style.backgroundPositionX = `${-x1}px`;
  cropDiv.style.backgroundPositionY = `${-y1}px`;
  cropDiv.style.width = `${x2-x1}px`;
  cropDiv.style.height = `${y2-y1}px`;
  cropDiv.style.left = `${x1}px`;
  cropDiv.style.top = `${y1}px`;
}

setCropRegion(10, 10, 240, 240);

* {
  margin:0px;
}

.backgroundImg {
  width:250px;
  height:250px;
  background-image: url('https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG');

  position:relative;
}

.backgroundOverlay {
  margin:0px;
  padding:0px;
  width:100%;
  height:100%;
  background-color:rgba(255,255,255,0.6);
}

.croppedRegion {
  width:110px;
  height:80px;
  background-image: url('https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG');

  background-size:250px 250px;
  background-position:-80px -90px;
  position:absolute;
  top:90px;
  left:80px;
}

<div class="backgroundImg">
  <div class="backgroundOverlay">
    <div class="croppedRegion"></div>
  </div>
</div>


问:
GWT java URL Validator
Does someone knows a function that validate if a url is valid or not purely in GWT java without using any JSNI</p>

答: org.apache.commons.validator.UrlValidator and static method isValid(String url) might be of help here.</p>

Title: GWT java URL Validator


问:
Vertically center list item content with Flexbox?
I have the following simple list...

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul></code>```

I am trying to get the item contents to be vertically centered, is flexbox the way to do this?

答:
Yes flexbox is great for this. You can use the existing layout and just use inline-flex on the li and set align-items: center to vertically center the content.

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-flex;margin-right:10px;background:green;color:white;align-items:center;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul></code>```

You could also just set the line-height of the content to the height of the parent and it will center the content vertically.

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;line-height:200px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul></code>```

Body:
I have the following simple list...

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;}

Item 1

Item 2

Item 3

Item 4

Item 5

I am trying to get the item contents to be vertically centered, is flexbox the way to do this?

Body:
Yes flexbox is great for this. You can use the existing layout and just use inline-flex on the li and set align-items: center to vertically center the content.

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-flex;margin-right:10px;background:green;color:white;align-items:center;}

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

You could also just set the line-height of the content to the height of the parent and it will center the content vertically.

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;line-height:200px;}

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>


问:
rationale for std::lower_bound and std::upper_bound?
STL provides binary search functions std::lower_bound and std::upper_bound,
but I tend not to use them because I've been unable to remember what they do,
because their contracts seem completely mystifying to me.

Just from looking at the names,
I'd guess that "lower_bound" might be short for "last lower bound",

i.e. the last element in the sorted list that is <= the given val (if any).

And similarly I'd guess "upper_bound" might be short for "first upper bound",

i.e. the first element in the sorted list that is >= the given val (if any).

But the documentation says they do something rather different from that--
something that seems to be a mixture of backwards and random, to me.
To paraphrase the doc:

    - lower_bound finds the first element that's >= val

    - upper_bound finds the first element that's > val

So lower_bound doesn't find a lower bound at all; it finds the first upper bound!?
And upper_bound finds the first strict upper bound.

Does this make any sense??
How do you remember it?

答:
For an array or vector :

std::lower_bound:
Returns an iterator pointing to the first element in the range  that is

less than or equal to value.(for array or vector in decreasing order)

greater than or equal to value.(for array or vector in increasing order)

std::upper_bound:
Returns an iterator pointing to the first element in the range that is

less than value.(for array or vector in decreasing order)

greater than value.(for array or vector in increasing order)


问:
Case Insensitive REPLACE for MySQL
Is there a case insensitive Replace for MySQL?

I'm trying to replace a user's old username with their new one within a paragraph text.

```<code>$targetuserold = "@".$mynewusername;
$targetusernew = "@".$newusername;

$sql = "
    UPDATE timeline
    SET message = Replace(message,'".$targetuserold."', '".$targetusernew."')
";

$result = mysql_query($sql);
</code>```

This is missing the instances where the old username is a different case. Example: replacing "Hank" with "Jack" in all the rows in my database will leave behind instances of "hank".

答:
An easier way that works without any stored function:

```<code>SELECT message,
       substring(comments,position(lower('".$targetuserold."') in message) ) AS oldval
  FROM timeline
 WHERE message LIKE '%".$targetuserold."%'
</code>```

gives you the exact, case sensitive spellings of the username in all messages. As you seem to run that from a PHP script, you could use that to collect the spellings together with the corresponding IDs, and then run a simple REPLACE(message,'".$oldval.",'".$targetusernew."') on that. Or use the above as sub-select:

```<code>UPDATE timeline
    SET message = REPLACE(
                   message,
                   (SELECT substring(comments,position(lower('".$targetuserold."') in message))),
                   '".$targetusernew."'
                  )
</code>```

Works like a charm here.

Credits given to this article, where I got the idea from.

Title: Case Insensitive REPLACE for MySQL

Body:
Is there a case insensitive Replace for MySQL?

I'm trying to replace a user's old username with their new one within a paragraph text.

$targetuserold = "@".$mynewusername;
$targetusernew = "@".$newusername;

$sql = "
    UPDATE timeline
    SET message = Replace(message,'".$targetuserold."', '".$targetusernew."')
";

$result = mysql_query($sql);

This is missing the instances where the old username is a different case. Example: replacing "Hank" with "Jack" in all the rows in my database will leave behind instances of "hank".

Body:
An easier way that works without any stored function:

SELECT message,
       substring(comments,position(lower('".$targetuserold."') in message) ) AS oldval
  FROM timeline
 WHERE message LIKE '%".$targetuserold."%'

gives you the exact, case sensitive spellings of the username in all messages. As you seem to run that from a PHP script, you could use that to collect the spellings together with the corresponding IDs, and then run a simple REPLACE(message,'".$oldval.",'".$targetusernew."') on that. Or use the above as sub-select:

UPDATE timeline
    SET message = REPLACE(
                   message,
                   (SELECT substring(comments,position(lower('".$targetuserold."') in message))),
                   '".$targetusernew."'
                  )

Works like a charm here.

Credits given to this article, where I got the idea from.


问:
SQL Query nvarchar to date
I am working on SAP HANA Studio and have tried to run SQL command that converts an entire column of field, nvarchar, into one of field, date.

My dates have format: dd-mon-yyyy (i.e '29-Mar-1997') with field nvarchar(11).

I have looked at previous questions and SQL command documentation (for functions like CAST, CONVERT, TO_DATE, STR_TO_DATE) and have not gotten a solution.

Typical errors I get are: Function not recognized, or, Error while parsing Service Date as DATE at function to_date().

Any suggestions?

Thanks
-Diana

答:
Try TO_DATE():

```<code>select to_date(col, 'DD-MON-YYYY')
</code>```

Title: SQL Query nvarchar to date

Body:
Try TO_DATE():

select to_date(col, 'DD-MON-YYYY')


问:
Routing does not work well with HTML5-History-API
In a mean-stack web application, I use html5mode and have the following code in index.html:

```<code><base href="/" />
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="https://cdn.rawgit.com/devote/HTML5-History-API/master/history.js"></script>
</code>```

I have defined the following angular-ui-router:

```<code>    .state('addinHome', {
        url: '/addin/home',
        template: "home page"
    })
    .state('addinTest', {
        url: '/addin/test',
        template: '<a href="addin/home">one</a>',
        controller: 'TestCtrl'
    })
</code>```

Then, I go to https://localhost:3000/addin/test, clicking on one leads me to https://localhost:3000/addin/test#%2Faddin%2Fhome, whereas I would want to go to https://localhost:3000/addin/home.

If I don't have office.js and history.js, clicking on one does lead me to https://localhost:3000/addin/home.

Does anyone know how to go to https://localhost:3000/addin/home while keeping office.js and history.js?

答:
I found it... just use </p>

```<code>template: '<a href="addin/home" target="_self">one</a>'
</code>```

Body:
In a mean-stack web application, I use html5mode and have the following code in index.html:

<base href="/" />

I have defined the following angular-ui-router:

    .state('addinHome', {
        url: '/addin/home',
        template: "home page"
    })
    .state('addinTest', {
        url: '/addin/test',
        template: 'one',
        controller: 'TestCtrl'
    })

Then, I go to https://localhost:3000/addin/test, clicking on one leads me to https://localhost:3000/addin/test#%2Faddin%2Fhome, whereas I would want to go to https://localhost:3000/addin/home.

If I don't have office.js and history.js, clicking on one does lead me to https://localhost:3000/addin/home.

Does anyone know how to go to https://localhost:3000/addin/home while keeping office.js and history.js?

Body:
I found it... just use

template: '<a href="addin/home" target="_self">one</a>'


问:
Python/Django excel to html
Okay, so what I want to do is upload an excel sheet and display it on my website, in html. What are my options here ? I've found this xlrd module that allows you to read the data from spreadsheets, but I don't really need that right now.</p>

答:
Use Zoho Viewer in your template.

For example:

```<code><iframe src="http://viewer.zoho.com/api/urlview.do?url=http://www.iasted.org/conferences/formatting/Presentations-Tips.ppt&embed=true"
        style="width:300px; height:300px;" frameborder="0">
</iframe>
</code>```

Title: Python/Django excel to html

Body:
Use Zoho Viewer in your template.

For example:

<iframe src="http://viewer.zoho.com/api/urlview.do?url=http://www.iasted.org/conferences/formatting/Presentations-Tips.ppt&embed=true"
        style="width:300px; height:300px;" frameborder="0">
</iframe>


答:
You could add padding on the top of your li

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;padding-top: 100px;display:inline-block;margin-right:10px;background:green;color:white;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>since you directly defined the height of the box I was able to just divide that value in half in order to center the content using padding. If you don't know the difference between padding margin and border. Look into the box model in css. It is one of the most fundamental concepts you will need to grasp to have a good understanding of css.

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul></code>```

Title: Vertically center list item content with Flexbox?

Body:
You could add padding on the top of your li

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;padding-top: 100px;display:inline-block;margin-right:10px;background:green;color:white;}

since you directly defined the height of the box I was able to just divide that value in half in order to center the content using padding. If you don't know the difference between padding margin and border. Look into the box model in css. It is one of the most fundamental concepts you will need to grasp to have a good understanding of css.

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>