问:
Check which one of two buttons has been pressed and pass a value to sharedpreferences
I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.

How do I check which of the two buttons has been pressed?

What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.

Here the first activity where the two buttons are in:

public void imagebutton (){

        ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name2", "Geschlecht");

                editor.clear();
                editor.apply();
                startActivity(new Intent(Akt1.this, Akt2.class));
            }
        });
    }

               //buttonclick mit datapass gemixt

    private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name","Geschlecht");
                editor.commit();

                Intent intent = new Intent (Akt1.this,Akt2.class);
                startActivity(intent);```
</div>
</div>
</p>

<p>And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class Akt6 extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Hiermit Layout mit Activity verbinden
        setContentView(R.layout.activity_akt6);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("Name",null);
        name ="Männlich";

        SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
        String name2 = preferences.getString("Name", "default");
        name2 ="Weiblich";
        //zeige Wert on screen

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);</code>```

答:
What is the problem in my code? I always get the same value in the
  end. So it seems like I always press the same button, which I don't.

1. In your method imagebutton1(), you are storing value for name into different sharedPreferences (myprefs):

```<code>// Akt1
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
</code>```

and trying to get value of name from default sharedPreferences:

```<code>// Akt6
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
</code>```

2. You have used KEY name to store value:

```<code> // Akt1
editor.putString("name","Geschlecht");
</code>```

and getting value by using different KEY Name which is totally wrong.

```<code>// Akt6
String name = preferences.getString("Name", null);
</code>```

How do I check which of the two buttons has been pressed?

SOLUTION:

Use same SharedPreferences to store and retrieve value.

Use same KEY "name" to store and retrieve value for name from SharedPreferences

Update your code as below:

Akt1.java

```<code>public void imageButton (){

    ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("name", "Male");
            editor.commit();

            startActivity(new Intent(Akt1.this, Akt2.class));
        }
    });
}

private void imageButton1 () {
    ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("name", "Female");
            editor.commit();

            startActivity(new Intent(Akt1.this, Akt2.class));
        }
    });
}
</code>```

Akt6.java

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

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

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("name", "default");

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);
    }
}
</code>```

Hope this will help~

Body:
I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.

How do I check which of the two buttons has been pressed?

What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.

Here the first activity where the two buttons are in:

public void imagebutton (){

        ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name2", "Geschlecht");

                editor.clear();
                editor.apply();
                startActivity(new Intent(Akt1.this, Akt2.class));
            }
        });
    }

               //buttonclick mit datapass gemixt

    private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name","Geschlecht");
                editor.commit();

                Intent intent = new Intent (Akt1.this,Akt2.class);
                startActivity(intent);

And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:

public class Akt6 extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Hiermit Layout mit Activity verbinden
        setContentView(R.layout.activity_akt6);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("Name",null);
        name ="Männlich";

        SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
        String name2 = preferences.getString("Name", "default");
        name2 ="Weiblich";
        //zeige Wert on screen

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);

Body:
What is the problem in my code? I always get the same value in the
  end. So it seems like I always press the same button, which I don't.

1. In your method imagebutton1(), you are storing value for name into different sharedPreferences (myprefs):

// Akt1
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);

and trying to get value of name from default sharedPreferences:

// Akt6
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

2. You have used KEY name to store value:

 // Akt1
editor.putString("name","Geschlecht");

and getting value by using different KEY Name which is totally wrong.

// Akt6
String name = preferences.getString("Name", null);

How do I check which of the two buttons has been pressed?

SOLUTION:

Use same SharedPreferences to store and retrieve value.

Use same KEY "name" to store and retrieve value for name from SharedPreferences

Update your code as below:

Akt1.java

public void imageButton (){

    ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("name", "Male");
            editor.commit();

            startActivity(new Intent(Akt1.this, Akt2.class));
        }
    });
}

private void imageButton1 () {
    ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("name", "Female");
            editor.commit();

            startActivity(new Intent(Akt1.this, Akt2.class));
        }
    });
}

Akt6.java

public class Akt6 extends AppCompatActivity {

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

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("name", "default");

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);
    }
}

Hope this will help~


来源: stackexchange

问:
Multiple file attachments to php via ajax
Before you judge me please know that I am not a big pro and just trying to learn how to do things here.

I am trying to create a mailing form with multiple attachments

form code

```<code><div class="file-upload-wrapper">
    <label class="file-field" data-max-files="6">
        <input type="file" name="photos[]" multiple>
            <span>Drag your files here or click to select your files <span>.jpg, .png and .pdf</span></span>
    </label>
    <div class="uploaded-files"></div>
</div>
</code>```

js/jQuery code

```<code>var photos = [];
var data;
$(document).ready ( function() {
    //Documnet Upload Script//
    function fileUpload(obj){
        var dropZone = obj.find('.file-field');
        var fileInput = dropZone.find('input[type="file"]');
        var filesBeen = obj.find('.uploaded-files');
        var maxFiles = Number(dropZone.attr('data-max-files'));

        function highlightDropZone(e){
            if(e.type == 'dragover') dropZone.addClass('highlighted');
            else dropZone.removeClass('highlighted');
            e.preventDefault();
            return false;
        }

        function filesDropped(e){
            highlightDropZone(e);
            var files = e.target.files || e.dataTransfer.files;
            for(var i = 0, file; file = files[i]; i++) {
                if(file.size <= 3000000 && (file.type == "application/pdf" || file.type == "image/jpg" || file.type == "image/jpeg" ||file.type == "image/png")) {
                    photos.push(file);
                    if (file.type == "application/pdf") {
                        var uploaded = filesBeen.prepend('<div><div><img src="images/adobe-acrobat-pdf-file-512.png"></div><span></span></div>');
                        uploaded.find('span').click(function () {
                            $(this).closest('div').animate({width: 0, height: 0}, 200, function () {
                                $(this).remove()
                            });
                        });
                    } else {
                        var fReader = new FileReader();
                        fReader.onloadend = (function(f){
                            return function() {
                                if (maxFiles > Number(filesBeen.children('div').length)) {
                                    var uploaded = filesBeen.prepend('<div><div><img src="' + this.result + '"></div><p><span>' + f.name + '</span></p><span></span></div>');
                                    uploaded.find('span').click(function () {
                                        var me = $(this);
                                        $(this).closest('div').animate({width: 0, height: 0}, 200, function () {
                                            $(this).remove();
                                            me.unbind('click');
                                        });
                                    });
                                }
                            }
                        })(file);
                        fReader.readAsDataURL(file);
                    }
                }else {
                    window.alert("The size of the file is more than 3Mb or format is not supported.");
                }
            }
            console.log(photos);
        }

        dropZone.get(0).addEventListener('dragover', highlightDropZone);
        dropZone.get(0).addEventListener('dragleave', highlightDropZone);
        dropZone.get(0).addEventListener('drop', filesDropped);
        fileInput.get(0).addEventListener('change', filesDropped);
    }

    $('.file-upload-wrapper').each(function(){
        new fileUpload($(this));
    });

    $('.submit-form').click(function(e) {
        e.preventDefault();
        // Store values in variables
        var form = $('form[name="contact-form"]');

        var ip = form.find('input[name=ip]');
        var httpref = form.find('input[name=httpref]');
        var httpagent = form.find('input[name=httpagent]');

        var name = form.find('input[name=name]');
        var email = form.find('input[name=email]');
        var phone = form.find('input[name=phone]');
        var message = form.find('textarea[name=message]');

        var submitted = form.find('input[name=submitted]');
        var visitor = form.find('input[name=visitor]');
        var emails = form.find('input[name=email]').val();

        function validateEmail(email) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
        }

        if (validateEmail(emails)) {
            // Organize data
            data = new FormData();
            data.append('ip', ip.val());
            data.append('httpref', httpref.val());
            data.append('httpagent', httpagent.val());
            data.append('name', name.val());
            data.append('email', email.val());
            data.append('phone', phone.val());
            data.append('message', message.val());
            data.append('submitted', submitted.val());
            data.append('visitor', visitor.val());
            for(var i = 0; i < photos.length; i++){
                data.append('file'+i, photos[i]);
            }

            var request = $.ajax({
                type: "POST",
                dataType: 'script',
                url: "/includes/sendConatctform.php",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (html) {
                    if (html == "true") {
                        form.find('.email-sent').fadeIn(500).delay(4000).fadeOut(500);
                    } else {
                        form.find('.email-error').fadeIn(500).delay(4000).fadeOut(500);
                    }
                },
                error: function (jqXHR, textStatus, error) {
                    alert("Form Error: " + error);
                }
            });
        } else {
            form.find('.email-results').fadeIn(500).delay(4000).fadeOut(500);
        }
        return false;
    });
});
</code>```

What I am trying to do is to receive the attachments in my PHP file for further proceedings.

php code

```<code>$message  = "Date: $todayis \r\n";
$message .= "From: $name ($email) \r\n";
$message .= "Phone: $phone \r\n";
$message .= "Subject: $subject \r\n";
$message .= "Message: $userMessage \r\n";
$message .= "IP Address: $ip \r\n";
$message .= "Browser Info: $httpagent \r\n";
$message .= "Referral: $httpref  \r\n";

