问:
keytool to generate keystore for android APK not working
When I generate a private key (for signing apps) using this command:

keytool -genkey -v -keystore myappname.keystore -alias myappname -keyalg RSA -keysize 2048 -validity 10000

... I get asked a series of questions by keytool:

What is your first and last name?
What is the name of your organizational unit?
What is the name of your organization?
What is the name of your City or Locality?
What is the name of your State or Province?
What is the two-letter country code for this unit?

After I answer all questions, I get prompted again in an infinite loop, what am I doing wrong?

I use this sample here:
https://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/publishing_an_application/part_2_-_signing_the_android_application_package/visual-studio-xa-4.2.6-to-6.1/

答:
When keytool asks

Is CN=..., OU=..., O=..., L=..., ST=..., C=... correct?
  [no]:
```

<p>you have to answer</p>

<pre class="lang-none prettyprint-override"><code>yes
</code>```

Body:
When keytool asks

Is CN=..., OU=..., O=..., L=..., ST=..., C=... correct?
  [no]:

you have to answer

yes


来源: stackexchange

问:
Python: Convert mono wave file to stereo
I am looking to convert a wave file from mono to stereo in Python. At the end there should be two identical channels right and left having the mono channel information. My code does not work. I get only the left channel with the input information, the right channel is empty. Any suggestions?</p>

```<code>import struct, wave
import numpy as np

def make_stereo(file1, output):
    def everyOther (v, offset=0):
        return [v[i] for i in range(offset, len(v), 2)]
    ifile = wave.open(file1)
    print ifile.getparams()
    # (1, 2, 44100, 2013900, 'NONE', 'not compressed')
    (nchannels, sampwidth, framerate, nframes, comptype, compname) = ifile.getparams()
    frames = ifile.readframes(nframes * nchannels)
    ifile.close()
    out = struct.unpack_from("%dh" % nframes * nchannels, frames)
    # Convert 2 channels to numpy arrays
    if nchannels == 2:
        left = np.array(list(everyOther(out, 0)))
        right = np.array(list(everyOther(out, 1)))
    else:
        left = np.array(out)
        right = left
    ofile = wave.open(output, 'w')
    ofile.setparams((2, sampwidth, framerate, nframes, comptype, compname))
    ofile.writeframes(left.tostring())
    # ofile.writeframes(right.tostring())
    ofile.close()

make_stereo("Input.wav", "Output.wav")
</code>```

答:
Using numpy for this is the proverbial elephant gun to shoot a fly, except, perhaps, if you are having performance problems.

array is easy to reason about and work with.  I'm not at my audio computer, but a translation of your program to use array should look something like this:

```<code>import wave, array

def make_stereo(file1, output):
    ifile = wave.open(file1)
    print ifile.getparams()
    # (1, 2, 44100, 2013900, 'NONE', 'not compressed')
    (nchannels, sampwidth, framerate, nframes, comptype, compname) = ifile.getparams()
    assert comptype == 'NONE'  # Compressed not supported yet
    array_type = {1:'B', 2: 'h', 4: 'l'}[sampwidth]
    left_channel = array.array(array_type, ifile.readframes(nframes))[::nchannels]
    ifile.close()

    stereo = 2 * left_channel
    stereo[0::2] = stereo[1::2] = left_channel

    ofile = wave.open(output, 'w')
    ofile.setparams((2, sampwidth, framerate, nframes, comptype, compname))
    ofile.writeframes(stereo.tostring())
    ofile.close()

make_stereo("Input.wav", "Output.wav")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am looking to convert a wave file from mono to stereo in Python. At the end there should be two identical channels right and left having the mono channel information. My code does not work. I get only the left channel with the input information, the right channel is empty. Any suggestions?

import struct, wave
import numpy as np

def make_stereo(file1, output):
    def everyOther (v, offset=0):
        return [v[i] for i in range(offset, len(v), 2)]
    ifile = wave.open(file1)
    print ifile.getparams()
    # (1, 2, 44100, 2013900, 'NONE', 'not compressed')
    (nchannels, sampwidth, framerate, nframes, comptype, compname) = ifile.getparams()
    frames = ifile.readframes(nframes * nchannels)
    ifile.close()
    out = struct.unpack_from("%dh" % nframes * nchannels, frames)
    # Convert 2 channels to numpy arrays
    if nchannels == 2:
        left = np.array(list(everyOther(out, 0)))
        right = np.array(list(everyOther(out, 1)))
    else:
        left = np.array(out)
        right = left
    ofile = wave.open(output, 'w')
    ofile.setparams((2, sampwidth, framerate, nframes, comptype, compname))
    ofile.writeframes(left.tostring())
    # ofile.writeframes(right.tostring())
    ofile.close()

make_stereo("Input.wav", "Output.wav")

Body:
Using numpy for this is the proverbial elephant gun to shoot a fly, except, perhaps, if you are having performance problems.

array is easy to reason about and work with.  I'm not at my audio computer, but a translation of your program to use array should look something like this:

import wave, array

def make_stereo(file1, output):
    ifile = wave.open(file1)
    print ifile.getparams()
    # (1, 2, 44100, 2013900, 'NONE', 'not compressed')
    (nchannels, sampwidth, framerate, nframes, comptype, compname) = ifile.getparams()
    assert comptype == 'NONE'  # Compressed not supported yet
    array_type = {1:'B', 2: 'h', 4: 'l'}[sampwidth]
    left_channel = array.array(array_type, ifile.readframes(nframes))[::nchannels]
    ifile.close()

    stereo = 2 * left_channel
    stereo[0::2] = stereo[1::2] = left_channel

    ofile = wave.open(output, 'w')
    ofile.setparams((2, sampwidth, framerate, nframes, comptype, compname))
    ofile.writeframes(stereo.tostring())
    ofile.close()

make_stereo("Input.wav", "Output.wav")


问:
I can't fire terminate callback on exiting iex -S mix
I have an application, which uses Application module, and also has an GenServer instance running. This GenServer module has a terminate callback.

The callback works fine if I force some error happen inside server instance, but doesn't fire if I abort the iex -S mix session using Ctrl-C a or by just closing console window (it should write into some file).

I've tried putting this in init():

```<code>Process.flag(:trap_exit, true)
</code>```

and also calling stop/1 in the main module:

```<code>def stop(state) do
  IO.puts "something" #never shown
  GenServer.stop(pid) #doesn't seem to work
end
</code>```

答:
From Saša Jurić’s post:

There is no way of catching abrupt BEAM OS process exits from within. It's a self-defining property: the BEAM process terminates suddenly, so it can't run any code (since it terminated)

Hence, if BEAM is brutally terminated, the callback will not be invoked.

So one solution is to not exit the session using Ctrl-C. Instead, you can try calling :init.stop which should gracefully shut down the supervision tree.

Body:
I have an application, which uses Application module, and also has an GenServer instance running. This GenServer module has a terminate callback.

The callback works fine if I force some error happen inside server instance, but doesn't fire if I abort the iex -S mix session using Ctrl-C a or by just closing console window (it should write into some file).

I've tried putting this in init():

Process.flag(:trap_exit, true)

and also calling stop/1 in the main module:

def stop(state) do
  IO.puts "something" #never shown
  GenServer.stop(pid) #doesn't seem to work
end


问:
Update array in a file
I have an include with a single array in it that holds 3 instructions; a "y/n" switch and a start and end date. The include meetingParams.php looks like this:

```<code><?php
$regArray = array("n","2018-03-03","2018-03-07");
?>
</code>```

I want to update those array values from time to time using a web based form. Where I get stuck is finding the correct syntax to do that. Right now I have the following:

```<code>$registration = $_POST['registration'];
$startMeeting = $_POST['startMeeting'];
$endMeeting = $_POST['endMeeting'];

$replace = array($registration, $startMeeting, $endMeeting);
$search = file_get_contents('includes/meetingParams.php');
$parsed = preg_replace('^$regArray.*$', $replace, $search);

file_put_contents("includes/meetingParams.php", $parsed);
</code>```

When I run this code, the file meetingParams.php get's replaced with an empty file. What am I missing?

答:
Try this.

include_once "includes/meetingParams.php";

$registration = $_POST['registration'];
$startMeeting = $_POST['startMeeting'];
$endMeeting = $_POST['endMeeting'];

$regArray = array($registration, $startMeeting, $endMeeting);
```

Explanation

There is no need to use file_get_contents since you are using a PHP file you can simply include it.

What that means is that you are placing that file inside your script. Then there is no need to use RegEx to replace the array, just reassign its value.

Title: Update array in a file

Body:
I have an include with a single array in it that holds 3 instructions; a "y/n" switch and a start and end date. The include meetingParams.php looks like this:

<?php
$regArray = array("n","2018-03-03","2018-03-07");
?>

I want to update those array values from time to time using a web based form. Where I get stuck is finding the correct syntax to do that. Right now I have the following:

$registration = $_POST['registration'];
$startMeeting = $_POST['startMeeting'];
$endMeeting = $_POST['endMeeting'];

$replace = array($registration, $startMeeting, $endMeeting);
$search = file_get_contents('includes/meetingParams.php');
$parsed = preg_replace('^$regArray.*$', $replace, $search);

file_put_contents("includes/meetingParams.php", $parsed);

When I run this code, the file meetingParams.php get's replaced with an empty file. What am I missing?

Body:
Try this.

include_once "includes/meetingParams.php";

$registration = $_POST['registration'];
$startMeeting = $_POST['startMeeting'];
$endMeeting = $_POST['endMeeting'];

$regArray = array($registration, $startMeeting, $endMeeting);

Explanation

There is no need to use file_get_contents since you are using a PHP file you can simply include it.

What that means is that you are placing that file inside your script. Then there is no need to use RegEx to replace the array, just reassign its value.


问:
Accessing array elements using the associative index and numbered index
Is it possible to define an array where I can access the elements via their string and numeric index?</p>

答:
martswite's answer is correct, although if you've already got an associative array it may not solve your problem. The following is an ugly hack to work around this - and should be avoided at all cost:

```<code>$a = array(
'first' => 1,
'second' => 2,
'third' => 3
 );
 $b=array_values($a);

 print $b[2];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
martswite's answer is correct, although if you've already got an associative array it may not solve your problem. The following is an ugly hack to work around this - and should be avoided at all cost:

$a = array(
'first' => 1,
'second' => 2,
'third' => 3
 );
 $b=array_values($a);

 print $b[2];


问:
Understanding char * to int * conversion and its meaning
I have the following simple piece of code,

```<code>unsigned long the_function(const char* p){
        int* ip = (int*)p;
        printf("%d\n",ip);
}
</code>```

I know that the first line cast is meaning less but that the code given to me.

Now when i just pass "a" to the function i get the constant output

```<code>4196024
</code>```

could someone explain to me what is the meaning.

答: It's printing the address of the string. </p>

Body:
I have the following simple piece of code,

unsigned long the_function(const char* p){
        int* ip = (int*)p;
        printf("%d\n",ip);
}

I know that the first line cast is meaning less but that the code given to me.

Now when i just pass "a" to the function i get the constant output

4196024

could someone explain to me what is the meaning.


问:
Syntax error on simple if condition (if partychoice = R:)
New programmer, working in python 2.7.

With this code, I get a syntax error in the line 'if partychoice = R, stating the '=' is invalid syntax. How come it won;t let me assign the variable.

Also, I'm sure there are tons of other errors, but I have to start somewhere.

```<code>print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input(str ('Press Y to continue:'))
print 'Great, lets get started!'
partychoice = raw_input (str("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat."))
if partychoice = R:
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input (str("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws'))
    if replegchoice = A or a
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice = L or l
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice = AW, aw, Aw, or AW
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice = H or h
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice = S or s
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'
</code>```

Thanks everyone.

答:
Change the line to

```<code>if partychoice == 'R':
</code>```

First you need to use two '=' characters. One '=' sets a variable, two compares for equality.

Second you want to compare the variable partychoice to the string "R" so you need quotes. Without quotes it thinks you're comparing a reference to another object.

Body:
New programmer, working in python 2.7.

With this code, I get a syntax error in the line 'if partychoice = R, stating the '=' is invalid syntax. How come it won;t let me assign the variable.

Also, I'm sure there are tons of other errors, but I have to start somewhere.

print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input(str ('Press Y to continue:'))
print 'Great, lets get started!'
partychoice = raw_input (str("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat."))
if partychoice = R:
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input (str("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws'))
    if replegchoice = A or a
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice = L or l
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice = AW, aw, Aw, or AW
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice = H or h
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice = S or s
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'

Thanks everyone.

Body:
Change the line to

if partychoice == 'R':

First you need to use two '=' characters. One '=' sets a variable, two compares for equality.

Second you want to compare the variable partychoice to the string "R" so you need quotes. Without quotes it thinks you're comparing a reference to another object.


问:
jQuery hold form submit until "continue" button pressed
I am trying to submit a form, which I have had working, but have now modified it to include a modal jQuery UI box, so that it won't submit until the user presses "continue". I've had various problems with this, including getting the form to hold until that button is pressed, but I think I have found a solution to that, but implementing it, I am getting a SyntaxError which I can't find the source of.

With the help of kevin B managed to find the answer was the form was submitting, but the returned JSON response wasn't quite formatted right. The response was that the form wasn't being submitted, so that problem is still occurring.

So updated the code with the provided feedback, now need to find out why the form isnt submitting. I know its something to do with the 2nd function isnt recognising the submit button has been pressed, so need to know how to submit that form data without the form needing to be submitted again.

Below is the new code:

```<code>function submitData() {
$("#submitProvData").submit(function(event) {
    event.preventDefault();
    var gTotal, sTotal, dfd;
    var dfd = new $.Deferred();
    $('html,body').animate({ scrollTop: 0 }, 'fast');
    $("#submitProvData input").css("border", "1px solid #aaaaaa");
    $("#submitProvData input[readonly='readonly']").css("border", "none");
    sTotal = $('#summaryTotal').val();
    gTotal = $('#gptotal').val();
    if(gTotal !== 'sTotal'){
        $("#newsupinvbox").append('<div id="newsupinvdiagbox" title="Warning - Totals do not match" class="hidden"><p>Press "Continue", to submit the invoice flagged for attention.</p> <br /><p class="italic">or</p><br /> <p>Press "Correct" to correct the discrepancy.</p></div>') //CREATE DIV
        //SET
        $("#newsupinvdiagbox").dialog({
            resizable: false,
            autoOpen:false,
            modal: true,
            draggable: false,
            width:380,
            height:240,
            closeOnEscape: false,
            position: ['center',20],
            buttons: {
                'Continue': function() {
                    $(this).dialog('close');
                    reData();
                }, // end continue button
                'Correct': function() {
                    $(this).dialog('close');
                        return false;
                    } //end cancel button
                }//end buttons
            });//end dialog
            $('#newsupinvdiagbox').dialog('open');
        }
        return false;
    });
}

function reData() {
    console.log('submitted');
    $("#submitProvData").submit(function(resubmit){
        console.log('form submit');
        var formData;
        formData = new FormData($(this)[0]);
        $.ajax({
            type: "POST",
            url: "functions/invoicing_upload_provider.php",
            data: formData,
            async: false,
            success: function(result) {
                $.each($.parseJSON(result), function(item, value){
                    if(item == 'Success'){
                        $('#newsupinv_window_message_success_mes').html('The provider invoice was uploaded successfully.');
                        $('#newsupinv_window_message_success').fadeIn(300, function (){
                            reset();
                        }).delay(2500).fadeOut(700);
                    } else if(item == 'Error'){
                        $('#newsupinv_window_message_error_mes').html(value);
                        $('#newsupinv_window_message_error').fadeIn(300).delay(3000).fadeOut(700);
                    } else if(item == 'Warning'){
                        $('#newsupinv_window_message_warning_mes').html(value);
                        $('#newsupinv_window_message_warning').fadeIn(300, function (){
                            reset();
                        }).delay(2500).fadeOut(700);
                    }
                });
            },
            error: function() {
                $('#newsupinv_window_message_error_mes').html("An error occured, the form was not submitted");
                $('#newsupinv_window_message_error').fadeIn(300);
                $('#newsupinv_window_message_error').delay(3000).fadeOut(700);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
}
</code>```

答:
A complete system to break form and post with jquery/ajax</p>

```<code>$(document).ready(function(e) {
$('#form_sendemail').submit(function(e) {
$.ajax({
  url: 'sendmail.php',
  type: 'POST',
  data: $(this).serialize(),
  dataType: 'json',
  beforeSend: function (XMLHttpRequest) {
    //
    $('#form_sendemail .has-error').removeClass('has-error');
    $('#form_sendemail .help-block').html('').hide();
    $('#form_message').removeClass('alert-success').html('');
  },
  success: function( json, textStatus ) {
    if( json.error ) {
      // Error messages
      if( json.error.name ) {
        $('#form_sendemail input[name="name"]').parent().addClass('has-error');
        $('#form_sendemail input[name="name"]').next('.help-block').html( json.error.name ).slideDown();
      }
      if( json.error.email ) {
        $('#form_sendemail input[name="email"]').parent().addClass('has-error');
        $('#form_sendemail input[name="email"]').next('.help-block').html( json.error.email ).slideDown();
      }
      if( json.error.message ) {
        $('#form_sendemail textarea[name="message"]').parent().addClass('has-error');
        $('#form_sendemail textarea[name="message"]').next('.help-block').html( json.error.message ).slideDown();
      }
    }
    //
    if( json.success ) {
      $('#form_message').addClass('alert-success').html( json.success ).slideDown();

      setTimeout(function() {
        $('#form_message').slideUp("fast", function() {
          $(this).removeClass('alert-success').html('');
         });
      },4000);
      $('#form_sendemail')[0].reset();
    }

  },
  complete: function( XMLHttpRequest, textStatus ) {
    //
  }
});

return false;
});
});
</code>```

Body:
I am trying to submit a form, which I have had working, but have now modified it to include a modal jQuery UI box, so that it won't submit until the user presses "continue". I've had various problems with this, including getting the form to hold until that button is pressed, but I think I have found a solution to that, but implementing it, I am getting a SyntaxError which I can't find the source of.

With the help of kevin B managed to find the answer was the form was submitting, but the returned JSON response wasn't quite formatted right. The response was that the form wasn't being submitted, so that problem is still occurring.

So updated the code with the provided feedback, now need to find out why the form isnt submitting. I know its something to do with the 2nd function isnt recognising the submit button has been pressed, so need to know how to submit that form data without the form needing to be submitted again.

Below is the new code:

function submitData() {
$("#submitProvData").submit(function(event) {
    event.preventDefault();
    var gTotal, sTotal, dfd;
    var dfd = new $.Deferred();
    $('html,body').animate({ scrollTop: 0 }, 'fast');
    $("#submitProvData input").css("border", "1px solid #aaaaaa");
    $("#submitProvData input[readonly='readonly']").css("border", "none");
    sTotal = $('#summaryTotal').val();
    gTotal = $('#gptotal').val();
    if(gTotal !== 'sTotal'){
        $("#newsupinvbox").append('

Press "Continue", to submit the invoice flagged for attention.

or

Press "Correct" to correct the discrepancy.

') //CREATE DIV
        //SET
        $("#newsupinvdiagbox").dialog({
            resizable: false,
            autoOpen:false,
            modal: true,
            draggable: false,
            width:380,
            height:240,
            closeOnEscape: false,
            position: ['center',20],
            buttons: {
                'Continue': function() {
                    $(this).dialog('close');
                    reData();
                }, // end continue button
                'Correct': function() {
                    $(this).dialog('close');
                        return false;
                    } //end cancel button
                }//end buttons
            });//end dialog
            $('#newsupinvdiagbox').dialog('open');
        }
        return false;
    });
}

function reData() {
    console.log('submitted');
    $("#submitProvData").submit(function(resubmit){
        console.log('form submit');
        var formData;
        formData = new FormData($(this)[0]);
        $.ajax({
            type: "POST",
            url: "functions/invoicing_upload_provider.php",
            data: formData,
            async: false,
            success: function(result) {
                $.each($.parseJSON(result), function(item, value){
                    if(item == 'Success'){
                        $('#newsupinv_window_message_success_mes').html('The provider invoice was uploaded successfully.');
                        $('#newsupinv_window_message_success').fadeIn(300, function (){
                            reset();
                        }).delay(2500).fadeOut(700);
                    } else if(item == 'Error'){
                        $('#newsupinv_window_message_error_mes').html(value);
                        $('#newsupinv_window_message_error').fadeIn(300).delay(3000).fadeOut(700);
                    } else if(item == 'Warning'){
                        $('#newsupinv_window_message_warning_mes').html(value);
                        $('#newsupinv_window_message_warning').fadeIn(300, function (){
                            reset();
                        }).delay(2500).fadeOut(700);
                    }
                });
            },
            error: function() {
                $('#newsupinv_window_message_error_mes').html("An error occured, the form was not submitted");
                $('#newsupinv_window_message_error').fadeIn(300);
                $('#newsupinv_window_message_error').delay(3000).fadeOut(700);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
}

Body:
A complete system to break form and post with jquery/ajax

$(document).ready(function(e) {
$('#form_sendemail').submit(function(e) {
$.ajax({
  url: 'sendmail.php',
  type: 'POST',
  data: $(this).serialize(),
  dataType: 'json',
  beforeSend: function (XMLHttpRequest) {
    //
    $('#form_sendemail .has-error').removeClass('has-error');
    $('#form_sendemail .help-block').html('').hide();
    $('#form_message').removeClass('alert-success').html('');
  },
  success: function( json, textStatus ) {
    if( json.error ) {
      // Error messages
      if( json.error.name ) {
        $('#form_sendemail input[name="name"]').parent().addClass('has-error');
        $('#form_sendemail input[name="name"]').next('.help-block').html( json.error.name ).slideDown();
      }
      if( json.error.email ) {
        $('#form_sendemail input[name="email"]').parent().addClass('has-error');
        $('#form_sendemail input[name="email"]').next('.help-block').html( json.error.email ).slideDown();
      }
      if( json.error.message ) {
        $('#form_sendemail textarea[name="message"]').parent().addClass('has-error');
        $('#form_sendemail textarea[name="message"]').next('.help-block').html( json.error.message ).slideDown();
      }
    }
    //
    if( json.success ) {
      $('#form_message').addClass('alert-success').html( json.success ).slideDown();

      setTimeout(function() {
        $('#form_message').slideUp("fast", function() {
          $(this).removeClass('alert-success').html('');
         });
      },4000);
      $('#form_sendemail')[0].reset();
    }

  },
  complete: function( XMLHttpRequest, textStatus ) {
    //
  }
});

return false;
});
});


问:
SQL Server using wildcard within IN
Since I believe this should be a basic question I know this question has probably been asked, but I am unable to find it. I'm probably about to earn my Peer Pressure badge, but I'll ask anyway:

Is there a way in SQL Server that I am not aware of for using the wildcard character % when using IN.

I realize that I can use OR's like:

```<code>select *
from jobdetails
where job_no like '0711%' or job_no like '0712%'
</code>```

and in some cases I can use a subquery like:

```<code>select *
from jobdetails
where job_no in (select job_no from jobs where job_id = 39)
</code>```

but I'm looking to do something like the following:

```<code>select *
from jobdetails
where job_no in ('0711%', '0712%')
</code>```

In this case it uses the percent sign as a character instead of a wildcard character so no rows are returned. I currently just use a bunch of OR's when I have to do this, but I know there has to be a better way. What method do you use for this?

答:
I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with ORs will do it.

```<code>select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%')
</code>```

Title: SQL Server using wildcard within IN

Body:
Since I believe this should be a basic question I know this question has probably been asked, but I am unable to find it. I'm probably about to earn my Peer Pressure badge, but I'll ask anyway:

Is there a way in SQL Server that I am not aware of for using the wildcard character % when using IN.

I realize that I can use OR's like:

select *
from jobdetails
where job_no like '0711%' or job_no like '0712%'

and in some cases I can use a subquery like:

select *
from jobdetails
where job_no in (select job_no from jobs where job_id = 39)

but I'm looking to do something like the following:

select *
from jobdetails
where job_no in ('0711%', '0712%')

In this case it uses the percent sign as a character instead of a wildcard character so no rows are returned. I currently just use a bunch of OR's when I have to do this, but I know there has to be a better way. What method do you use for this?

Body:
I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with ORs will do it.

select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%')


问:
Backtesting stock returns for Moving Average rule in r
I am trying to backtest stock returns given a 10 month moving average rule. The rule being, if the price is above the 10mnth average - buy, if it is below the 10mnth average - hold the value constant.

I know how to do this in excel very easily, but I am having trouble in R.

Below is my approach in R:

```<code>#Downloand financial data
library(Quandl)

SPY <- Quandl("YAHOO/INDEX_GSPC", type = "xts", collapse = "monthly")
head(SPY)

#Calculate log returns
SPY$log_ret <- diff(log(SPY$Close))

#Calculate moving average for Closing price
SPY$MA.10 <- rollapply(SPY$Close, width = 10, FUN = mean)

#Create binary rule to determine when to buy and when to hold
#1 = Buy
SPY$Action <- ifelse(SPY$MA.10 < SPY$Close, 1, 0)

#Create default value in a new column to backtest returns
SPY$Hit <- 100

#Calculate cumulative returns
SPY$Hit <-ifelse(SPY$Action == 1, SPY[2:n, "Hit"] *
                (1 + SPY$log_ret), lag.xts(SPY$Hit, k=1))
</code>```

Returns do get calculated correctly for an Action of 1, but when the Action is not 1, I find that SPY$Hit only lags 1 time, then defaults to the 100 value, while I would like it to hold the value from the last Action == 1 time.

This formula works very well in MS Excel and is very easy to implement, but it seems that the issue in R is that I cannot keep the value constant from the last Action == 1, how can I do this so that I can see how well this simple trading strategy would work?

Please let me know if I can clarify this further, thank you.

```<code>Sample of the desired output:
      Action Return    Answer
 [1,]      0   0.00 100.00000
 [2,]      1   0.09 109.00000
 [3,]      1   0.08 117.72000
 [4,]      1  -0.05 111.83400
 [5,]      1  -0.03 108.47898
 [6,]      0  -0.02 108.47898
 [7,]      0   0.01 108.47898
 [8,]      0   0.06 108.47898
 [9,]      1  -0.03 105.22461
[10,]      0   0.10 105.22461
[11,]      1  -0.05  99.96338
</code>```

Body:
I am trying to backtest stock returns given a 10 month moving average rule. The rule being, if the price is above the 10mnth average - buy, if it is below the 10mnth average - hold the value constant.

I know how to do this in excel very easily, but I am having trouble in R.

Below is my approach in R:

#Downloand financial data
library(Quandl)

SPY <- Quandl("YAHOO/INDEX_GSPC", type = "xts", collapse = "monthly")
head(SPY)

#Calculate log returns
SPY$log_ret <- diff(log(SPY$Close))

#Calculate moving average for Closing price
SPY$MA.10 <- rollapply(SPY$Close, width = 10, FUN = mean)

#Create binary rule to determine when to buy and when to hold
#1 = Buy
SPY$Action <- ifelse(SPY$MA.10 < SPY$Close, 1, 0)

#Create default value in a new column to backtest returns
SPY$Hit <- 100

#Calculate cumulative returns
SPY$Hit <-ifelse(SPY$Action == 1, SPY[2:n, "Hit"] *
                (1 + SPY$log_ret), lag.xts(SPY$Hit, k=1))

Returns do get calculated correctly for an Action of 1, but when the Action is not 1, I find that SPY$Hit only lags 1 time, then defaults to the 100 value, while I would like it to hold the value from the last Action == 1 time.

This formula works very well in MS Excel and is very easy to implement, but it seems that the issue in R is that I cannot keep the value constant from the last Action == 1, how can I do this so that I can see how well this simple trading strategy would work?

Please let me know if I can clarify this further, thank you.

Sample of the desired output:
      Action Return    Answer
 [1,]      0   0.00 100.00000
 [2,]      1   0.09 109.00000
 [3,]      1   0.08 117.72000
 [4,]      1  -0.05 111.83400
 [5,]      1  -0.03 108.47898
 [6,]      0  -0.02 108.47898
 [7,]      0   0.01 108.47898
 [8,]      0   0.06 108.47898
 [9,]      1  -0.03 105.22461
[10,]      0   0.10 105.22461
[11,]      1  -0.05  99.96338

Body:
Here's my guess, let me know what you think.

# Looping
Hit <- matrix(100, nrow = nrow(SPY))
for(row in 11:nrow(SPY)){ # 11 since you have NA's from your moving average
  if(SPY$Action[row] == 1){
    Hit[row] = Hit[row-1] * (1 + SPY$log_ret[row]) # here we needed row-1
  } else {
    Hit[row] = Hit[row-1]
  }
}
SPY$Hit <- Hit

cbind(SPY$Action, SPY$Hit)

For your sample:

x <- data.frame(Action = c(0,1,1,1,1,0,0,0,1,0,1))
x$Return <- c(0,0.09,0.08,-0.05,-0.03,-0.02,0.01,0.06,-0.03,0.10,-0.05)

x$Answer <- matrix(100, nrow = nrow(x))
for(row in 2:nrow(x)){ # 11 since you have NA's from your moving average
  if(x$Action[row] == 1){
    x$Answer[row] = x$Answer[row-1] * (1 + x$Return[row])
  } else {
    x$Answer[row] = x$Answer[row-1]
  }
}
x
       Action Return    Answer
1       0   0.00 100.00000
2       1   0.09 109.00000
3       1   0.08 117.72000
4       1  -0.05 111.83400
5       1  -0.03 108.47898
6       0  -0.02 108.47898
7       0   0.01 108.47898
8       0   0.06 108.47898
9       1  -0.03 105.22461
10      0   0.10 105.22461
11      1  -0.05  99.96338


问:
Can The Style of A Table In Numbers Be Set Programmatically
Pretty straight forward. There are different styles of tables to choose from manually. The AppleScript Numbers library doesn't mention the style can be set, and an internet search isn't turning up many results. Has anyone had success or made the ultimate decision that it can't be done? I'm hoping it can be done without using system events to "click" a table style.</p>

```<code>        set newTable to make new table with properties {style:"Something here?", column count:10, header column count:1, footer row count:1, position:{0, 72}, name:"Sample Table", header row count:1, row count:10}
        #Or Here?
        tell newtable
        set style of table somehow?
</code>```

答:
Technically yes. You could set the properties of rows and columns in the tell newTable area. Although it's not the easy way, it can still be done if you build it from scratch. (Which you are doing)

EDIT To clarify with a little more and include examples, if you're having trouble identifying additional properties that can be set, you could use get properties of table 1 to guide you further if the library isn't much assistance. Getting properties would yield you results similar to below.

```<code>tell application "Numbers"
get properties of table 1 of sheet 1 of document 1

(* returned from get properties of table
{locked:false, cell range:range "A1:E10" of table 1 of sheet 1 of document id "4F9B1A5C-CC34-4C74-B05C-4856839EE760" of application "Numbers", column count:5, parent:sheet 1 of document id "4F9B1A5C-CC34-4C74-B05C-4856839EE760" of application "Numbers", header column count:1, footer row count:0, class:table, header columns frozen:true, position:{16, 43}, filtered:false, header rows frozen:true, width:490, name:"Table 1", selection range:range "A1:E10" of table 1 of sheet 1 of document id "4F9B1A5C-CC34-4C74-B05C-4856839EE760" of application "Numbers", header row count:1, height:203, row count:10}
*)

get properties of row 1 of table 1 of sheet 1 of document 1

(* returned from get properties of row
{vertical alignment:top, font name:"Helvetica-Bold", class:row, background color:{18205, 30509, 7341}, name:"1", text wrap:true, text color:{65528, 65533, 65524}, alignment:auto align, format:automatic, address:1, font size:10.0, height:20.625}
*)

get properties of column 1 of table 1 of sheet 1 of document 1

(*returned from get properties of column
{vertical alignment:top, font name:"Helvetica-Bold", class:column, background color:{27817, 27821, 27814}, width:98.0, format:automatic, text wrap:true, text color:{65528, 65533, 65524}, alignment:auto align, name:"A", address:1, font size:10.0}
*)

end tell
</code>```

Using the above, you're able to see specific characteristics able to be set. Then you could mimic those settings in your own table as demonstrated below with a slight mix of variations of using the tell newTable block

```<code>tell application "Numbers"
activate
set thisDocument to make new document
tell sheet 1 of thisDocument
    delete every table
    set newTable to make new table with properties ¬
        {name:"Sample Table", position:{16, 43}, column count:5, row count:10, header column count:1, header row count:1, footer row count:1}
    tell newTable
        set properties of column 1 to {width:216, background color:{27817, 27821, 27814}}
        set format of column 2 to checkbox
        set properties of column 3 to {width:98, format:currency}
        set properties of row 1 to {background color:{18205, 30509, 7341}}
        set properties of last row to {background color:{18205, 30509, 7341}}
        set value of last cell to "=SUM(E)"
    end tell
end tell
end tell
</code>```

If you're looking for very specific borders, you could start the document off with using a template that uses the desired border you want, since every table started in that template will be the same default table. However since you're scripting it to begin with, and didn't specifically mention looking on how to change the border, I'm under the impression you're after colors, formats, and formulas rather than borders. So the answer to the question still remains "technically yes" you can programmatically set the style of your table.

Body:
Pretty straight forward. There are different styles of tables to choose from manually. The AppleScript Numbers library doesn't mention the style can be set, and an internet search isn't turning up many results. Has anyone had success or made the ultimate decision that it can't be done? I'm hoping it can be done without using system events to "click" a table style.

        set newTable to make new table with properties {style:"Something here?", column count:10, header column count:1, footer row count:1, position:{0, 72}, name:"Sample Table", header row count:1, row count:10}
        #Or Here?
        tell newtable
        set style of table somehow?

Body:
Technically yes. You could set the properties of rows and columns in the tell newTable area. Although it's not the easy way, it can still be done if you build it from scratch. (Which you are doing)

EDIT To clarify with a little more and include examples, if you're having trouble identifying additional properties that can be set, you could use get properties of table 1 to guide you further if the library isn't much assistance. Getting properties would yield you results similar to below.

tell application "Numbers"
get properties of table 1 of sheet 1 of document 1

(* returned from get properties of table
{locked:false, cell range:range "A1:E10" of table 1 of sheet 1 of document id "4F9B1A5C-CC34-4C74-B05C-4856839EE760" of application "Numbers", column count:5, parent:sheet 1 of document id "4F9B1A5C-CC34-4C74-B05C-4856839EE760" of application "Numbers", header column count:1, footer row count:0, class:table, header columns frozen:true, position:{16, 43}, filtered:false, header rows frozen:true, width:490, name:"Table 1", selection range:range "A1:E10" of table 1 of sheet 1 of document id "4F9B1A5C-CC34-4C74-B05C-4856839EE760" of application "Numbers", header row count:1, height:203, row count:10}
*)

get properties of row 1 of table 1 of sheet 1 of document 1

(* returned from get properties of row
{vertical alignment:top, font name:"Helvetica-Bold", class:row, background color:{18205, 30509, 7341}, name:"1", text wrap:true, text color:{65528, 65533, 65524}, alignment:auto align, format:automatic, address:1, font size:10.0, height:20.625}
*)

get properties of column 1 of table 1 of sheet 1 of document 1

(*returned from get properties of column
{vertical alignment:top, font name:"Helvetica-Bold", class:column, background color:{27817, 27821, 27814}, width:98.0, format:automatic, text wrap:true, text color:{65528, 65533, 65524}, alignment:auto align, name:"A", address:1, font size:10.0}
*)

end tell

Using the above, you're able to see specific characteristics able to be set. Then you could mimic those settings in your own table as demonstrated below with a slight mix of variations of using the tell newTable block

tell application "Numbers"
activate
set thisDocument to make new document
tell sheet 1 of thisDocument
    delete every table
    set newTable to make new table with properties ¬
        {name:"Sample Table", position:{16, 43}, column count:5, row count:10, header column count:1, header row count:1, footer row count:1}
    tell newTable
        set properties of column 1 to {width:216, background color:{27817, 27821, 27814}}
        set format of column 2 to checkbox
        set properties of column 3 to {width:98, format:currency}
        set properties of row 1 to {background color:{18205, 30509, 7341}}
        set properties of last row to {background color:{18205, 30509, 7341}}
        set value of last cell to "=SUM(E)"
    end tell
end tell
end tell

If you're looking for very specific borders, you could start the document off with using a template that uses the desired border you want, since every table started in that template will be the same default table. However since you're scripting it to begin with, and didn't specifically mention looking on how to change the border, I'm under the impression you're after colors, formats, and formulas rather than borders. So the answer to the question still remains "technically yes" you can programmatically set the style of your table.


问:
Could not build Objective c Module
i was making a xcode project with swift and it was working fine but suddenly it started giving me this error.

Could not build Objective C Module 'Foundation'

/Users/admin/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator10.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSNotification.h:17:4: Prefix attribute must be followed by an interface or protocol

Even when i create a new project and do nothing but just build it, this error is shown. The project is not built. When i click on the error message, it leads me to this file NSNotification.h

Here are the contents of this file

```<code>/*  NSNotification.h
Copyright (c) 1994-2016, Apple Inc. All rights reserved.
*/

#import <Foundation/NSObject.h>

typedef NSString *NSNotificationName NS_EXTENSIBLE_STRING_ENUM;

@class NSString, NSDictionary, NSOperationQueue;

NS_ASSUME_NONNULL_BEGIN

/****************   Notifications   ****************/

@interface NSNotification : NSObject <NSCopying, NSCoding>

id@property (nullable, readonly, retain) id object;
@property (nullable, readonly, copy) NSDictionary *userInfo;

- (instancetype)initWithName:(NSNotificationName)name object:(nullable    id)object userInfo:(nullable NSDictionary *)userInfo NS_AVAILABLE(10_6, 4_0) NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder     NS_DESIGNATED_INITIALIZER;

@end

@interface NSNotification (NSNotificationCreation)

+ (instancetype)notificationWithName:(NSNotificationName)aName object:      (nullable id)anObject;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:        (nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

- (instancetype)init /*NSUIImagePNGRepresentation_UNAVAILABLE*/;    /* do     not invoke; not a valid initializer for this class */

@end

/****************   Notification Center ****************/

@interface NSNotificationCenter : NSObject {
@package
void *_impl;
void *_callback;
void *_pad[11];
}

#if FOUNDATION_SWIFT_SDK_EPOCH_AT_LEAST(8)
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable      NSNotificationName)aName object:(nullable id)anObject;
#endif

- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable  id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

-     (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block NS_AVAILABLE(10_6, 4_0);
// The return value is retained by the system, and should be held onto by the caller in
// order to remove the observer with removeObserver: later, to stop observation.

@end

NS_ASSUME_NONNULL_END
</code>```

Please help me through this. I will be very grateful for this. Thanks.

答:
This line in NSNotification.h looks like it's been modified:

```<code>id@property (nullable, readonly, retain) id object;
</code>```

Delete the id at the front of that line and try to recompile. That should fix it.

Title: Could not build Objective c Module

Body:
i was making a xcode project with swift and it was working fine but suddenly it started giving me this error.

Could not build Objective C Module 'Foundation'

/Users/admin/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator10.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSNotification.h:17:4: Prefix attribute must be followed by an interface or protocol

Even when i create a new project and do nothing but just build it, this error is shown. The project is not built. When i click on the error message, it leads me to this file NSNotification.h

Here are the contents of this file

/*  NSNotification.h
Copyright (c) 1994-2016, Apple Inc. All rights reserved.
*/

#import <Foundation/NSObject.h>

typedef NSString *NSNotificationName NS_EXTENSIBLE_STRING_ENUM;

@class NSString, NSDictionary, NSOperationQueue;

NS_ASSUME_NONNULL_BEGIN

/****************   Notifications   ****************/

@interface NSNotification : NSObject <NSCopying, NSCoding>

id@property (nullable, readonly, retain) id object;
@property (nullable, readonly, copy) NSDictionary *userInfo;

- (instancetype)initWithName:(NSNotificationName)name object:(nullable    id)object userInfo:(nullable NSDictionary *)userInfo NS_AVAILABLE(10_6, 4_0) NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder     NS_DESIGNATED_INITIALIZER;

@end

@interface NSNotification (NSNotificationCreation)

+ (instancetype)notificationWithName:(NSNotificationName)aName object:      (nullable id)anObject;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:        (nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

- (instancetype)init /*NSUIImagePNGRepresentation_UNAVAILABLE*/;    /* do     not invoke; not a valid initializer for this class */

@end

/****************   Notification Center ****************/

@interface NSNotificationCenter : NSObject {
@package
void *_impl;
void *_callback;
void *_pad[11];
}

#if FOUNDATION_SWIFT_SDK_EPOCH_AT_LEAST(8)
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable      NSNotificationName)aName object:(nullable id)anObject;
#endif

- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable  id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

-     (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block NS_AVAILABLE(10_6, 4_0);
// The return value is retained by the system, and should be held onto by the caller in
// order to remove the observer with removeObserver: later, to stop observation.

@end

NS_ASSUME_NONNULL_END

Please help me through this. I will be very grateful for this. Thanks.

Body:
This line in NSNotification.h looks like it's been modified:

id@property (nullable, readonly, retain) id object;

Delete the id at the front of that line and try to recompile. That should fix it.


问:
Out of bounds subscript error
I am working on a simple matrix for Singular Value Decomposition 10x10 with all entries zeros. I'd like to add a coin flip to this matrix and run SVD. The code is below:

# Simple Example

set.seed(1234)
par(mar=rep(0.2,4))
dataMatrix = matrix(rnorm(100), nrow=10)

dataMatrix

getMatrix = dataMatrix*0
getMatrix

svd1 = svd(getMatrix)
svd1

par(mfrow=c(1,5))

image(t(getMatrix)[,nrow(getMatrix):1], col='blue')
plot(svd1$d,xlab='Column',ylab='Singular Values', pch=19, col='red')

## Add a pattern to the data set , flipping a coin

set.seed(78910)
for (i in 1:40){
  coinFlip1 = rbinom(1,size=1, prob=0.5)
  coinFlip2 = rbinom(1,size=1,prob=0.5)

  if (coinFlip1){
    getMatrix[i,]=getMatrix[i,]+rep(c(0,5),each=5)
  }
  if (coinFlip2){
    getMatrix[i,]=getMatrix[i,]+rep(c(0,5),each=5)
  }
}

hh = hclust(dist(getMatrix))
getMatrixOrdered= getMatrix[hh$order,]```

When I run the program in R, it gives me an error below:

Error in getMatrix[i, ] : subscript out of bounds

I know the bounds are out of order, so how can I fix it?

Thank you!

答:
```<code>for (i in 1:40){
</code>```

substitute for

```<code>for (i in 1:10){
</code>```

Title: Out of bounds subscript error

Body:
I am working on a simple matrix for Singular Value Decomposition 10x10 with all entries zeros. I'd like to add a coin flip to this matrix and run SVD. The code is below:

# Simple Example

set.seed(1234)
par(mar=rep(0.2,4))
dataMatrix = matrix(rnorm(100), nrow=10)

dataMatrix

getMatrix = dataMatrix*0
getMatrix

svd1 = svd(getMatrix)
svd1

par(mfrow=c(1,5))

image(t(getMatrix)[,nrow(getMatrix):1], col='blue')
plot(svd1$d,xlab='Column',ylab='Singular Values', pch=19, col='red')

## Add a pattern to the data set , flipping a coin

set.seed(78910)
for (i in 1:40){
  coinFlip1 = rbinom(1,size=1, prob=0.5)
  coinFlip2 = rbinom(1,size=1,prob=0.5)

  if (coinFlip1){
    getMatrix[i,]=getMatrix[i,]+rep(c(0,5),each=5)
  }
  if (coinFlip2){
    getMatrix[i,]=getMatrix[i,]+rep(c(0,5),each=5)
  }
}

hh = hclust(dist(getMatrix))
getMatrixOrdered= getMatrix[hh$order,]

When I run the program in R, it gives me an error below:

Error in getMatrix[i, ] : subscript out of bounds

I know the bounds are out of order, so how can I fix it?

Thank you!

Body:
for (i in 1:40){

substitute for

for (i in 1:10){


问:
How set context variable in a web app's context.xml when it's also the default web app?
I have a WAR that I've set as the default web app in Tomcat's server.xml:

Inside Server.xml

```<code><Host...>
    <Context docBase="mywar" path="" />
</code>```

In addition, I have a META-INF/context.xml file where I set an environment variable.

```<code><?xml version="1.0" encoding="utf-8"?>
<Context debug="0" reloadable="true">
    <Environment
            name="my.name"
            type="java.lang.String"
            value="donrhummy"
    />
</Context>
</code>```

But it's throwing an exception javax.naming.NameNotFoundException: Name my.name is not bound in this Context.

How can I get that context variable in my app?

NOTE: That variable exists when I go to http://localhost/mywar

答:
The only solution i could find was:

Rename my WAR as ROOT.war (Case-sensitive)

Remove the <Context...> from server.xml

Tomcat will treat that as the root WAR (i.e. for the "/" path) and let it use the context form it's own META-INF directory.

Body:
I have a WAR that I've set as the default web app in Tomcat's server.xml:

Inside Server.xml

<Host...>
    <Context docBase="mywar" path="" />

In addition, I have a META-INF/context.xml file where I set an environment variable.

<?xml version="1.0" encoding="utf-8"?>
<Context debug="0" reloadable="true">
    <Environment
            name="my.name"
            type="java.lang.String"
            value="donrhummy"
    />
</Context>

But it's throwing an exception javax.naming.NameNotFoundException: Name my.name is not bound in this Context.

How can I get that context variable in my app?

NOTE: That variable exists when I go to http://localhost/mywar


问:
NAnt: executing NCover as administrator account - runas returns directly without waiting
My NAnt build runs as a non-admin as part of CruiseControl. But we have an NCover task which needs to run as an Administrator. For this we are thinking about using RunAs with an admin account.

The problem is that RunAs returns directly and doesn't wait for the process to exit.

Is there a way to block the NAnt build until NCover has finished?

Tnx

答:
So far I have found that using psexec works for this. The command I am using is:

```<code>psexec -w directory file_to_run -u myusername
</code>```

With an optional -p password

The one concern I have is that psexec's EULA appears to forbid what I want to use it for. But I am not sure. The phrase I am worried about is:

You may not:

transfer the software or this agreement to any third party;

I want to replace the runas usage  in our installer with psexec. Psexec would be on a cd, and I could just run it from there, or make a copy and delete it when I am done.

Would these uses violate this agreement?

Body:
So far I have found that using psexec works for this. The command I am using is:

psexec -w directory file_to_run -u myusername

With an optional -p password

The one concern I have is that psexec's EULA appears to forbid what I want to use it for. But I am not sure. The phrase I am worried about is:

You may not:

transfer the software or this agreement to any third party;

I want to replace the runas usage  in our installer with psexec. Psexec would be on a cd, and I could just run it from there, or make a copy and delete it when I am done.

Would these uses violate this agreement?


答:
This should work fine:</p>

```<code>$content = '<?php
$regArray = array("'.$registration.'","'.$startMeeting.'","'.$endMeeting.'");
?>';

file_put_contents("includes/meetingParams.php", $content);
</code>```

Title: Update array in a file

Body:
I have an include with a single array in it that holds 3 instructions; a "y/n" switch and a start and end date. The include meetingParams.php looks like this:

<?php
$regArray = array("n","2018-03-03","2018-03-07");
?>

I want to update those array values from time to time using a web based form. Where I get stuck is finding the correct syntax to do that. Right now I have the following:

$registration = $_POST['registration'];
$startMeeting = $_POST['startMeeting'];
$endMeeting = $_POST['endMeeting'];

$replace = array($registration, $startMeeting, $endMeeting);
$search = file_get_contents('includes/meetingParams.php');
$parsed = preg_replace('^$regArray.*$', $replace, $search);

file_put_contents("includes/meetingParams.php", $parsed);

When I run this code, the file meetingParams.php get's replaced with an empty file. What am I missing?

Body:
This should work fine:

$content = '<?php
$regArray = array("'.$registration.'","'.$startMeeting.'","'.$endMeeting.'");
?>';

file_put_contents("includes/meetingParams.php", $content);


问:
d3.js stacked bar with toggleable series
this time I am trying to create a stacked bar with toggleable series- based on Mike Bostock's example (thanks once more Mike!) I have already succeeded into making it responsive and zoomable, and the toggleable series through a legend is the last thing remaining.

I created the legend items, and applied the correct color by using keys:

var legendItem = d3.select(".legend")
  .selectAll("li")
  .data(keys)
  .enter()
  .append("li")
  .on('click', function(d) {
    keys.forEach(function(c) {
      if (c != d) tKeys.push(c)
    });
    fKeys = tKeys;
    tKeys = [];
    redraw();
  });

legendItem
  .append("span")
  .attr("class", "color-square")
  .style("color", function(d) {
    return colorScale5(d);
  });

legendItem
  .append("span")
  .text(function(d) {
    return (d)
  });
```

<p>Based on the structure, in order to create the toggleable item, I came to the conclusion that I somehow have to be able to toggle it from the keys AND the dataset - or is there another way to do it? I have managed to remove a specific key from the keys, but not from the dataset, I have no idea how to map it properly.</p>

<p>The second issue is that I can't figure of a way to toggle a key, but just remove it. This is the original dataset:</p>

<pre class="lang-js prettyprint-override"><code>var data = [{
  "country": "Greece",
  "Vodafone": 57,
  "Wind": 12,
  "Cosmote": 20
}, {
  "country": "Italy",
  "Vodafone": 40,
  "Wind": 24,
  "Cosmote": 35
}, {
  "country": "France",
  "Vodafone": 22,
  "Wind": 9,
  "Cosmote": 9
}]
</code>```

In the values were provided from a nested dataset, I could attach a key named 'enabled' to each object and could easily filter the dataset, but can't figure out how to attach a key to help in the filtering proccess.

edit3 Removed useless information from the question:

Here is a working fiddle:
https://jsfiddle.net/fgseaxoy/2/

答:
There are a few things that needed fixing:

First, JavaScript assignes objects by reference. It means that after

var fKeys = keys;
```

<p>both <code>fKeys</code> and <code>keys</code> point to the same array. This is not what you want. You want something copying such as:</p>

<pre class="lang-js prettyprint-override"><code>var fKeys = keys.slice();
</code>```

Then your legendItem "click" handler was wrong because it doesn't really toggle the selected item. What you want is something like

        .on('click', function (keyToToggle) {
            // Go through both keys and fKeys to find out proper
            // position to insert keyToToggle if it is to be inserted
            var i, j;
            for (i = 0, j = 0; i < keys.length; i++) {
                // If we hit the end of fKeys, keyToToggle
                // should be last
                if (j >= fKeys.length) {
                    fKeys.push(keyToToggle);
                    break;
                }
                // if we found keyToToggle in fKeys - remove it
                if (fKeys[j] == keyToToggle) {
                    // remove it
                    fKeys.splice(j, 1);
                    break;
                }

                // we found keyToToggle in the original collection
                // AND it was not found at fKeys[j]. It means
                // it should be inserted to fKeys at position "j"
                if (keys[i] == keyToToggle) {
                    // add it
                    fKeys.splice(j, 0, keyToToggle);
                    break;
                }

                if (keys[i] == fKeys[j])
                    j++;
            }

            redraw();
        });
```

<p>Next you want to povide <code>key</code> fuction when you call <code>data</code> to get <code>stackedBars</code>. This is important because otherwise data would be bound by index and always the last piece of data would be removed.</p>

<pre class="lang-js prettyprint-override"><code>    var stackedData = d3.stack().keys(fKeys)(dataset);
    var stackedBars = g
            .selectAll(".d3-group")
            .data(stackedData , function (__data__, i, group) {
                return __data__.key;
            });
</code>```

And finally, when you update '.d3-rect' you want to call data once again as child nodes cache data from the last draw and you want to override it with new data

        stackedBars.selectAll('.d3-rect')
                .data(function (d) {
                    return d; // force override with updated parent's data
                })
                .attr("x", function (d) {
                    return xz(d.data.country);
                })
                ...
```

<p>Without such call, hiding first piece of data ("Vodafone") would not move other stacked pieces down.</p>

<p>Also there are a few too many global vairables (i.e. too few <code>var</code>s) and a few unnecessary variables.</p>

<p><strong>Update</strong> (auto-scale y)</p>

<p>If you also want your Y-scale to be updated, you move <code>var stackedData</code> higher in the code of the <code>redraw</code> so you can use it to calculate your <code>y</code> as following</p>

<pre class="lang-js prettyprint-override"><code>    var stackedData = d3.stack().keys(fKeys)(dataset);
    var autoScaleY = true; // scale Y according to selected data or always use original range
    var stackedDataForMax;
    if (autoScaleY && stackedData.length > 0) {
        // only selected data
        stackedDataForMax = stackedData;
    }
    else {
        // full range
        stackedDataForMax = d3.stack().keys(keys)(dataset);
    }
    var maxDataY = 1.2 * d3.max(stackedDataForMax.map(function (d) {
                return d3.max(d, function (innerD) {
                    return innerD[1];
                });
            }));
    y.domain([0, maxDataY]).rangeRound([height, 0]);
</code>```

You can find whole code in the fork of your original fiddle.

Body:
this time I am trying to create a stacked bar with toggleable series- based on Mike Bostock's example (thanks once more Mike!) I have already succeeded into making it responsive and zoomable, and the toggleable series through a legend is the last thing remaining.

I created the legend items, and applied the correct color by using keys:

var legendItem = d3.select(".legend")
  .selectAll("li")
  .data(keys)
  .enter()
  .append("li")
  .on('click', function(d) {
    keys.forEach(function(c) {
      if (c != d) tKeys.push(c)
    });
    fKeys = tKeys;
    tKeys = [];
    redraw();
  });

legendItem
  .append("span")
  .attr("class", "color-square")
  .style("color", function(d) {
    return colorScale5(d);
  });

legendItem
  .append("span")
  .text(function(d) {
    return (d)
  });

Based on the structure, in order to create the toggleable item, I came to the conclusion that I somehow have to be able to toggle it from the keys AND the dataset - or is there another way to do it? I have managed to remove a specific key from the keys, but not from the dataset, I have no idea how to map it properly.

The second issue is that I can't figure of a way to toggle a key, but just remove it. This is the original dataset:

var data = [{
  "country": "Greece",
  "Vodafone": 57,
  "Wind": 12,
  "Cosmote": 20
}, {
  "country": "Italy",
  "Vodafone": 40,
  "Wind": 24,
  "Cosmote": 35
}, {
  "country": "France",
  "Vodafone": 22,
  "Wind": 9,
  "Cosmote": 9
}]

In the values were provided from a nested dataset, I could attach a key named 'enabled' to each object and could easily filter the dataset, but can't figure out how to attach a key to help in the filtering proccess.

edit3 Removed useless information from the question:

Here is a working fiddle:
https://jsfiddle.net/fgseaxoy/2/

Body:
There are a few things that needed fixing:

First, JavaScript assignes objects by reference. It means that after

var fKeys = keys;

both fKeys and keys point to the same array. This is not what you want. You want something copying such as:

var fKeys = keys.slice();

Then your legendItem "click" handler was wrong because it doesn't really toggle the selected item. What you want is something like

        .on('click', function (keyToToggle) {
            // Go through both keys and fKeys to find out proper
            // position to insert keyToToggle if it is to be inserted
            var i, j;
            for (i = 0, j = 0; i < keys.length; i++) {
                // If we hit the end of fKeys, keyToToggle
                // should be last
                if (j >= fKeys.length) {
                    fKeys.push(keyToToggle);
                    break;
                }
                // if we found keyToToggle in fKeys - remove it
                if (fKeys[j] == keyToToggle) {
                    // remove it
                    fKeys.splice(j, 1);
                    break;
                }

                // we found keyToToggle in the original collection
                // AND it was not found at fKeys[j]. It means
                // it should be inserted to fKeys at position "j"
                if (keys[i] == keyToToggle) {
                    // add it
                    fKeys.splice(j, 0, keyToToggle);
                    break;
                }

                if (keys[i] == fKeys[j])
                    j++;
            }

            redraw();
        });

Next you want to povide key fuction when you call data to get stackedBars. This is important because otherwise data would be bound by index and always the last piece of data would be removed.

    var stackedData = d3.stack().keys(fKeys)(dataset);
    var stackedBars = g
            .selectAll(".d3-group")
            .data(stackedData , function (__data__, i, group) {
                return __data__.key;
            });

And finally, when you update '.d3-rect' you want to call data once again as child nodes cache data from the last draw and you want to override it with new data

        stackedBars.selectAll('.d3-rect')
                .data(function (d) {
                    return d; // force override with updated parent's data
                })
                .attr("x", function (d) {
                    return xz(d.data.country);
                })
                ...

Without such call, hiding first piece of data ("Vodafone") would not move other stacked pieces down.

Also there are a few too many global vairables (i.e. too few vars) and a few unnecessary variables.

Update (auto-scale y)

If you also want your Y-scale to be updated, you move var stackedData higher in the code of the redraw so you can use it to calculate your y as following

    var stackedData = d3.stack().keys(fKeys)(dataset);
    var autoScaleY = true; // scale Y according to selected data or always use original range
    var stackedDataForMax;
    if (autoScaleY && stackedData.length > 0) {
        // only selected data
        stackedDataForMax = stackedData;
    }
    else {
        // full range
        stackedDataForMax = d3.stack().keys(keys)(dataset);
    }
    var maxDataY = 1.2 * d3.max(stackedDataForMax.map(function (d) {
                return d3.max(d, function (innerD) {
                    return innerD[1];
                });
            }));
    y.domain([0, maxDataY]).rangeRound([height, 0]);

You can find whole code in the fork of your original fiddle.


问:
How do I parse an Excel file that will give me data exactly as it appears visually?
I'm on Rails 5 (Ruby 2.4).  I want to read an .xls doc and I would like to get the data into CSV format, just as it appears in the Excel file.  Someone recommended I use Roo, and so I have

```<code>book = Roo::Spreadsheet.open(file_location)
sheet = book.sheet(0)
text = sheet.to_csv
arr_of_arrs = CSV.parse(text)
</code>```

However what is getting returned is not the same as what I see in the spreadsheet.  For isntance, a cell in the spreadsheet has

```<code>16:45.81
</code>```

and when I get the CSV data from above, what is returned is

```<code>"0.011641319444444444"
</code>```

How do I parse the Excel doc and get exactly what I see?  I don't care if I use Roo to parse or not, just as long as I can get CSV data that is a representation of what I see rather than some weird internal representation.  For reference the file type I was parsing givies this when I run "file name_of_file.xls" ...

```<code>Composite Document File V2 Document, Little Endian, Os: Windows, Version 5.1, Code page: 1252, Author: Dwight Schroot, Last Saved By: Dwight Schroot, Name of Creating Application: Microsoft Excel, Create Time/Date: Tue Sep 21 17:05:21 2010, Last Saved Time/Date: Wed Oct 13 16:52:14 2010, Security: 0
</code>```

答:
Under the hood roo-xls gem uses the spreadsheet gem to parse the xls file. There was a similar issue to yours logged here, but it doesn't appear that there was any real resolution. Internally xls stores 16:45.81 as a Number and associates some formatting with it. I believe the issue has something to do with the spreadsheet gem not correctly handling the cell format.

I did try messing around with adding a format mm:ss.0 by following this guide but I couldn't get it to work, maybe you'll have more luck.

Body:
I'm on Rails 5 (Ruby 2.4).  I want to read an .xls doc and I would like to get the data into CSV format, just as it appears in the Excel file.  Someone recommended I use Roo, and so I have

book = Roo::Spreadsheet.open(file_location)
sheet = book.sheet(0)
text = sheet.to_csv
arr_of_arrs = CSV.parse(text)

However what is getting returned is not the same as what I see in the spreadsheet.  For isntance, a cell in the spreadsheet has

16:45.81

and when I get the CSV data from above, what is returned is

"0.011641319444444444"

How do I parse the Excel doc and get exactly what I see?  I don't care if I use Roo to parse or not, just as long as I can get CSV data that is a representation of what I see rather than some weird internal representation.  For reference the file type I was parsing givies this when I run "file name_of_file.xls" ...

Composite Document File V2 Document, Little Endian, Os: Windows, Version 5.1, Code page: 1252, Author: Dwight Schroot, Last Saved By: Dwight Schroot, Name of Creating Application: Microsoft Excel, Create Time/Date: Tue Sep 21 17:05:21 2010, Last Saved Time/Date: Wed Oct 13 16:52:14 2010, Security: 0


问:
Cannot get initial React Native App to Run
Description

I can't get an initial React Native app to run, following a basic tutorial. The error seems to have to do with UIUserInterfaceIdiomCarPlay.

Reproduction Steps and Sample Code

Following the tutorial here https://facebook.github.io/react-native/releases/0.23/docs/tutorial.html#content

I created a new React Native project react-native init AwesomeProject
Then went into the directory, and ran react-native run-ios

Note I also tried from Xcode, and the myriad fixes online, but still no dice. This is the error I got:

/Users/lauracressman/Desktop/AwesomeProject/node_modules/react-native/React/Base/RCTPlatform.m:26:10: error: use of undeclared identifier 'UIUserInterfaceIdiomCarPlay'; did you mean 'UIUserInterfaceIdiomPad'?
    case UIUserInterfaceIdiomCarPlay:
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~
         UIUserInterfaceIdiomPad
In module 'UIKit' imported from /Users/lauracressman/Desktop/AwesomeProject/node_modules/react-native/React/Base/RCTPlatform.m:12:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator9.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIDevice.h:33:5: note: 'UIUserInterfaceIdiomPad' declared here
    UIUserInterfaceIdiomPad NS_ENUM_AVAILABLE_IOS(3_2), // iPad style UI
    ^
/Users/lauracressman/Desktop/AwesomeProject/node_modules/react-native/React/Base/RCTPlatform.m:26:10: error: duplicate case value 'UIUserInterfaceIdiomPad'
    case UIUserInterfaceIdiomCarPlay:
         ^
/Users/lauracressman/Desktop/AwesomeProject/node_modules/react-native/React/Base/RCTPlatform.m:22:10: note: previous case defined here
    case UIUserInterfaceIdiomPad:
         ^
2 errors generated.

Additional Information

React Native version: 0.42.3

Platform: iOS

Development Operating System: MacOS

Dev tools: Xcode, command line

答: Someone was recently facing the same problem with that error message Use of undeclared identifier 'UIUserInterfaceIdiomCarPlay'; did you mean 'UIUserInterfaceIdiomPad'?. He commented out lines 26 & 27 from node_modules/react-native/React/Base/RCTPlatform.m and apparently got it to work. It might be related to using an outdated version of Xcode


问:
How to conciliate the best Object Oriented Programming practices in getters and setters with the needs of ORMs frameworks?
In many of systems I have worked in, the class that represents a model is a POJO, and we map their fields to columns (in relational databases) or attributes (in some NoSQL databases). So, em many ORMs, it is mandatory to have accessors methods to take and bring data from/to database.
However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object

Let's give an example. Let's say we have a class Client. This class has an ID, the customer's name e its date of last change. We cannot change this data directly, but we want to persist them. If we want to modify the client's name, we must also change the ID and the last change date.

The ORM needs of following getters and setters methods, so that we have:

```<code>@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}
</code>```

The way it is, anyone, besides the ORM, could change the ID and last change date, causing unwanted effects on the rest of the system.

Instead, if we wanted to respect the Oriented Object rules, we have something like this:

```<code>@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}
</code>```

So, my question is: how we conciliate the best practices of Object Oriented Programming with the needs of getters and setters in ORMs frameworks?

答:
An ORM like JDXA (Disclaimer: I am the architect of JDXA ORM for Android) can solve the problem by using a non-standard alternate setter method (for example, with the following signature) to set an attribute value:

```<code>void setAttribValue(String attribName, Object Value)
</code>```

So, rest of the developers would not see and (ab)use a 'standard' bean setter method but the ORM can employ this alternate method for its own use. For example, in your case, JDXA can work with the following class definition:

```<code>public class Client {

  private Long id;
  private String name;
  private Date lastChange;
  private int something;

  public Client() {
  }

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date getLastChange() {
    return this.lastChange;
  }

  public int getSomething() {
     return something;
  }

  // May be OK to expose this bean style setter method
  public void setSomething(int something) {
    this.something = something;
  }

  // JDXA ORM will automatically use this method to set values of those
  // attributes for which it cannot find a 'regular' setter method.
  public void setAttribValue(String attribName, Object value) {
    switch (attribName) {
        case "id":
           this.id = (Long) value;
           break;
        case "name":
           this.name = (String) value;
           break;
        case "lastChange":
           this.lastChange = (Date) value;
           break;
        default:
           throw new IllegalArgumentException("Invalid attribute name: " + attribName);
      }
      return;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = getNewIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}
</code>```

Body:
In many of systems I have worked in, the class that represents a model is a POJO, and we map their fields to columns (in relational databases) or attributes (in some NoSQL databases). So, em many ORMs, it is mandatory to have accessors methods to take and bring data from/to database.
However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object

Let's give an example. Let's say we have a class Client. This class has an ID, the customer's name e its date of last change. We cannot change this data directly, but we want to persist them. If we want to modify the client's name, we must also change the ID and the last change date.

The ORM needs of following getters and setters methods, so that we have:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}

The way it is, anyone, besides the ORM, could change the ID and last change date, causing unwanted effects on the rest of the system.

Instead, if we wanted to respect the Oriented Object rules, we have something like this:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}

So, my question is: how we conciliate the best practices of Object Oriented Programming with the needs of getters and setters in ORMs frameworks?

Body:
An ORM like JDXA (Disclaimer: I am the architect of JDXA ORM for Android) can solve the problem by using a non-standard alternate setter method (for example, with the following signature) to set an attribute value:

void setAttribValue(String attribName, Object Value)

So, rest of the developers would not see and (ab)use a 'standard' bean setter method but the ORM can employ this alternate method for its own use. For example, in your case, JDXA can work with the following class definition:

public class Client {

  private Long id;
  private String name;
  private Date lastChange;
  private int something;

  public Client() {
  }

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date getLastChange() {
    return this.lastChange;
  }

  public int getSomething() {
     return something;
  }

  // May be OK to expose this bean style setter method
  public void setSomething(int something) {
    this.something = something;
  }

  // JDXA ORM will automatically use this method to set values of those
  // attributes for which it cannot find a 'regular' setter method.
  public void setAttribValue(String attribName, Object value) {
    switch (attribName) {
        case "id":
           this.id = (Long) value;
           break;
        case "name":
           this.name = (String) value;
           break;
        case "lastChange":
           this.lastChange = (Date) value;
           break;
        default:
           throw new IllegalArgumentException("Invalid attribute name: " + attribName);
      }
      return;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = getNewIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}


问:
PHP Mysql table fetch only gives first row
```<code>$query = "SELECT * FROM pass";
$result = mysql_query($query,$conn);
echo mysql_num_rows($result);

while($row = mysql_fetch_array($result))
{
    $username = $row['user'];
    $password = $row['pass'];
}
</code>```

Num rows = 12 but while loops only the first one if I use in while $row = mysql_fetch_array(mysql_query("SELECT * FROM pass",$conn))

If i use the first code it gives error after the first row,
Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in

答:
you define the variables wrong if you don't give it a number it will always only have 1 result and do some reading about newer ways to connect to mysql database</p>

```<code>$i = 0;
while($row = mysql_fetch_assoc($result))
{
    $username[$i] = $row['user'];
    $password[$i] = $row['pass'];
    $i++;
}

//you can test like this
$r = 0;
while($r < $i)
{
    echo $username[$r];
    echo $password[$r];
    $r++;
}
</code>```

Body:
$query = "SELECT * FROM pass";
$result = mysql_query($query,$conn);
echo mysql_num_rows($result);

while($row = mysql_fetch_array($result))
{
    $username = $row['user'];
    $password = $row['pass'];
}

Num rows = 12 but while loops only the first one if I use in while $row = mysql_fetch_array(mysql_query("SELECT * FROM pass",$conn))

If i use the first code it gives error after the first row,
Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in

Body:
you define the variables wrong if you don't give it a number it will always only have 1 result and do some reading about newer ways to connect to mysql database

$i = 0;
while($row = mysql_fetch_assoc($result))
{
    $username[$i] = $row['user'];
    $password[$i] = $row['pass'];
    $i++;
}

//you can test like this
$r = 0;
while($r < $i)
{
    echo $username[$r];
    echo $password[$r];
    $r++;
}


问:
How to create a sub menu from an ImageMap
I have a Nav bar that I created and it is 1 image with multiple image maps... is it possible to make sub menus from the image maps in the image/Nav Bar?</p>

答:
Instead of an image map, you should use a hidden unordered list for the sub menu (and show it with javascript when appropriate)

something like:

```<code><a href="#" id="menuitem1">Menu Item</a>
<ul class="submenu" style="display: none;">
  <li><a href="/path">Item 1</a></li>
  <li><a href="/path">Item 2</a></li>
  <li><a href="/path">Item 3</a></li>
</ul>
</code>```

JS:

```<code>$("#menuitem1").click(function() {
  $(this).next().show();
});
</code>```

Body:
Instead of an image map, you should use a hidden unordered list for the sub menu (and show it with javascript when appropriate)

something like:

<a href="#" id="menuitem1">Menu Item</a>
<ul class="submenu" style="display: none;">
  <li><a href="/path">Item 1</a></li>
  <li><a href="/path">Item 2</a></li>
  <li><a href="/path">Item 3</a></li>
</ul>

JS:

$("#menuitem1").click(function() {
  $(this).next().show();
});


问:
How to calculate difference between dates in R
I am working on a project right now and encountered this problem.

I have a dataset consisting of two dates columns. One, say it x1, stands for check-in dates, the other, say it x2, stands for check-out dates.

Both of them are in the "year-month-day" format and have the type of string.

What I would like to do is figuring out how long does a person stay using check-in, check-out dates. I've tried multiple functions like as.Date. But all failed and I believe I just can't subtract these two dates directly as the results wouldn't represent the actual stay length.

Does anybody have any idea on how to do this in R?

Thanks!

答:
If I understood your question, you want the difference between checkout and checkin? I would try this:</p>

```<code>library(lubridate)
df<-data.frame(x1=c("2017-03-23","2017-03-24"),x2=c("2017-03-24","2017-03-28"))
df[]<-lapply(df,ymd)
df$x2-df$x1
</code>```

Body:
If I understood your question, you want the difference between checkout and checkin? I would try this:

library(lubridate)
df<-data.frame(x1=c("2017-03-23","2017-03-24"),x2=c("2017-03-24","2017-03-28"))
df[]<-lapply(df,ymd)
df$x2-df$x1


答:
For CONDITIONALS you need to use comparison operator == not the assignment operator which is =.

Check this out: https://www.tutorialspoint.com/python/python_basic_operators.htm

Hope that helps!

Title: Syntax error on simple if condition (if partychoice = R:)

Body:
New programmer, working in python 2.7.

With this code, I get a syntax error in the line 'if partychoice = R, stating the '=' is invalid syntax. How come it won;t let me assign the variable.

Also, I'm sure there are tons of other errors, but I have to start somewhere.

print "Welcome to 'Pass the Bill', where you will take on the role of a professional lobbyist trying to guide a bill through Congress and get it signed into law by the President!"
start = raw_input(str ('Press Y to continue:'))
print 'Great, lets get started!'
partychoice = raw_input (str("Would you like to be a Republican or Democrat? Type 'R' for Republican or 'D' for Democrat."))
if partychoice = R:
    print 'Ah, the Grand old Party of Lincoln and Reagan. Great Choice!'
    replegchoice = raw_input (str("What type of bill what you like congress to introduce? Restrictions on abortions, lower income taxes, easier access to automatic weapons, private health plans, or stricter immigration laws? ( A = abortion restrictions, L = lower taxes, AW = automatic weapons, H = private health plans, S = stricter immigration laws'))
    if replegchoice = A or a
            print 'A controversial choice, despite support of most Republicans, you are sure to face opposition from Democrats in Congress!'
    if replegchoice = L or l
            print 'A popular idea, Republicans in Congress are sure to support this idea, as will many American voters!'
    if replegchoice = AW, aw, Aw, or AW
            print 'Rural, midwest, and small town voters will love this, as will most Republicans in Congress. Democrats and voters in urban cities will surely be less supportive.'
    if replegchoice = H or h
            print 'Eimination of Medicare, Medicaid, and Obamacare! Republicans generally like the idea of making each person responsible for paying their own health care costs'
    if replegchoice = S or s
            print 'a popular idea supported by president Trump, this is sure face strong opposition from democrats and many voters.'

Thanks everyone.


问:
I am getting an internal server error on my local Python server when authenticating to Yelp API
I am trying to authenticate to the Yelp API and this is what I'm getting:

{ "error": { "description": "client_id or client_secret parameters not found. Make sure to provide client_id and client_secret in the body with the application/x-www-form-urlencoded content-type", "code": "VALIDATION_ERROR" } }

This is the method I have defined in Python and I am have installed Python Flask. I have never worked with an API before this:

```<code>@app.route("/run_post")
def run_post():
   url = "https://api.yelp.com/oauth2/token"
   data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'Content-type': 'application/x-www-form-urlencoded'}

   body = requests.post(url, data=json.dumps(data))

   return json.dumps(body.json(), indent=4)
</code>```

答:
The data should be passed as application/x-www-form-urlencoded, so you should not serialize request parameters. You also should not specify Content-Type as parameter, it belongs to request headers.

The final code:

```<code>@app.route("/run_post")
def run_post():
   url = "https://api.yelp.com/oauth2/token"
   data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET}

   body = requests.post(url, data=data)

   return json.dumps(body.json(), indent=4)
</code>```

Body:
I am trying to authenticate to the Yelp API and this is what I'm getting:

{ "error": { "description": "client_id or client_secret parameters not found. Make sure to provide client_id and client_secret in the body with the application/x-www-form-urlencoded content-type", "code": "VALIDATION_ERROR" } }

This is the method I have defined in Python and I am have installed Python Flask. I have never worked with an API before this:

@app.route("/run_post")
def run_post():
   url = "https://api.yelp.com/oauth2/token"
   data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'Content-type': 'application/x-www-form-urlencoded'}

   body = requests.post(url, data=json.dumps(data))

   return json.dumps(body.json(), indent=4)

Body:
The data should be passed as application/x-www-form-urlencoded, so you should not serialize request parameters. You also should not specify Content-Type as parameter, it belongs to request headers.

The final code:

@app.route("/run_post")
def run_post():
   url = "https://api.yelp.com/oauth2/token"
   data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET}

   body = requests.post(url, data=data)

   return json.dumps(body.json(), indent=4)


问:
Connect local ftp server with Android
I have made an ftp server in a Local drive of my laptop and assigned an IP address to it. I want to fetch excel files on that server using my android app and process the data.
How can I go about this?
Is Commons Apache the way to it?</p>

答:
This was the snippet I made and worked for me.</p>

```<code>     FTPClient ftpClient = new FTPClient();
                try {
                    ftpClient.connect("192.168.5.3", 21);
                    ftpClient.enterLocalPassiveMode();
                    ftpClient.login("FTP_User", "ravi1998");

                    ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);

                    InputStream inStream = ftpClient.retrieveFileStream("record.xls");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "done", Toast.LENGTH_SHORT).show();

                        }
                    });
                    ftpClient.disconnect();
                    Workbook wb = Workbook.getWorkbook(inStream);
                    Sheet s = wb.getSheet(0);
                    int row = s.getRows();
                    int col = s.getColumns();

                    for (int i = 0; i < row; i++) {
                      for(int c = 0, c< col; c++){
                        Cell z = s.getCell(c, i);
                        String content = z.getContents();
                       }
                    }
</code>```

Title: Connect local ftp server with Android

Body:
This was the snippet I made and worked for me.

     FTPClient ftpClient = new FTPClient();
                try {
                    ftpClient.connect("192.168.5.3", 21);
                    ftpClient.enterLocalPassiveMode();
                    ftpClient.login("FTP_User", "ravi1998");

                    ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);

                    InputStream inStream = ftpClient.retrieveFileStream("record.xls");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "done", Toast.LENGTH_SHORT).show();

                        }
                    });
                    ftpClient.disconnect();
                    Workbook wb = Workbook.getWorkbook(inStream);
                    Sheet s = wb.getSheet(0);
                    int row = s.getRows();
                    int col = s.getColumns();

                    for (int i = 0; i < row; i++) {
                      for(int c = 0, c< col; c++){
                        Cell z = s.getCell(c, i);
                        String content = z.getContents();
                       }
                    }


问:
Insert a point into a mysql column
I'm trying to insert a point into a mysql column. However, when I try to retrieve the point, it says just "?? ??"

```<code>CREATE TABLE geom (g GEOMETRY);
ALTER TABLE geom ADD pt POINT;
INSERT INTO geom VALUES (GeomFromText('POINT(1 1)'));
</code>```

The lines above are the ones that I use to create the table and to insert the point.

When I perform SELECT * FROM GEOM, I got the result below

If you pay attention, these lines are the same available here: https://dev.mysql.com/doc/refman/5.6/en/populating-spatial-columns.html

I spent some hours on this problem and I see many questions here about this issue. None of them helped me to solve the problem. If you know something, please tell me.

Thank you!

答:
Try: SELECT ST_AsText(pt) instead.

Read more here: https://dev.mysql.com/doc/refman/5.7/en/gis-format-conversion-functions.html

Title: Insert a point into a mysql column

Body:
I'm trying to insert a point into a mysql column. However, when I try to retrieve the point, it says just "?? ??"

CREATE TABLE geom (g GEOMETRY);
ALTER TABLE geom ADD pt POINT;
INSERT INTO geom VALUES (GeomFromText('POINT(1 1)'));

The lines above are the ones that I use to create the table and to insert the point.

When I perform SELECT * FROM GEOM, I got the result below

If you pay attention, these lines are the same available here: https://dev.mysql.com/doc/refman/5.6/en/populating-spatial-columns.html

I spent some hours on this problem and I see many questions here about this issue. None of them helped me to solve the problem. If you know something, please tell me.

Thank you!