foreach($_FILES['photos']['name'] as $file){
    $message .= "Attachments:" .$file['filename'];
}
</code>```

I have tried the suggestion that I have found here Send multiple file attachments to php file using ajax

but it did not help with my situation.

can you please advise?

All help is appreciated

Thank you in advance

答:
Since in your php code you are iterating over $_FILES['photos'], then  you should change in your js code this:

```<code>data.append('file'+i, photos[i]);
</code>```

to

```<code>data.append('photos[]', photos[i]);
</code>```

Update:

Also, in your php code change $file['filename'] here:

```<code>foreach($_FILES['photos']['name'] as $file){
  $message .= "Attachments:" .$file['filename'];
}
</code>```

to just $file:

```<code>foreach($_FILES['photos']['name'] as $file){
  $message .= "Attachments:" . $file;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Before you judge me please know that I am not a big pro and just trying to learn how to do things here.

I am trying to create a mailing form with multiple attachments

form code

        <input type="file" name="photos[]" multiple>
            Drag your files here or click to select your files .jpg, .png and .pdf

js/jQuery code

var photos = [];
var data;
$(document).ready ( function() {
    //Documnet Upload Script//
    function fileUpload(obj){
        var dropZone = obj.find('.file-field');
        var fileInput = dropZone.find('input[type="file"]');
        var filesBeen = obj.find('.uploaded-files');
        var maxFiles = Number(dropZone.attr('data-max-files'));

        function highlightDropZone(e){
            if(e.type == 'dragover') dropZone.addClass('highlighted');
            else dropZone.removeClass('highlighted');
            e.preventDefault();
            return false;
        }

        function filesDropped(e){
            highlightDropZone(e);
            var files = e.target.files || e.dataTransfer.files;
            for(var i = 0, file; file = files[i]; i++) {
                if(file.size <= 3000000 && (file.type == "application/pdf" || file.type == "image/jpg" || file.type == "image/jpeg" ||file.type == "image/png")) {
                    photos.push(file);
                    if (file.type == "application/pdf") {
                        var uploaded = filesBeen.prepend('

');
                        uploaded.find('span').click(function () {
                            $(this).closest('div').animate({width: 0, height: 0}, 200, function () {
                                $(this).remove()
                            });
                        });
                    } else {
                        var fReader = new FileReader();
                        fReader.onloadend = (function(f){
                            return function() {
                                if (maxFiles > Number(filesBeen.children('div').length)) {
                                    var uploaded = filesBeen.prepend('

' + f.name + '

');
                                    uploaded.find('span').click(function () {
                                        var me = $(this);
                                        $(this).closest('div').animate({width: 0, height: 0}, 200, function () {
                                            $(this).remove();
                                            me.unbind('click');
                                        });
                                    });
                                }
                            }
                        })(file);
                        fReader.readAsDataURL(file);
                    }
                }else {
                    window.alert("The size of the file is more than 3Mb or format is not supported.");
                }
            }
            console.log(photos);
        }

        dropZone.get(0).addEventListener('dragover', highlightDropZone);
        dropZone.get(0).addEventListener('dragleave', highlightDropZone);
        dropZone.get(0).addEventListener('drop', filesDropped);
        fileInput.get(0).addEventListener('change', filesDropped);
    }

    $('.file-upload-wrapper').each(function(){
        new fileUpload($(this));
    });

    $('.submit-form').click(function(e) {
        e.preventDefault();
        // Store values in variables
        var form = $('form[name="contact-form"]');

        var ip = form.find('input[name=ip]');
        var httpref = form.find('input[name=httpref]');
        var httpagent = form.find('input[name=httpagent]');

        var name = form.find('input[name=name]');
        var email = form.find('input[name=email]');
        var phone = form.find('input[name=phone]');
        var message = form.find('textarea[name=message]');

        var submitted = form.find('input[name=submitted]');
        var visitor = form.find('input[name=visitor]');
        var emails = form.find('input[name=email]').val();

        function validateEmail(email) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
        }

        if (validateEmail(emails)) {
            // Organize data
            data = new FormData();
            data.append('ip', ip.val());
            data.append('httpref', httpref.val());
            data.append('httpagent', httpagent.val());
            data.append('name', name.val());
            data.append('email', email.val());
            data.append('phone', phone.val());
            data.append('message', message.val());
            data.append('submitted', submitted.val());
            data.append('visitor', visitor.val());
            for(var i = 0; i < photos.length; i++){
                data.append('file'+i, photos[i]);
            }

            var request = $.ajax({
                type: "POST",
                dataType: 'script',
                url: "/includes/sendConatctform.php",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (html) {
                    if (html == "true") {
                        form.find('.email-sent').fadeIn(500).delay(4000).fadeOut(500);
                    } else {
                        form.find('.email-error').fadeIn(500).delay(4000).fadeOut(500);
                    }
                },
                error: function (jqXHR, textStatus, error) {
                    alert("Form Error: " + error);
                }
            });
        } else {
            form.find('.email-results').fadeIn(500).delay(4000).fadeOut(500);
        }
        return false;
    });
});

What I am trying to do is to receive the attachments in my PHP file for further proceedings.

php code

$message  = "Date: $todayis \r\n";
$message .= "From: $name ($email) \r\n";
$message .= "Phone: $phone \r\n";
$message .= "Subject: $subject \r\n";
$message .= "Message: $userMessage \r\n";
$message .= "IP Address: $ip \r\n";
$message .= "Browser Info: $httpagent \r\n";
$message .= "Referral: $httpref  \r\n";

foreach($_FILES['photos']['name'] as $file){
    $message .= "Attachments:" .$file['filename'];
}

I have tried the suggestion that I have found here Send multiple file attachments to php file using ajax

but it did not help with my situation.

can you please advise?

All help is appreciated

Thank you in advance

Body:
Since in your php code you are iterating over $_FILES['photos'], then  you should change in your js code this:

data.append('file'+i, photos[i]);

to

data.append('photos[]', photos[i]);

Update:

Also, in your php code change $file['filename'] here:

foreach($_FILES['photos']['name'] as $file){
  $message .= "Attachments:" .$file['filename'];
}

to just $file:

foreach($_FILES['photos']['name'] as $file){
  $message .= "Attachments:" . $file;
}


问:
Creating Marklogic docker instance in Ubuntu 16.04 exposing the ports
I have created a marklogic instance on Ubuntu 16.04 using a DockerFile. After the marklogic server is started, I try to access admin interface from the port 8000, 8001, 8002 etc, which are exposed in the creation of docker instance, but I encounter issue of server not started or page not found. Has anyone encountered this issue and how to circumvent it.</p>

答:
Try these three steps:

Confirm the Docker container is still running with

docker ps

If there is no container running, you probably need a command in the Dockerfile to keep the container running indefinitely. Try adding the following at the end of your Dockerfile:

CMD tail -f /dev/null

which will keep the container running indefinitely.

In your Dockerfile, confirm the EXPOSE setting contains the three ports you wish to access:

EXPOSE 8000 8001 8002

Confirm that the MarkLogic service is started in a command in the Dockerfile. For example in a default install of MarkLogic 8 on CentOS 7, I start the MarkLogic service in the Dockerfile with

CMD /etc/init.d/MarkLogic start


问:
Trouble installing google assistant on a raspberry pi 3
I am getting the following error when I run google-assistant-demo</p>

```<code>OpenAlsaHandle PcmOpen: No such file or directory
[4571:4583:ERROR:audio_input_processor.cc(756)] Input error
ON_MUTED_CHANGED:
  {'is_muted': False}
ON_START_FINISHED
ON_ASSISTANT_ERROR:
  {'is_fatal': True}
[4571:4586:ERROR:audio_input_processor.cc(756)] Input error
ON_ASSISTANT_ERROR:
  {'is_fatal': True}
</code>```

答: Its an error due to improper alsa.conf configuration. You need to change it according to your audio setup.</p>

Body:
I am getting the following error when I run google-assistant-demo

OpenAlsaHandle PcmOpen: No such file or directory
[4571:4583:ERROR:audio_input_processor.cc(756)] Input error
ON_MUTED_CHANGED:
  {'is_muted': False}
ON_START_FINISHED
ON_ASSISTANT_ERROR:
  {'is_fatal': True}
[4571:4586:ERROR:audio_input_processor.cc(756)] Input error
ON_ASSISTANT_ERROR:
  {'is_fatal': True}


问:
Extract certain amount of factor levels in R
I have a data frame with a column with more than 100 factor levels.

I want to extract rows to make the column just have 50 factor levels, to decrease the calculation time.

How to randomly extract certain amount of factor levels?

答:
To avoid no answer ...

You can use sample to get a random sample of the factor and then use %in% to select the relevant rows of your data.frame.

```<code>ReducedFactors = sample(levels(df$MyFactor), 50)
df[which(df$MyFactor %in% ReducedFactors ), ]
</code>```

Body:
To avoid no answer ...

You can use sample to get a random sample of the factor and then use %in% to select the relevant rows of your data.frame.

ReducedFactors = sample(levels(df$MyFactor), 50)
df[which(df$MyFactor %in% ReducedFactors ), ]


问:
Is there a way to mock an $? return using Pester?
I'm writing tests for a PowerShell application, using Pester.

I have been able to create mocks for most functions, but I haven't been able to mock a function returning the $? variable. I'm currently using it to evaluate the returns from AWS CLI commands.

This is, for example, to mock a failing AWS CLI command return.

Any thoughts?

答:
If you're looking to get mock code which performs the same function as $?, you can use something like this (it is quite limited in terms of how it actually returns if multiple lines are executed at once, etc., and it will likely need to be modified depending on the execution context):

```<code>Function Test-LastCommandError {
    $LastCommand = (History | Select -Last 1).CommandLine
    $LastError = $Error[-1].InvocationInfo.Line
    $LastCommand -eq $LastError
}

1/1#Success
Test-LastCommandError # Returns false

1/0#Error
Test-LastCommandError # Returns true
</code>```

This works for me manually executing each line, but not in an ad-hoc ISE window (since it copy-pastes everything as one command on execute).

ContentLicense: CC BY-SA 4.0

Body:
If you're looking to get mock code which performs the same function as $?, you can use something like this (it is quite limited in terms of how it actually returns if multiple lines are executed at once, etc., and it will likely need to be modified depending on the execution context):

Function Test-LastCommandError {
    $LastCommand = (History | Select -Last 1).CommandLine
    $LastError = $Error[-1].InvocationInfo.Line
    $LastCommand -eq $LastError
}

1/1#Success
Test-LastCommandError # Returns false

1/0#Error
Test-LastCommandError # Returns true

This works for me manually executing each line, but not in an ad-hoc ISE window (since it copy-pastes everything as one command on execute).


问:
How do I protect phone number from bots
I want a phone number which display on public page will be protected. Example converts phone number characters to HTML entities and bots can't grab the number in plain text. Let me know the trick.</p>

答:
Try writing the number using ASCII:
http://www.ascii.cl/htmlcodes.htm</p>

```<code><html>
    <body>112</body>
</html>
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I protect phone number from bots

Body:
Try writing the number using ASCII:
http://www.ascii.cl/htmlcodes.htm

<html>
    <body>&#49;&#49;&#50;</body>
</html>


问:
Merging objects (associative arrays)
What’s the best/standard way of merging two associative arrays in JavaScript?  Does everyone just do it by rolling their own for loop?

答:
Here is the best solution.

```<code>obj1.unshift.apply( obj1, obj2 );
</code>```

Also, obj1 can grow inside a loop without any problem. (lets say obj2 is dynamic)

Title: Merging objects (associative arrays)

Body:
Here is the best solution.

obj1.unshift.apply( obj1, obj2 );

Also, obj1 can grow inside a loop without any problem. (lets say obj2 is dynamic)


问:
Code to convert PostGIS Hex to string
I have PostGis database build on PostSql.
Is there python or any language code to decode postgis hex?

For example,
0102000020E6100000020000007925A437FFFA53C04100AC0C45A14540035E8F61FFFA53C0747BD20945A14540

This is the data I have.

Thanks!

Title: Code to convert PostGIS Hex to string

Body:
You can use the function st_astext directly in PostgreSql.

Using your example, it gives:

select ST_AsText('0102000020E6100000020000007925A437FFFA53C04100AC0C45A14540035E8F61FFFA53C0747BD20945A14540');
-- > LINESTRING(-79.9218272307388 43.2599197234963,-79.9218372249671 43.2599193837877)


问:
Fabric: Answers: purchase flow tracking of `success` bool doesn't work as expected
I'm tracking purchase-related events in an iOS app with Answers (part of Fabric). The Answers docs for purchase flow tracking are very straightforward:

```<code>Answers.logPurchaseWithPrice(13.50,
                  currency: "USD",
                  success: true,
                  itemName: "Answers Shirt",
                  itemType: "Apparel",
                  itemId: "sku-350",
                  customAttributes: nil)
</code>```

The success bool is documented as:

When a Purchase Event has the success attribute set to NO (Objective-C) or false (Swift), it is excluded from revenue charts but included in all other charts and calculations.

I've submitted one full flow of events, through Add Cart, Start Checkout, and Purchase, and for Purchase (logPurchase…) I set success to false, because I took the cancellation route, rather than completing the payment.

However, when I look at Answers' Purchase Funnel, I see a 100% purchase success rate:

That's not quite right! What's the proper Answers tracking call for a user tapping Cancel in my Purchase flow? It doesn't seem to be logPurchaseWithPrice(… success: false…

答:
Mike from Fabric here. Definitely understand the confusion on this, but will aim to clarify it.

If a user hits the event on each step of the funnel, then it would be considered a success regardless of the success attribute. The funnels are intended to function as a what % of your users hit the event triggers that were set within the app to send the data to Answers. If a user hits cancel, then you shouldn't trigger the logPurchase event. I recommend setting the event after the purchase has been confirmed - so on a successful tap or trigger of the final purchase button.

As you mentioned from the documentation, the success attribute only affects the revenue chart and the funnel does not take it into consideration.

Body:
I'm tracking purchase-related events in an iOS app with Answers (part of Fabric). The Answers docs for purchase flow tracking are very straightforward:

Answers.logPurchaseWithPrice(13.50,
                  currency: "USD",
                  success: true,
                  itemName: "Answers Shirt",
                  itemType: "Apparel",
                  itemId: "sku-350",
                  customAttributes: nil)

The success bool is documented as:

When a Purchase Event has the success attribute set to NO (Objective-C) or false (Swift), it is excluded from revenue charts but included in all other charts and calculations.

I've submitted one full flow of events, through Add Cart, Start Checkout, and Purchase, and for Purchase (logPurchase…) I set success to false, because I took the cancellation route, rather than completing the payment.

However, when I look at Answers' Purchase Funnel, I see a 100% purchase success rate:

That's not quite right! What's the proper Answers tracking call for a user tapping Cancel in my Purchase flow? It doesn't seem to be logPurchaseWithPrice(… success: false…


问:
git commit directory
I created a repo and, locally, dragged-and-dropped an existing project directory into the repo. I then did something like git add directory/ and committed it and pushed it. When I look at my repo on github though, all i see is the directory with no subfolders, no content. How do I push all of the files and subfolders of that project to the repo?</p>

答:
Try this:

```<code>$ git add directory/*
</code>```

(or *.h, *.c, and so on).

and then check as Aaronontheweb suggests (with gitk or git status) that the files are included in the staging area. Not only the folder name.

Title: git commit directory

Body:
Try this:

$ git add directory/*

(or *.h, *.c, and so on).

and then check as Aaronontheweb suggests (with gitk or git status) that the files are included in the staging area. Not only the folder name.


问:
How to get text I inputted into textView
```<code>-(void)textViewDidChange:(UITextView *)textView{
    self.textView.text=textView.text;
    self.statusString=textView.text;
}
</code>```

In this method ,it returns self.statusString nil or empty description(when initialized statusString it happens), and self.textView.text is nil too.

How to get the text I inputted into textView?

答:
At first check whether your textView outlet is ok or not.

You don't have to write so much code to get textView's text. I just wrote this code and it's working fine.

```<code>- (IBAction)sendDataToFirstVC:(id)sender {

    self.firstLabel.text = self.textView.text;
}
</code>```

Body:
-(void)textViewDidChange:(UITextView *)textView{
    self.textView.text=textView.text;
    self.statusString=textView.text;
}

In this method ,it returns self.statusString nil or empty description(when initialized statusString it happens), and self.textView.text is nil too.

How to get the text I inputted into textView?

Body:
At first check whether your textView outlet is ok or not.

You don't have to write so much code to get textView's text. I just wrote this code and it's working fine.

- (IBAction)sendDataToFirstVC:(id)sender {

    self.firstLabel.text = self.textView.text;
}


问:
How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?
When I have a link that is wired-up with a jQuery or JavaScript event such as:

```<code><a href="#">My Link</a>
</code>```

How do I prevent the page from scrolling to the top?  When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.

答:
You might want to check your CSS. In the example here: https://css-tricks.com/the-checkbox-hack/ there's position: absolute; top: -9999px;. This is particularly goofy on Chrome, as onclick="whatever" still jumps to the absolute position of the clicked element.

Removing position: absolute; top: -9999px;, for display: none; might help.

Body:
When I have a link that is wired-up with a jQuery or JavaScript event such as:

My Link

How do I prevent the page from scrolling to the top?  When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.


问:
SqlDataReader displaying like fields
When I try to display only distinct values in my DB with SqlDataReader, it is still showing duplicate columns.

```<code>string State = ddlState.SelectedItem.Value;
string City = ddlCities.SelectedItem.Text;

SqlConnection con = new SqlConnection("Data Source=--myDB--;Database=--MyconnectionString--");

SqlCommand cmd = new SqlCommand("Select distinct State, City, ExchangeType, Boid, Bex, Npa, Nxx from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);

if (!string.IsNullOrEmpty(ddlCities.SelectedItem.Text))
{
    exchangesheet.Visible = true;

    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        this.STATE.Text = rdr["State"].ToString();
        this.CITY.Text = rdr["City"].ToString();
        this.ExchangeType.Text = rdr["ExchangeType"].ToString();
        this.BOID.Text += rdr["Boid"].ToString() + ", ";
        this.BEX.Text += rdr["Bex"].ToString() + ", ";
        this.NPA.Text += rdr["Npa"].ToString() + ", ";
        this.NXX.Text += rdr["Nxx"].ToString() + ", ";
    }

    con.Close();
}
else
{
    exchangesheet.Visible = false;
}
</code>```

All queries with += are resulting in duplicate data in the labels, even though I have specified only distinct data to be shown in the SqlCommand query. I apologize if I am not explaining correctly but any help or direction will be much appreciated.

Results when searching a specific state:

```<code>BOID: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
BEX: 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205,
NPA: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
NXX: 212, 214, 226, 238, 244, 250, 251, 252, 254, 262, 263, 278, 279, 290, 298, 307, 313, 314, 320, 321, 322, 323, 324, 326, 328, 380, 397, 402, 403, 408, 414, 421, 423, 437, 444, 445, 453, 458, 502, 520, 533, 536, 545, 558, 583, 591, 592, 595, 599, 682, 714, 731, 733, 776, 780, 781, 783, 786, 787, 788, 791, 798, 801, 802, 803, 808, 822, 823, 824, 833, 836, 841, 854, 856, 868, 870, 871, 873, 876, 879, 913, 916, 917, 923, 925, 929, 930, 933, 939, 940, 941, 942, 943, 945, 949, 951, 956, 957, 967, 968, 969, 970, 972, 977, 978, 979, 980, 981, 982, 983, 985, 987, 988, 989, 991, 995,
</code>```

答: What happens when you replace the += with = ?</p>

Title: SqlDataReader displaying like fields

Body:
When I try to display only distinct values in my DB with SqlDataReader, it is still showing duplicate columns.

string State = ddlState.SelectedItem.Value;
string City = ddlCities.SelectedItem.Text;

SqlConnection con = new SqlConnection("Data Source=--myDB--;Database=--MyconnectionString--");

SqlCommand cmd = new SqlCommand("Select distinct State, City, ExchangeType, Boid, Bex, Npa, Nxx from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);

if (!string.IsNullOrEmpty(ddlCities.SelectedItem.Text))
{
    exchangesheet.Visible = true;

    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        this.STATE.Text = rdr["State"].ToString();
        this.CITY.Text = rdr["City"].ToString();
        this.ExchangeType.Text = rdr["ExchangeType"].ToString();
        this.BOID.Text += rdr["Boid"].ToString() + ", ";
        this.BEX.Text += rdr["Bex"].ToString() + ", ";
        this.NPA.Text += rdr["Npa"].ToString() + ", ";
        this.NXX.Text += rdr["Nxx"].ToString() + ", ";
    }

    con.Close();
}
else
{
    exchangesheet.Visible = false;
}

All queries with += are resulting in duplicate data in the labels, even though I have specified only distinct data to be shown in the SqlCommand query. I apologize if I am not explaining correctly but any help or direction will be much appreciated.

Results when searching a specific state:

BOID: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
BEX: 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205,
NPA: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
NXX: 212, 214, 226, 238, 244, 250, 251, 252, 254, 262, 263, 278, 279, 290, 298, 307, 313, 314, 320, 321, 322, 323, 324, 326, 328, 380, 397, 402, 403, 408, 414, 421, 423, 437, 444, 445, 453, 458, 502, 520, 533, 536, 545, 558, 583, 591, 592, 595, 599, 682, 714, 731, 733, 776, 780, 781, 783, 786, 787, 788, 791, 798, 801, 802, 803, 808, 822, 823, 824, 833, 836, 841, 854, 856, 868, 870, 871, 873, 876, 879, 913, 916, 917, 923, 925, 929, 930, 933, 939, 940, 941, 942, 943, 945, 949, 951, 956, 957, 967, 968, 969, 970, 972, 977, 978, 979, 980, 981, 982, 983, 985, 987, 988, 989, 991, 995,


问:
stylesheets and mobile browsers
I aint sure if I have asked this question in other threads as well ... but my question have still been unanswered ... what I need to know is that while using Opera mini... or browsing site on the mobile.. are there certain restrictions while using HTML or CSS ?? I got totally confused with certain terms like Screen Stylesheets and Handheld Stylesheets... while getting the media type, there was a mention that we gotta use some screen or handheld stylesheets .... depending upon the media type ...  just not sure how else to ask ....</p>

答:
Stylesheets for media=handheld were supposed to be used by mobile browsers, but once browsers became more advanced, browser vendors started ignoring media=handheld, because they can display media=screen now (browser chooses what media it supports).

A more modern and much more flexible approach is to use CSS3 Media Queries that let you set certain styles only when selected criteria match, e.g. minimum screen size. Keep in mind though that mobile browsers report virtual (zoomed out) screen size in width media queries, and device-width is closer to physical size.

Title: stylesheets and mobile browsers


答:
When doing a query with distinct, it will give you the distinct combination of all the selected columns. to accomplish what you want, it would have to be more like this

```<code>SqlCommand cmd = new SqlCommand("Select distinct State from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
...code to collate all the unique values and add to appropriate label...

SqlCommand cmd = new SqlCommand("Select distinct City from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
...code to collate all the unique values and add to appropriate label...

SqlCommand cmd = new SqlCommand("Select distinct Exchange from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
...code to collate all the unique values and add to appropriate label...
</code>```

etc.

There are many other ways to accomplish the same thing as well

For the repeating the multiple queries, you can use something roughly like this

```<code>SqlCommand cmd = new SqlCommand..the query for getting unique state
con.Open();
using ( SqlDataReader rdr = cmd.ExecuteReader())
  {
    while (rdr.Read())
      {
          this.STATE.Text = rdr["State"].ToString();
       }
    }
</code>```

then repeating the others

Title: SqlDataReader displaying like fields

Body:
When doing a query with distinct, it will give you the distinct combination of all the selected columns. to accomplish what you want, it would have to be more like this

SqlCommand cmd = new SqlCommand("Select distinct State from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
...code to collate all the unique values and add to appropriate label...

SqlCommand cmd = new SqlCommand("Select distinct City from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
...code to collate all the unique values and add to appropriate label...

SqlCommand cmd = new SqlCommand("Select distinct Exchange from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
...code to collate all the unique values and add to appropriate label...

etc.

There are many other ways to accomplish the same thing as well

For the repeating the multiple queries, you can use something roughly like this

SqlCommand cmd = new SqlCommand..the query for getting unique state
con.Open();
using ( SqlDataReader rdr = cmd.ExecuteReader())
  {
    while (rdr.Read())
      {
          this.STATE.Text = rdr["State"].ToString();
       }
    }

then repeating the others


问:
Underline selection only in RichTextBox
I am implementing basic formatting functionality (bold, italic, underline) to a RichTextBox in WPF by means of buttons that trigger such functionality (see my previous question if you need some context).

As in this answer, I can apply underlining by something like the following:

```<code>selectionRange.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);
</code>```

The problem is that this seems to apply the underline to the entire Inline. For example, if I have the text "Chuck Norris", and I only highlight "Norris", then the whole of "Chuck Norris" gets highlighted when I click the underline button.

This problem does not apply to bold and italic since I am using TextElement.FontWeightProperty and TextElement.FontStyleProperty, but when using Inline.TextDecorationsProperty I get the problem I just described.

Is there any way to make the underline apply only to the selected text, and not to the entire Inline?

答:
You can use the following:</p>

```<code>richTextBox.Selection.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);
</code>```

Title: Underline selection only in RichTextBox

Body:
I am implementing basic formatting functionality (bold, italic, underline) to a RichTextBox in WPF by means of buttons that trigger such functionality (see my previous question if you need some context).

As in this answer, I can apply underlining by something like the following:

selectionRange.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);

The problem is that this seems to apply the underline to the entire Inline. For example, if I have the text "Chuck Norris", and I only highlight "Norris", then the whole of "Chuck Norris" gets highlighted when I click the underline button.

This problem does not apply to bold and italic since I am using TextElement.FontWeightProperty and TextElement.FontStyleProperty, but when using Inline.TextDecorationsProperty I get the problem I just described.

Is there any way to make the underline apply only to the selected text, and not to the entire Inline?

Body:
You can use the following:

richTextBox.Selection.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);


问:
VBA : Overflow error in multidimensionnal array init
I got a bizzare overflow message error with this code and I can't understand why.
Could you please help ? I am using exactly the same code in another vba module and it works.

```<code>Dim tab_base As Variant
tab_base= Worksheets("Test").Range("A1:AL1492").Value
</code>```

Thanks,

Ismail

答:
You must have some invalid cells in the range. I suspect mostly some cells formatted as Date with a value that is either too large or negative.

To be on the safe side and get the numeric values independent of the format, use the recommended .Value2. So try

```<code>tab_base= Worksheets("Test").Range("A1:AL1492").Value2
</code>```

Then you get everything in the array as either strings or numbers (for date: number). You can later convert numbers to dates if necessary, but you can also check them for errors before.

For example, before converting some cell to a date, something like this:

```<code>Dim d As Date
On Error Resume Next
d = tab_base(i, j)
if Err.Number <> 0 Then ' invalid date, this was a cell causing overflow
</code>```

p.s.: check for example if Err.Number = 6, it means you really had a date overflow (thx Mat's)

Body:
I got a bizzare overflow message error with this code and I can't understand why.
Could you please help ? I am using exactly the same code in another vba module and it works.

Dim tab_base As Variant
tab_base= Worksheets("Test").Range("A1:AL1492").Value

Thanks,

Ismail

Body:
You must have some invalid cells in the range. I suspect mostly some cells formatted as Date with a value that is either too large or negative.

To be on the safe side and get the numeric values independent of the format, use the recommended .Value2. So try

tab_base= Worksheets("Test").Range("A1:AL1492").Value2

Then you get everything in the array as either strings or numbers (for date: number). You can later convert numbers to dates if necessary, but you can also check them for errors before.

For example, before converting some cell to a date, something like this:

Dim d As Date
On Error Resume Next
d = tab_base(i, j)
if Err.Number <> 0 Then ' invalid date, this was a cell causing overflow

p.s.: check for example if Err.Number = 6, it means you really had a date overflow (thx Mat's)


问:
Jest throwing TypeError: Cannot read property 'fetch' of undefined
I'm trying to run some tests with Jest on my react/react-native library (only some business logic inside).

We are testing actions that uses fetch function (polyfill with whatwg-fetch).
I've added whatwg-fetch (thanks to Safari) for react.

Whenever i try to run a test, i'm getting this error:

```<code>TypeError: Cannot read property 'fetch' of undefined

  at node_modules/whatwg-fetch/fetch.js:4:11
  at Object.<anonymous> (node_modules/whatwg-fetch/fetch.js:461:3)
  at Object.<anonymous> (node_modules/jest-expo/src/setup.js:138:416)
</code>```

What can cause this issue? Is there a way in the jest config to avoid this?

Here are some files for debug:

Jest config in package.json

```<code>"jest": {
"preset": "jest-expo",
"moduleFileExtensions": [
  "js",
  "jsx",
  "ts",
  "tsx"
],
"verbose": true,
"transform": {
  "^.+\\.(js|ts|tsx)$": "<rootDir>/node_modules/babel-jest"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
  "\\.snap$",
  "<rootDir>/node_modules/",
  "<rootDir>/dist/"
],
"transformIgnorePatterns": [
  "node_modules/?!react-native"
]
},
</code>```

Webpack config:

```<code>const config = {
entry: [
    'whatwg-fetch',
    __dirname + '/src/index.ts',
],
devtool: 'source-map',
output: {
    path: path.join(__dirname, '/dist'),
    filename: 'index.js',
    library: 'checkinatwork-module',
    libraryTarget: 'umd',
    umdNamedDefine: true,
},
module: {
    loaders: [
        { test: /\.(tsx|ts)?$/, loader: 'ts-loader', exclude: /node_modules/ },
    ],
},
resolve: {
    modules: [
        './src',
        'node_modules',
    ],
    extensions: ['.js', '.ts', '.jsx', '.tsx', 'json'],
},
plugins: [
],
};
</code>```

Test file:

```<code>import expect from 'expect';
import * as actions from '../../src/components/Checkin/checkin.action';
import * as reducers from '../../src/components/Checkin/checkin.reducer';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';

const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);

describe('=> ADD CHECKIN ACTIONS', () => {
  describe('- REQUEST', () => {
    it('Action: ADD_CHECKIN_REQUEST should request addCawCheckin', () => {
      const expectedAction = {
        type: actions.ADD_CHECKIN_REQUEST,
        isFetching: true,
      };
      expect(actions.addCheckinRequest())
        .toEqual(expectedAction);
    });
    it('Reducer: newCheckin should trigger ADD_CHECKIN_REQUEST and initiate loading', () => {
      const expectedState = {
        isFetching: true,
        status: null,
      };
      expect(reducers.newCheckin(reducers.newCheckinDefaultState, actions.addCheckinRequest()))
        .toEqual(expectedState);
    });
  });
</code>```

Action file:

```<code>export const getCheckins = (sessionId, date, url, isRefresh) => {
  const config = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      sessionId: {sessionId},
      date: {date},
    }),
  };

  return dispatch => {
    if (!isRefresh) {
      dispatch(getCheckinsRequest());
    }
    return fetch(url + 'getCAWCheckIns', config)
      .then(response => response.json())
      .then(({ checkins }) => {
        dispatch(getCheckinsSuccess(checkins));
      }).catch(err => {
        dispatch(getCheckinsError('Get checkins failed'));
        console.error('Get checkins failed: ', err);
      });
  };
};
</code>```

Thanks!

答: Upgrading react-native, jest, and babel-jest to the latest versions fixed this issue for us.</p>

Body:
I'm trying to run some tests with Jest on my react/react-native library (only some business logic inside).

We are testing actions that uses fetch function (polyfill with whatwg-fetch).
I've added whatwg-fetch (thanks to Safari) for react.

Whenever i try to run a test, i'm getting this error:

TypeError: Cannot read property 'fetch' of undefined

  at node_modules/whatwg-fetch/fetch.js:4:11
  at Object.<anonymous> (node_modules/whatwg-fetch/fetch.js:461:3)
  at Object.<anonymous> (node_modules/jest-expo/src/setup.js:138:416)

What can cause this issue? Is there a way in the jest config to avoid this?

Here are some files for debug:

Jest config in package.json

"jest": {
"preset": "jest-expo",
"moduleFileExtensions": [
  "js",
  "jsx",
  "ts",
  "tsx"
],
"verbose": true,
"transform": {
  "^.+\\.(js|ts|tsx)$": "<rootDir>/node_modules/babel-jest"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
  "\\.snap$",
  "<rootDir>/node_modules/",
  "<rootDir>/dist/"
],
"transformIgnorePatterns": [
  "node_modules/?!react-native"
]
},

Webpack config:

const config = {
entry: [
    'whatwg-fetch',
    __dirname + '/src/index.ts',
],
devtool: 'source-map',
output: {
    path: path.join(__dirname, '/dist'),
    filename: 'index.js',
    library: 'checkinatwork-module',
    libraryTarget: 'umd',
    umdNamedDefine: true,
},
module: {
    loaders: [
        { test: /\.(tsx|ts)?$/, loader: 'ts-loader', exclude: /node_modules/ },
    ],
},
resolve: {
    modules: [
        './src',
        'node_modules',
    ],
    extensions: ['.js', '.ts', '.jsx', '.tsx', 'json'],
},
plugins: [
],
};

Test file:

import expect from 'expect';
import * as actions from '../../src/components/Checkin/checkin.action';
import * as reducers from '../../src/components/Checkin/checkin.reducer';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';

const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);

describe('=> ADD CHECKIN ACTIONS', () => {
  describe('- REQUEST', () => {
    it('Action: ADD_CHECKIN_REQUEST should request addCawCheckin', () => {
      const expectedAction = {
        type: actions.ADD_CHECKIN_REQUEST,
        isFetching: true,
      };
      expect(actions.addCheckinRequest())
        .toEqual(expectedAction);
    });
    it('Reducer: newCheckin should trigger ADD_CHECKIN_REQUEST and initiate loading', () => {
      const expectedState = {
        isFetching: true,
        status: null,
      };
      expect(reducers.newCheckin(reducers.newCheckinDefaultState, actions.addCheckinRequest()))
        .toEqual(expectedState);
    });
  });

Action file:

export const getCheckins = (sessionId, date, url, isRefresh) => {
  const config = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      sessionId: {sessionId},
      date: {date},
    }),
  };

  return dispatch => {
    if (!isRefresh) {
      dispatch(getCheckinsRequest());
    }
    return fetch(url + 'getCAWCheckIns', config)
      .then(response => response.json())
      .then(({ checkins }) => {
        dispatch(getCheckinsSuccess(checkins));
      }).catch(err => {
        dispatch(getCheckinsError('Get checkins failed'));
        console.error('Get checkins failed: ', err);
      });
  };
};

Thanks!


问:
Combinations of Map<Object, List<Object>>
I have a HashMap<GC, List<RR>> with sample data like:

```<code>key   values

gc1 - rr1
    - rr2
    - rr3

gc2 - rr4
    - rr5

gc3 - rr6
</code>```

And I need to create all possible combinations of RR from different GC like:

```<code>Combination1: rr1, rr4, rr6
Combination2: rr1, rr5, rr6
Combination3: rr2, rr4, rr6
Combination4: rr2, rr5, rr6
Combination5: rr3, rr4, rr6
Combination6: rr3, rr5, rr6
</code>```

What I've tried so far is, as @Sanket Makani suggests, to turn my HashMap<GC, List<RR>> into a List<List<RR>>, and then iterate through all the elements like:

```<code>List<List<RR>> inputList = new ArrayList<List<RR>>();

for (Map.Entry<GC, List<RR>> rrList : Map.entrySet()) {
    inputList.add(rrList.getValue());
}

List<List<RR>> combinationsList = new ArrayList<List<RR>>();

for (List<RR> rrList : inputList) {
    List<RR> rrList1 = new ArrayList<RR>();
    for (RR rr : rrList) {
        rrList1.add(rr);
    }
    combinationsList.add(rrList1);
}
</code>```

This is not working for me, as it groups all the RR inside one GC like:

```<code>Combination1: rr1, rr2, rr3
Combination2: rr4, rr5
Combination3: rr6
</code>```

So my quesiton is, how can I adapt my code to obtain the expected result?

PS: I'm working with Java6 unfortunately, so no lambdas/streams allowed.

PS2: I've seen similar questions, but can't find and exact example of what I'm looking for.

EDIT:

This is my final implementation with @nandsito's answer:

```<code>//this method groups RRs by GC key with a given list
HashMap<GC, List<RR>> GCRRHashMap = groupRRsByGC(list);

List<Map.Entry<GC, List<RR>>> mapEntryList = new ArrayList<Map.Entry<GC, List<RR>>>(GCRRHashMap.entrySet());
List<List<RR>> combinationsList = new ArrayList<List<RR>>();
List<RR> combinations = new ArrayList<RR>();

generateCombinations(mapEntryList, combinations, combinationsList);

private void generateCombinations(
  List<Map.Entry<GC, List<RR>>> mapEntryList,
  List<RR> combinations, List<List<RR>> combinationsList) {

  if (mapEntryList.isEmpty()) {
    combinationsList.add(new ArrayList<RoomStay>(combinations));
    return;
  }

  Map.Entry<GC, List<RR>> entry = mapEntryList.remove(0);

  List<RR> entryValue = new ArrayList<RR>(entry.getValue());

  while (!entryValue.isEmpty()) {

    RR rr = entryValue.remove(0);

    combinations.add(rr);

    generateCombinations(mapEntryList, combinations, combinationsList);

    combinations.remove(combinations.size() - 1);
  }

  mapEntryList.add(0, entry);

}
</code>```

答:
All you really need to do is work through an incrementing index list:

```<code>0,0,0
0,1,0
1,0,0
1,1,0
2,0,0
... etc.
</code>```

It should be obvious how to translate each of those rows into to values from your data structure. e.g. 0,0,0 maps to rr1, rr4, rr6. This will involve converting the map into a list so that indexes are consistent.

It's very much like a normal base-b count where you increment the rightmost column and if it overflows, set to zero and increment the next one. The only difference is that each column overflows at a different number.

So:

```<code>boolean increment(int[] indexes) {
   int column = 0;
   while(true) {
      indexes[column]++;
      if(indexes[column] <  numberOfRRsInColumn(column)) {
         return true;  // finished
      }
      indexes[column]=0;
      column++;
      if(column = indexes.length) {
         return false; // can't increment, no more.
      }
   }
}
</code>```

This implementation uses indexes[0] as the "rightmost" column. I've glossed over numberOfRRsInColumn(), but it should be pretty obvious how to do it.

Then:

```<code>int[] indexes = new int[mapsize];
do {
    output(translate(map, indexes));
} while (increment(indexes));
</code>```

Body:
I have a HashMap<GC, List<RR>> with sample data like:

key   values

gc1 - rr1
    - rr2
    - rr3

gc2 - rr4
    - rr5

gc3 - rr6

And I need to create all possible combinations of RR from different GC like:

Combination1: rr1, rr4, rr6
Combination2: rr1, rr5, rr6
Combination3: rr2, rr4, rr6
Combination4: rr2, rr5, rr6
Combination5: rr3, rr4, rr6
Combination6: rr3, rr5, rr6

What I've tried so far is, as @Sanket Makani suggests, to turn my HashMap<GC, List<RR>> into a List<List<RR>>, and then iterate through all the elements like:

List<List<RR>> inputList = new ArrayList<List<RR>>();

for (Map.Entry<GC, List<RR>> rrList : Map.entrySet()) {
    inputList.add(rrList.getValue());
}

List<List<RR>> combinationsList = new ArrayList<List<RR>>();

for (List<RR> rrList : inputList) {
    List<RR> rrList1 = new ArrayList<RR>();
    for (RR rr : rrList) {
        rrList1.add(rr);
    }
    combinationsList.add(rrList1);
}

This is not working for me, as it groups all the RR inside one GC like:

Combination1: rr1, rr2, rr3
Combination2: rr4, rr5
Combination3: rr6

So my quesiton is, how can I adapt my code to obtain the expected result?

PS: I'm working with Java6 unfortunately, so no lambdas/streams allowed.

PS2: I've seen similar questions, but can't find and exact example of what I'm looking for.

EDIT:

This is my final implementation with @nandsito's answer:

//this method groups RRs by GC key with a given list
HashMap<GC, List<RR>> GCRRHashMap = groupRRsByGC(list);

List<Map.Entry<GC, List<RR>>> mapEntryList = new ArrayList<Map.Entry<GC, List<RR>>>(GCRRHashMap.entrySet());
List<List<RR>> combinationsList = new ArrayList<List<RR>>();
List<RR> combinations = new ArrayList<RR>();

generateCombinations(mapEntryList, combinations, combinationsList);

private void generateCombinations(
  List<Map.Entry<GC, List<RR>>> mapEntryList,
  List<RR> combinations, List<List<RR>> combinationsList) {

  if (mapEntryList.isEmpty()) {
    combinationsList.add(new ArrayList<RoomStay>(combinations));
    return;
  }

  Map.Entry<GC, List<RR>> entry = mapEntryList.remove(0);

  List<RR> entryValue = new ArrayList<RR>(entry.getValue());

  while (!entryValue.isEmpty()) {

    RR rr = entryValue.remove(0);

    combinations.add(rr);

    generateCombinations(mapEntryList, combinations, combinationsList);

    combinations.remove(combinations.size() - 1);
  }

  mapEntryList.add(0, entry);

}

Body:
All you really need to do is work through an incrementing index list:

0,0,0
0,1,0
1,0,0
1,1,0
2,0,0
... etc.

It should be obvious how to translate each of those rows into to values from your data structure. e.g. 0,0,0 maps to rr1, rr4, rr6. This will involve converting the map into a list so that indexes are consistent.

It's very much like a normal base-b count where you increment the rightmost column and if it overflows, set to zero and increment the next one. The only difference is that each column overflows at a different number.

So:

boolean increment(int[] indexes) {
   int column = 0;
   while(true) {
      indexes[column]++;
      if(indexes[column] <  numberOfRRsInColumn(column)) {
         return true;  // finished
      }
      indexes[column]=0;
      column++;
      if(column = indexes.length) {
         return false; // can't increment, no more.
      }
   }
}

This implementation uses indexes[0] as the "rightmost" column. I've glossed over numberOfRRsInColumn(), but it should be pretty obvious how to do it.

Then:

int[] indexes = new int[mapsize];
do {
    output(translate(map, indexes));
} while (increment(indexes));


问:
batch file bcp command
Stuck with a simple batch file that runs a bcp command.
I need this batch file to loop thru a txt file that contains the tables names.

Here is what I have so far

```<code>set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hour%%min%%secs%
set filename=%1
bcp TABLE.dbo.%1 OUT C:\temp\%filename%_%dt%.dat -n -T
</code>```

I like the %1 come from input.txt file that might have 50 table names.

Thank you for your help

答:
I wouldn't use the locale/user settings dependent date/time variables but the
wmic os get LocalDateTime command which misses only the underscore between date and time.

```<code>@Echo off
For /f "delims=." %%A in ('wmic os get LocalDateTime^|find "."') do Set DT=%%A
for /f "delims=" %%F in (%1) do (
    bcp TABLE.dbo.%%F OUT "C:\temp\%%F_%DT:~0,8%_%DT:~8,6%.dat" -n -T
)
</code>```

Title: batch file bcp command

Body:
Stuck with a simple batch file that runs a bcp command.
I need this batch file to loop thru a txt file that contains the tables names.

Here is what I have so far

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hour%%min%%secs%
set filename=%1
bcp TABLE.dbo.%1 OUT C:\temp\%filename%_%dt%.dat -n -T

I like the %1 come from input.txt file that might have 50 table names.

Thank you for your help

Body:
I wouldn't use the locale/user settings dependent date/time variables but the
wmic os get LocalDateTime command which misses only the underscore between date and time.

@Echo off
For /f "delims=." %%A in ('wmic os get LocalDateTime^|find "."') do Set DT=%%A
for /f "delims=" %%F in (%1) do (
    bcp TABLE.dbo.%%F OUT "C:\temp\%%F_%DT:~0,8%_%DT:~8,6%.dat" -n -T
)


问:
How to replace such text
I have a lot of file and I have to replace such text:

```<code><script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</code>```

I tried with grep like:

```<code>cat filename | sed '<script type=\"text\/javascript\"\nsrc=\"http:\/\/pagead2\.googlesyndication\.com\/pagead\/show_ads\.js\">\n<\/script>'
</code>```

But this won't work, any ideas?

答:
this uses sed across several lines, replace BLAH with whatever you want to search for and it will be replaced with nothing</p>

```<code>find . -type f -exec sed -i -n '1h;1!H;${;g;s/BLAH//g;p}' {} \;
</code>```

Title: How to replace such text

Body:
I have a lot of file and I have to replace such text:

I tried with grep like:

cat filename | sed '

Body:
this uses sed across several lines, replace BLAH with whatever you want to search for and it will be replaced with nothing

find . -type f -exec sed -i -n '1h;1!H;${;g;s/BLAH//g;p}' {} \;


问:
jQuery .find() method - searching within string converted to jquery object

var myHTML = '

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

';

var obj = $(myHTML).get(0);
var totalCount = $(obj).find('.infoWindowParagraph').length;

console.log('Total p.infoWindowParagraph tags in the FIRST mapInfoWindow div is : ' + totalCount);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

So I have a HTML string that is similar to the following, and I'm trying to get a count of the .infoWindowParagraph tags in the FIRST .mapInfoWindow div.  For whatever reason, it's not working as I expect and I'm not sure why.

HTML

```<code><div class="mapInfoWindow">
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
</div>
<div class="mapInfoWindow">
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
</div>
<div class="mapInfoWindow">
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
</div>
</code>```

jQuery/JavaScript

```<code>var testObj = $([string from above]);
console.log(testObj.find('.mapInfoWindow').find('.infoWindowParagraph').length);

-- returns 0 every time should return 4
-- also tried below trying to focus on first index (first instance of mapInfoWindow div in object returned)

var testObj = $([string from above]).get(0).find('.infoWindowParagraph').length);

-- still returns 0
</code>```

update

Well damn, I got it working now.  Sorry SO for the time-wasting here, overlooked the obvious!

答:
The issue is that you are trying to select ".mapInfoWindow" and that is the actual object, you can only do .find() on descendants nodes.

Try:testObj.find('.infoWindowParagraph').length

That will work!

Body:
var myHTML = '

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

';

var obj = $(myHTML).get(0);
var totalCount = $(obj).find('.infoWindowParagraph').length;

console.log('Total p.infoWindowParagraph tags in the FIRST mapInfoWindow div is : ' + totalCount);

So I have a HTML string that is similar to the following, and I'm trying to get a count of the .infoWindowParagraph tags in the FIRST .mapInfoWindow div.  For whatever reason, it's not working as I expect and I'm not sure why.

HTML

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

jQuery/JavaScript

var testObj = $([string from above]);
console.log(testObj.find('.mapInfoWindow').find('.infoWindowParagraph').length);

-- returns 0 every time should return 4
-- also tried below trying to focus on first index (first instance of mapInfoWindow div in object returned)

var testObj = $([string from above]).get(0).find('.infoWindowParagraph').length);

-- still returns 0

update

Well damn, I got it working now.  Sorry SO for the time-wasting here, overlooked the obvious!


问:
Angular $http GET pass authorization
Is it possible to pass a user and password to basic auth in AngularJS? I am using a $http to make the request :

```<code>  var urlsave = myurl;
  $http({method: 'GET', url: urlsave}).success(function(data) {
      console.log(data);
  })
</code>```

This is the response :

```<code>Status Code:401 Unauthorized
</code>```

I don't have access to the back end but there is no CORS, i just need to pass it my username and password

答:
Yes you can pass username and password if you know username and password.

for example : http://username:password@domain.com/api/something

Title: Angular $http GET pass authorization

Body:
Is it possible to pass a user and password to basic auth in AngularJS? I am using a $http to make the request :

  var urlsave = myurl;
  $http({method: 'GET', url: urlsave}).success(function(data) {
      console.log(data);
  })

This is the response :

Status Code:401 Unauthorized

I don't have access to the back end but there is no CORS, i just need to pass it my username and password


问:
NameError: name 'reload' is not defined
I'm using python 3.2.2. When I write a simple program, I meet the problem.

```<code>>>> reload(recommendations)
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    reload(recommendations)
NameError: name 'reload' is not defined
</code>```

How should I do it?

答:
An update to @Gareth Latty's answer. imp was depreciated in Python 3.4. Now you want importlib.reload().

```<code>from importlib import reload
</code>```

Title: NameError: name 'reload' is not defined

Body:
I'm using python 3.2.2. When I write a simple program, I meet the problem.

>>> reload(recommendations)
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    reload(recommendations)
NameError: name 'reload' is not defined

How should I do it?

Body:
An update to @Gareth Latty's answer. imp was depreciated in Python 3.4. Now you want importlib.reload().

from importlib import reload


问:
Is it possible to encrypt the username and password in the connection string in the web.config file (Visual Studio 2015, SQL Server 2014)
So I have a connection string labeled as:

```<code><connectionStrings>
    <add name="TBL_ClassServices"
         connectionString="Server=(localdb)\MSSQLLocalDB; database=Assignment1; User Id=test; Password=test"
         providerName="System.data.sqlclient" />
</connectionStrings>
</code>```

I just want to encrypt the User Id and the Password without encrypting the whole connection string itself.  Is it possible, and if so, how would you encrypt it, and then decrypt it using aspx.cs (C# back-end) code.

Thanks

答:
I would suggest using a separate program to set the encrypted string into the config file and decrypt the string in your c# code whenever you need to read the connection string. Here is a helpful post for accomplishing this:
Encrypt and decrypt a string</p>

Body:
So I have a connection string labeled as:

<connectionStrings>
    <add name="TBL_ClassServices"
         connectionString="Server=(localdb)\MSSQLLocalDB; database=Assignment1; User Id=test; Password=test"
         providerName="System.data.sqlclient" />
</connectionStrings>

I just want to encrypt the User Id and the Password without encrypting the whole connection string itself.  Is it possible, and if so, how would you encrypt it, and then decrypt it using aspx.cs (C# back-end) code.

Thanks


问:
Get referrer after installing app from Android Market
I am trying to register a Broadcast Receiver that catches "com.android.vending.INSTALL_REFERRER" intents launched by Android after an app is installed from the Market.

I am following the details here: http://code.google.com/mobile/analytics/docs/android/#referrals

However, I cannot use Google Analytics so I have created my own solution. I have added the following to my manifest file:

```<code><receiver android:name="com.test.Receiver" android:exported="true">
<intent-filter>
    <action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
</code>```

and created a basic BroadcastReceiver class:

```<code>public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle extras = intent.getExtras();
        String referrerString = extras.getString("referrer");

        Log.w("TEST", "Referrer is: " + referrerString);
    }
}
</code>```

However, when the app is installed the receiver doesn't seem to catch the Intent (if the Intent is even broadcast?) and I get no logging output.

Am I going wrong somewhere or is the Market no longer launching these Intents when an app is installed?

答:
I would try to help who, like me, fails to make install_referrer work and who don't find ANY useful information about these features.

Notes:

The intent com.android.vending.INSTALL_REFERRER will be caught
during the install process, not when the application starts for the
first time.

The referrer ...extras.getString("referrer").. is fixed but the contents can be any string value that respect the http get syntax ...referrer=thatsthevalue&thisisnot=xxx

The above code is okay, just some explanations to complete the info:

Android Manifest. The <receiver> tags must be inside the
<application> tags.

The correct url to link the market is not the results of the famous google forms in sdk

but this one

http://market.android.com/details?id=your.application.package.name&referrer=my_referrer_finally_works_fine

Obviously, you need to follow the link from the mobile device and the only way for a complete test is to publish a test application in the market.

And a final and personal note.

I don't understand why those info are omitted completely and i hope that Google will act for detailing it.

Body:
I am trying to register a Broadcast Receiver that catches "com.android.vending.INSTALL_REFERRER" intents launched by Android after an app is installed from the Market.

I am following the details here: http://code.google.com/mobile/analytics/docs/android/#referrals

However, I cannot use Google Analytics so I have created my own solution. I have added the following to my manifest file:

<receiver android:name="com.test.Receiver" android:exported="true">
<intent-filter>
    <action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>

and created a basic BroadcastReceiver class:

public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle extras = intent.getExtras();
        String referrerString = extras.getString("referrer");

        Log.w("TEST", "Referrer is: " + referrerString);
    }
}

However, when the app is installed the receiver doesn't seem to catch the Intent (if the Intent is even broadcast?) and I get no logging output.

Am I going wrong somewhere or is the Market no longer launching these Intents when an app is installed?