问:
Design issue with the bootstrap based form in iphone browser
I have a blog page where user can post comments, comment form shows up as a bootstrap modal when user click on a link or button.

This website is designed in asp.net webform just in case information is helpful

Since i cant put all the code i have just put related code of the page with css & JS.

This form works fine on Desktop browser and also on samsung browser but same breaks on iphone.

Form has multiple fields for input Name, Email, Country, Comments etc

When i start to enter Name cursor show below the Name inputbox and when i enter email cursor show almost two row below the email input feild..
I am adding screen for reference and also Codepen link

1[]2

I am not sure why it is breaking as i am not able to debut it in Iphone

```<code><div class="modal fade in" id="commentModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="display: block;" aria-hidden="false">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Comment</h4>
      </div>
      <div class="modal-body">

        <!--- UpdatePanel -->
        <div id="MainContent_UpdatePanel1">

          <!--- Code -HERE -->
          <div id="MainContent_pnlForm">

            <div class="comment-intro-w">
              <span id="MainContent_lblCommentMsg" class="txtLabelComment">All fields are mandatory.</span>
            </div>

            <div data-val-validationgroup="vgCommentForm" id="MainContent_vsCommentForm" class="validation-sum" data-valsummary="true" style="display:none;">

            </div>

            <div class="comment-fullname-w">

              <input name="ctl00$MainContent$txtCommentFullName" id="MainContent_txtCommentFullName" tabindex="1" class="txt-comment-fn" placeholder="Full Name" type="text">
              <span data-val-controltovalidate="MainContent_txtCommentFullName" data-val-errormessage="Name can't be blank" data-val-validationgroup="vgCommentForm" id="MainContent_rfv1" class="dp-comment-validation" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid"
                data-val-initialvalue="" style="visibility:hidden;">Name can't be blank</span>
            </div>

            <div class="comment-email-w">

              <input name="ctl00$MainContent$txtCommentEmail" id="MainContent_txtCommentEmail" tabindex="1" class="txt-comment-fn" placeholder="Email" type="text">
              <span data-val-controltovalidate="MainContent_txtCommentEmail" data-val-errormessage="Email can't be blank" data-val-validationgroup="vgCommentForm" id="MainContent_rfvEmail" class="dp-comment-validation" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid"
                data-val-initialvalue="" style="visibility:hidden;">Email can't be blank</span>
              <span data-val-controltovalidate="MainContent_txtCommentEmail" data-val-errormessage="Enter correct email" data-val-validationgroup="vgCommentForm" id="MainContent_revEmail" class="dp-comment-validation" data-val="true" data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid"
                data-val-validationexpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" style="visibility:hidden;">Enter correct email</span>
            </div>

            <div class="comment-country-w">
              <select name="ctl00$MainContent$ddCountry" id="MainContent_ddCountry" tabindex="3" class="dd-comment-country">
            <option value="">Country</option>
            <option value="AF">Afghanistan</option>
            <option value="AL">Albania</option>

        </select>
              <span data-val-controltovalidate="MainContent_ddCountry" data-val-errormessage="Select Country" data-val-validationgroup="vgCommentForm" id="MainContent_rfvddC" class="dp-comment-validation" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid"
                data-val-initialvalue="" style="visibility:hidden;">Select Country</span>
            </div>

            <div class="comment-message-w">
              <textarea name="ctl00$MainContent$txtCommentMessage" rows="5" cols="20" id="MainContent_txtCommentMessage" tabindex="4" class="txt-comment-msg" placeholder="Message"></textarea>
              <span data-val-controltovalidate="MainContent_txtCommentMessage" data-val-errormessage="Message can't be blank" data-val-validationgroup="vgCommentForm" id="MainContent_rfvmsg" class="dp-comment-validation" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid"
                data-val-initialvalue="" style="visibility:hidden;">Message can't be blank</span>
            </div>

            <div class="comment-anonymous-w">
              <span class="chk-anonymous"><input id="MainContent_cbAnonymous" name="ctl00$MainContent$cbAnonymous" type="checkbox"><label for="MainContent_cbAnonymous">I wish to be anonymous. Do not publish my name with my comment.</label></span>
            </div>

            <div class="comment-btnsave-w">
              <input name="ctl00$MainContent$btnSaveComments" value="Post Comment" onclick="ClientSideClick(this);WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$btnSaveComments", "", true, "vgCommentForm", "", false, true))"
                id="MainContent_btnSaveComments" class="buttonPopups" type="button">
            </div>

          </div>

          <!--- Code -HERE -->

        </div>
        <!--- UpdatePanel -->
      </div>
    </div>
  </div>
</div>
</code>```

答:
I found the solution it seems to work .modal-open { position: fixed; width: 100%; }

It seems like a bug in iOS. Any other solution is welcome

Personally, position: fixed scroll to top automatically. Quite annoying !

To avoid penalizing other devices and versions I apply this fix only to the appropriate versions of iOS.

For the javascript/jQuery

```<code>$(document).ready(function() {

    // Detect ios 11_0_x affected
    // NEED TO BE UPDATED if new versions are affected
    var ua = navigator.userAgent,
    iOS = /iPad|iPhone|iPod/.test(ua),
    iOS11 = /OS 11_0_1|OS 11_0_2|OS 11_0_3|OS 11_1/.test(ua);

    // ios 11 bug caret position
    if ( iOS && iOS11 ) {

        // Add CSS class to body
        $("body").addClass("iosBugFixCaret");

    }

}

For the CSS

/* Apply CSS to iOS affected versions only */
body.iosBugFixCaret.modal-open { position: fixed; width: 100%; }
</code>```

Reference Source iOS 11 Safari bootstrap modal text area outside of cursor

Body:
I have a blog page where user can post comments, comment form shows up as a bootstrap modal when user click on a link or button.

This website is designed in asp.net webform just in case information is helpful

Since i cant put all the code i have just put related code of the page with css & JS.

This form works fine on Desktop browser and also on samsung browser but same breaks on iphone.

Form has multiple fields for input Name, Email, Country, Comments etc

When i start to enter Name cursor show below the Name inputbox and when i enter email cursor show almost two row below the email input feild..
I am adding screen for reference and also Codepen link

1[]2

I am not sure why it is breaking as i am not able to debut it in Iphone

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Comment

              All fields are mandatory.

              <input name="ctl00$MainContent$txtCommentFullName" id="MainContent_txtCommentFullName" tabindex="1" class="txt-comment-fn" placeholder="Full Name" type="text">
              Name can't be blank

              <input name="ctl00$MainContent$txtCommentEmail" id="MainContent_txtCommentEmail" tabindex="1" class="txt-comment-fn" placeholder="Email" type="text">
              Email can't be blank
              Enter correct email

              <select name="ctl00$MainContent$ddCountry" id="MainContent_ddCountry" tabindex="3" class="dd-comment-country">
            <option value="">Country</option>
            <option value="AF">Afghanistan</option>
            <option value="AL">Albania</option>

        </select>
              Select Country

              <textarea name="ctl00$MainContent$txtCommentMessage" rows="5" cols="20" id="MainContent_txtCommentMessage" tabindex="4" class="txt-comment-msg" placeholder="Message"></textarea>
              Message can't be blank

              <input id="MainContent_cbAnonymous" name="ctl00$MainContent$cbAnonymous" type="checkbox">I wish to be anonymous. Do not publish my name with my comment.

              <input name="ctl00$MainContent$btnSaveComments" value="Post Comment" onclick="ClientSideClick(this);WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$btnSaveComments", "", true, "vgCommentForm", "", false, true))"
                id="MainContent_btnSaveComments" class="buttonPopups" type="button">

Body:
I found the solution it seems to work .modal-open { position: fixed; width: 100%; }

It seems like a bug in iOS. Any other solution is welcome

Personally, position: fixed scroll to top automatically. Quite annoying !

To avoid penalizing other devices and versions I apply this fix only to the appropriate versions of iOS.

For the javascript/jQuery

$(document).ready(function() {

    // Detect ios 11_0_x affected
    // NEED TO BE UPDATED if new versions are affected
    var ua = navigator.userAgent,
    iOS = /iPad|iPhone|iPod/.test(ua),
    iOS11 = /OS 11_0_1|OS 11_0_2|OS 11_0_3|OS 11_1/.test(ua);

    // ios 11 bug caret position
    if ( iOS && iOS11 ) {

        // Add CSS class to body
        $("body").addClass("iosBugFixCaret");

    }

}

For the CSS

/* Apply CSS to iOS affected versions only */
body.iosBugFixCaret.modal-open { position: fixed; width: 100%; }

Reference Source iOS 11 Safari bootstrap modal text area outside of cursor


来源: stackexchange

问:
How to get weights in tf.layers.dense?
I wanna draw the weights of tf.layers.dense in tensorboard histogram, but it not show in the parameter, how could I do that?</p>

答:
The latest tensorflow layers api creates all the variables using the tf.get_variable call. This ensures that if you wish to use the variable again, you can just use the tf.get_variable function and provide the name of the variable that you wish to obtain.

In the case of a tf.layers.dense, the variable is created as: layer_name/kernel. So, you can obtain the variable by saying:

```<code>with tf.variable_scope("layer_name", reuse=True):
    weights = tf.get_variable("kernel") # do not specify
    # the shape here or it will confuse tensorflow into creating a new one.
</code>```

[Edit]: The new version of Tensorflow now has both Functional and Object-Oriented interfaces to the layers api. If you need the layers only for computational purposes, then using the functional api is a good choice. The function names start with small letters for instance -> tf.layers.dense(...). The Layer Objects can be created using capital first letters e.g. -> tf.layers.Dense(...). Once you have a handle to this layer object, you can use all of its functionality. For obtaining the weights, just use obj.trainable_weights this returns a list of all the trainable variables found in that layer's scope.

ContentLicense: CC BY-SA 3.0

Title: How to get weights in tf.layers.dense?

Body:
The latest tensorflow layers api creates all the variables using the tf.get_variable call. This ensures that if you wish to use the variable again, you can just use the tf.get_variable function and provide the name of the variable that you wish to obtain.

In the case of a tf.layers.dense, the variable is created as: layer_name/kernel. So, you can obtain the variable by saying:

with tf.variable_scope("layer_name", reuse=True):
    weights = tf.get_variable("kernel") # do not specify
    # the shape here or it will confuse tensorflow into creating a new one.

[Edit]: The new version of Tensorflow now has both Functional and Object-Oriented interfaces to the layers api. If you need the layers only for computational purposes, then using the functional api is a good choice. The function names start with small letters for instance -> tf.layers.dense(...). The Layer Objects can be created using capital first letters e.g. -> tf.layers.Dense(...). Once you have a handle to this layer object, you can use all of its functionality. For obtaining the weights, just use obj.trainable_weights this returns a list of all the trainable variables found in that layer's scope.


问:
Java: is there a way to convert text into a class?
I have the input: "ListClients param1 param2"
which splits by " " to "ListClients", "param1", "param2";

and I want to call a static method from ListClients.

So it would do ListClients.someMethodThatTakesPraams(param1, param2);

is there a way to do that in java?

答:
Yes you can use reflection. Below is an e.g. of creating a new instance

```<code>Class<Object> fc = Class.forName("ListClients");
   Object myObj = fc.newInstance();
</code>```

Here are some examples of invoking methods

ContentLicense: CC BY-SA 2.5

Body:
Yes you can use reflection. Below is an e.g. of creating a new instance

Class<Object> fc = Class.forName("ListClients");
   Object myObj = fc.newInstance();

Here are some examples of invoking methods


问:
Django form validation don't function
I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution.
This is my code:
(The variables of class are indented)

```<code>class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

def clean_question(self):
     question = self.cleaned_data.get('question')
     a = "0"
     if not a in question:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return question

def clean_answer(self):
     answer = self.cleaned_data.get('answer')
     a = "0"
     if not a in answer:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return answer
</code>```

Also I have try this way:

```<code>def clean(self, *args, **kwargs):
        question = self.cleaned_data.get('question')
        answer = self.cleaned_data.get('answer')
        if question != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        if answer != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return super(QuestionForm, self).clean(*args, **kwargs)
</code>```

In this case the view corresponding to this form is the following one:

```<code>def ayudanos(request):
    form = QuestionForm(request.POST or None)
    if form.is_valid():
        form_data = form.cleaned_data
        subject = form_data.get("subject")
        question = form_data.get("question")
        answer = form_data.get("answer")
        answerOne = form_data.get("answerOne")
        answerTwo = form_data.get("answerTwo")
        name = form_data.get("name")
        obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                          answerTwo=answerTwo, name=name)
    context = {
        "form": form
    }
    return render(request, "ayudanos.html", context)
</code>```

Where the variables passed to the object is for save in a BBDD.

ACTUALIZED--------------------

After try the options people recommended my in the comments, I didn't see the validation message, and the moment I have remove the part of code which reload page after doing the form I could see the validation message.

my html and JavaScript:

```<code><div class="col-md-6">
        {% if form %}
        <form action="" method="POST" id="askFortm"> {% csrf_token %}
          {{ form.as_p }}
          <button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
              pregunta</button>
          </form>
          {% endif %}
    </div>

<script>

    $(function() {
        var counter = 94;
        $( "#enviar" ).click(function() {
            counter = counter + 1;
                //alert(counter);
                localStorage.setItem("counter",counter);
                alert('Su pregunta ha sido enviada correctamente. ' +
                    'Envía otra y tendras más posibilidades de ganar los Airpods.');
            });
        $('#askFortm').on('submit', function(e) {
              e.preventDefault();
              setTimeout(function() {
                   window.location.reload();
              },0);
              this.submit();
        });
    });

    </script>
</code>```

I suppose that the problem can be relation with the reload page,  is possible I have to compare the csrf_token or something like this?
Can you help me, thanks.

答:
I believe when the user did not give the value in the must field Question or answer, it will be empty , so below code should work.</p>

```<code>class QuestionForm(forms.Form):
    subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
    question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
    answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
    answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

    def clean_question(self):
        question = self.cleaned_data.get('question')

        if not question:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return question

    def clean_answer(self):
        answer = self.cleaned_data.get('answer')

        if not answer:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return answer
</code>```

ContentLicense: CC BY-SA 4.0

Title: Django form validation don't function

Body:
I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution.
This is my code:
(The variables of class are indented)

class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

def clean_question(self):
     question = self.cleaned_data.get('question')
     a = "0"
     if not a in question:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return question

def clean_answer(self):
     answer = self.cleaned_data.get('answer')
     a = "0"
     if not a in answer:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return answer

Also I have try this way:

def clean(self, *args, **kwargs):
        question = self.cleaned_data.get('question')
        answer = self.cleaned_data.get('answer')
        if question != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        if answer != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return super(QuestionForm, self).clean(*args, **kwargs)

In this case the view corresponding to this form is the following one:

def ayudanos(request):
    form = QuestionForm(request.POST or None)
    if form.is_valid():
        form_data = form.cleaned_data
        subject = form_data.get("subject")
        question = form_data.get("question")
        answer = form_data.get("answer")
        answerOne = form_data.get("answerOne")
        answerTwo = form_data.get("answerTwo")
        name = form_data.get("name")
        obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                          answerTwo=answerTwo, name=name)
    context = {
        "form": form
    }
    return render(request, "ayudanos.html", context)

Where the variables passed to the object is for save in a BBDD.

ACTUALIZED--------------------

After try the options people recommended my in the comments, I didn't see the validation message, and the moment I have remove the part of code which reload page after doing the form I could see the validation message.

my html and JavaScript:

        {% if form %}
        <form action="" method="POST" id="askFortm"> {% csrf_token %}
          {{ form.as_p }}
          <button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
              pregunta</button>
          </form>
          {% endif %}

I suppose that the problem can be relation with the reload page,  is possible I have to compare the csrf_token or something like this?
Can you help me, thanks.

Body:
I believe when the user did not give the value in the must field Question or answer, it will be empty , so below code should work.

class QuestionForm(forms.Form):
    subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
    question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
    answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
    answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

    def clean_question(self):
        question = self.cleaned_data.get('question')

        if not question:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return question

    def clean_answer(self):
        answer = self.cleaned_data.get('answer')

        if not answer:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return answer


问:
android type_step_counter value stop counting up when app not in background
I am using type_step_counter sensor in Service to get the step value from android phone. It gives me the value as I expected. When I close my app, shake the phone, and then open again the app, the step value from the sensor counts up (this is also as I expected).

However, when I swipe the app from the background, shake the phone, and then open again the app, the value from the sensor doesn't increase.

I read the android documentation of type_step_counter that if we want the counter to keep working while the app stopped, we should not unregister the sensor if we want it to continuously working (see this). So, I don't unregister it, but it stopped counting.

Here is my code (sorry not to put all code for security reason):

```<code>public void onCreate(){
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}

public int onStartCommand(Intent intent, int flags, int startId){
    // edited (it was unregister)
    mSensorManager.registerListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL);

    return START_STICKY;
}

public void onSensorChanged(SensorEvent event){
    float[] values = event.values;
    Log.d("onSensorChanged", "value: " + String.valueOf(values[0])); // <-- this value does not increase after app stopped
}
</code>```

Does anyone has any clue on this?
Thanks in advance.

答:
when I swipe the app from the background - this means your app is completely closed.

START_STICKY will keep the service running even after application is closed.

On reopening application i think you are starting this service again and so OnStartCommand will be called.

```<code> mSensorManager.unregisterListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL);
</code>```

Then the type_step_counter will be reinitialized.

You can have a look at this for your criteria

https://developer.android.com/training/sync-adapters/creating-sync-adapter.html

Body:
I am using type_step_counter sensor in Service to get the step value from android phone. It gives me the value as I expected. When I close my app, shake the phone, and then open again the app, the step value from the sensor counts up (this is also as I expected).

However, when I swipe the app from the background, shake the phone, and then open again the app, the value from the sensor doesn't increase.

I read the android documentation of type_step_counter that if we want the counter to keep working while the app stopped, we should not unregister the sensor if we want it to continuously working (see this). So, I don't unregister it, but it stopped counting.

Here is my code (sorry not to put all code for security reason):

public void onCreate(){
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}

public int onStartCommand(Intent intent, int flags, int startId){
    // edited (it was unregister)
    mSensorManager.registerListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL);

    return START_STICKY;
}

public void onSensorChanged(SensorEvent event){
    float[] values = event.values;
    Log.d("onSensorChanged", "value: " + String.valueOf(values[0])); // <-- this value does not increase after app stopped
}

Does anyone has any clue on this?
Thanks in advance.

Body:
when I swipe the app from the background - this means your app is completely closed.

START_STICKY will keep the service running even after application is closed.

On reopening application i think you are starting this service again and so OnStartCommand will be called.

 mSensorManager.unregisterListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL);

Then the type_step_counter will be reinitialized.

You can have a look at this for your criteria

https://developer.android.com/training/sync-adapters/creating-sync-adapter.html


问:
Deserializing from Json throw exception
I am reading a JSOn text in my application as follow, I replaced the special characters as well..

```<code>    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new StringReader("[{ \"alg\":\"rf\", \"response_variable\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"regressionparam\":{ \"maxIterations\":10, \"objReg\":0.3, \"ntrees\":35, \"nbins\":10, \"maxDepth\":5, \"scoreTreeInterval\":10, \"epochs\":0.0, \"hidden\":[ 200, 200 ], \"sparse\":true, \"activation\":\"Tanh\", \"stopping_metric\":\"AUTO\", \"stopping_tolerance\":0.001, \"max_runtime_secs\":0.0, \"overwrite_with_best_model\":true, \"missing_values_handling\":\"MeanImputation\", \"weight_column\":\"\", \"standardize\":true, \"score_interval\":10, \"ignore_const_cols\":true, \"distribution\":\"AUTO\", \"number_of_similiar_clusters\":1, \"estimate_k\":false, \"family\":\"gaussian\" }, \"aggParam\":{ \"nodeId\":\"d7c3d762-6078-4f98-a5a4-cc164c76fb34\", \"features\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ], \"dataTypeToFeatureMap\":{ \"ANALOG\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ] }, \"predictor\":{ \"fnodeid\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"nodename\":\"PV\", \"sensordata_type\":\"ANALOG\" }, \"starttime\":1491235200000, \"endtime\":1506700800000, \"samplingRate\":10, \"samplingTimePeriod\":\"MINUTE\", \"aggregator\":\"AVG\" }, \"keyspace\":\"vroc\", \"phoenixHost\":\"auper01-01-20-01-0.prod.vroc.com.au:2181:/hbase-unsecure\", \"number_of_features\":1, \"feature_selection\":false, \"model_parameters_optimization\":false, \"training_ratio\":0.5, \"validation_ratio\":0.7, \"ttf_calculation\":false, \"ttf_threshold\":0.0, \"ttf_thershold_greater\":false, \"number_of_lags\":5, \"modelMetadata\":{ \"startedByUser\":\"Livy Demo\", \"userOrganization\":\"Livy Demo\", \"nodeName\":\"VROC.Rishi_trial.Update_test.try1_1\" } }]"));
    ModelParameter modelParam = gson.fromJson(reader, ModelParameter.class);
</code>```

The model parameter class is as follow:

```<code>package au.com.vroc.mdm.model;

import java.io.Serializable;

import com.google.gson.Gson;

/**
 * The Class ModelParameter.
 */
public class ModelParameter implements Serializable {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -8395899340046386755L;

    /** The alg. */
    public String alg = "rf";

    /** The response_variable. */
    public String response_variable = "";

    /** The regressionparam. */
    public RegressionParameter regressionparam = new RegressionParameter();

    /** The agg param. */
    public AggregationParameter aggParam = new AggregationParameter();;

    /** The keyspace. */
    public String keyspace = "vroctest";

    /** The keyspace. */
    public String phoenixHost = null;

    /** The automatic feature selection. */
    public Integer number_of_features =10 ;

    /** Feature selection. */
    public Boolean feature_selection =false ;

    /** The model parameter optimization. */
    public Boolean model_parameters_optimization=false;

    /** Training ratio. */
    public Double training_ratio=0.5;

    /** Validation ratio. */
    public Double validation_ratio=0.7;

    /** TTF calculation. */
    public Boolean ttf_calculation=false;

    /** TTF threshold. */
    public Double ttf_threshold=0.5;

    /** Values greater than TTF threshold become alarms otherwise values below threshold become alarm. */
    public Boolean ttf_thershold_greater=true;

    /** Number of lags. */
    public Integer number_of_lags=1;

    public ModelMetadata modelMetadata;

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return new Gson().toJson(this);
    }
}
</code>```

However, it throws exception like below:

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
        at com.google.gson.Gson.fromJson(Gson.java:803)
        at au.com.vroc.mdm.SparkSubmitModel.main(SparkSubmitModel.java:404)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code>```

I don't know what is wrong with the codes. Is there anything wrong with my model parameter class? I have very nested collections in my model parameter class as well..

答:
Looks like your json text contains an array of ModelParameter objects rather than a single one. So either you need to

remove the [] characters at the beginning and end of the json string to make it a json object

or parse it to an array of ModelParameter objects as below

ModelParameter[] modelParam = gson.fromJson(reader,ModelParameter[].class);

Title: Deserializing from Json throw exception

Body:
I am reading a JSOn text in my application as follow, I replaced the special characters as well..

    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new StringReader("[{ \"alg\":\"rf\", \"response_variable\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"regressionparam\":{ \"maxIterations\":10, \"objReg\":0.3, \"ntrees\":35, \"nbins\":10, \"maxDepth\":5, \"scoreTreeInterval\":10, \"epochs\":0.0, \"hidden\":[ 200, 200 ], \"sparse\":true, \"activation\":\"Tanh\", \"stopping_metric\":\"AUTO\", \"stopping_tolerance\":0.001, \"max_runtime_secs\":0.0, \"overwrite_with_best_model\":true, \"missing_values_handling\":\"MeanImputation\", \"weight_column\":\"\", \"standardize\":true, \"score_interval\":10, \"ignore_const_cols\":true, \"distribution\":\"AUTO\", \"number_of_similiar_clusters\":1, \"estimate_k\":false, \"family\":\"gaussian\" }, \"aggParam\":{ \"nodeId\":\"d7c3d762-6078-4f98-a5a4-cc164c76fb34\", \"features\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ], \"dataTypeToFeatureMap\":{ \"ANALOG\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ] }, \"predictor\":{ \"fnodeid\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"nodename\":\"PV\", \"sensordata_type\":\"ANALOG\" }, \"starttime\":1491235200000, \"endtime\":1506700800000, \"samplingRate\":10, \"samplingTimePeriod\":\"MINUTE\", \"aggregator\":\"AVG\" }, \"keyspace\":\"vroc\", \"phoenixHost\":\"auper01-01-20-01-0.prod.vroc.com.au:2181:/hbase-unsecure\", \"number_of_features\":1, \"feature_selection\":false, \"model_parameters_optimization\":false, \"training_ratio\":0.5, \"validation_ratio\":0.7, \"ttf_calculation\":false, \"ttf_threshold\":0.0, \"ttf_thershold_greater\":false, \"number_of_lags\":5, \"modelMetadata\":{ \"startedByUser\":\"Livy Demo\", \"userOrganization\":\"Livy Demo\", \"nodeName\":\"VROC.Rishi_trial.Update_test.try1_1\" } }]"));
    ModelParameter modelParam = gson.fromJson(reader, ModelParameter.class);

The model parameter class is as follow:

package au.com.vroc.mdm.model;

import java.io.Serializable;

import com.google.gson.Gson;

/**
 * The Class ModelParameter.
 */
public class ModelParameter implements Serializable {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -8395899340046386755L;

    /** The alg. */
    public String alg = "rf";

    /** The response_variable. */
    public String response_variable = "";

    /** The regressionparam. */
    public RegressionParameter regressionparam = new RegressionParameter();

    /** The agg param. */
    public AggregationParameter aggParam = new AggregationParameter();;

    /** The keyspace. */
    public String keyspace = "vroctest";

    /** The keyspace. */
    public String phoenixHost = null;

    /** The automatic feature selection. */
    public Integer number_of_features =10 ;

    /** Feature selection. */
    public Boolean feature_selection =false ;

    /** The model parameter optimization. */
    public Boolean model_parameters_optimization=false;

    /** Training ratio. */
    public Double training_ratio=0.5;

    /** Validation ratio. */
    public Double validation_ratio=0.7;

    /** TTF calculation. */
    public Boolean ttf_calculation=false;

    /** TTF threshold. */
    public Double ttf_threshold=0.5;

    /** Values greater than TTF threshold become alarms otherwise values below threshold become alarm. */
    public Boolean ttf_thershold_greater=true;

    /** Number of lags. */
    public Integer number_of_lags=1;

    public ModelMetadata modelMetadata;

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return new Gson().toJson(this);
    }
}

However, it throws exception like below:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
        at com.google.gson.Gson.fromJson(Gson.java:803)
        at au.com.vroc.mdm.SparkSubmitModel.main(SparkSubmitModel.java:404)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

I don't know what is wrong with the codes. Is there anything wrong with my model parameter class? I have very nested collections in my model parameter class as well..


问:
preventDefault is not a function error when trying to pass an image
I'm using an image cropper to crop an image. I'm using the following library

https://github.com/mosch/react-avatar-editor

I have implemented this correctly and i'm getting the cropped image using this function.

```<code>handleSave = () => {
  const img = this.editor.getImageScaledToCanvas().toDataURL();

  this.props.croppedImage(img);
};
</code>```

Here i have passed the cropped image using props to another function as follows

```<code>this.props.croppedImage(img);
</code>```

This is where i have implemented the cropper (2nd component)

```<code><CropperTest croppedImage={this.getCroppedImg}/>
</code>```

In the 2nd component i have used this function to access the cropped image and again pass that image to another function. This is where i get the issue.

```<code>getCroppedImg(img) {
    this.props.onImageImgPoll(img);
}
</code>```

onImageImgPoll function

```<code>onImageImgPoll(event) {

event.preventDefault();
let array = this.state.filepoll.slice();
let unq_file = event.target.files[0];

if (event.target.files && event.target.files[0]) {

  let reader = new FileReader();
  reader.onloadend = (e) => {
    array.push(unq_file);
  };
  reader.readAsDataURL(unq_file);

  this.setState({
    image: event.target.result,
    filepoll: array,
    filestar: []
  });

}

};
</code>```

When running this code i'm getting this error

```<code>event.preventDefault is not a function
</code>```

What I've found out is the cropped image is in base64 format. Maybe that might be the issue. How can i solve this?

答: Make sure you have added this.onImageImgPoll= this.onImageImgPoll.bind(this); in your component constructor

Body:
I'm using an image cropper to crop an image. I'm using the following library

https://github.com/mosch/react-avatar-editor

I have implemented this correctly and i'm getting the cropped image using this function.

handleSave = () => {
  const img = this.editor.getImageScaledToCanvas().toDataURL();

  this.props.croppedImage(img);
};

Here i have passed the cropped image using props to another function as follows

this.props.croppedImage(img);

This is where i have implemented the cropper (2nd component)

<CropperTest croppedImage={this.getCroppedImg}/>

In the 2nd component i have used this function to access the cropped image and again pass that image to another function. This is where i get the issue.

getCroppedImg(img) {
    this.props.onImageImgPoll(img);
}

onImageImgPoll function

onImageImgPoll(event) {

event.preventDefault();
let array = this.state.filepoll.slice();
let unq_file = event.target.files[0];

if (event.target.files && event.target.files[0]) {

  let reader = new FileReader();
  reader.onloadend = (e) => {
    array.push(unq_file);
  };
  reader.readAsDataURL(unq_file);

  this.setState({
    image: event.target.result,
    filepoll: array,
    filestar: []
  });

}

};

When running this code i'm getting this error

event.preventDefault is not a function

What I've found out is the cropped image is in base64 format. Maybe that might be the issue. How can i solve this?


问:
Adding same "*.dll" reference to multiple projects in the same Solution
I have a Visual Studio 2008 .NET C++/CLI Solution. My solution consists of many sub projects. I define a custom build directory for each project and called it "Output".

My solution:

MyFirstProject (*.exe)

MySecondPrject (*.dll)

...

MyNthProject (*.dll)

Each of the sub project use Log4.net.So I create a directory (called LogBinary) and put log4.net DLL in that folder. Then to use log4net I add this DLL as a reference to each of my project.

But when I try to compile my main project (*.exe) I got tons of warning (over 400).

Just an example:

Warning  110 warning C4945: 'AbsoluteTimeDateFormatter' :
  cannot import symbol from 'somepath\log4net.dll': as
  'log4net::DateFormatter::AbsoluteTimeDateFormatter'
  has already been imported from another assembly 'log4net'"somepath\log4net.dll"

Lots of warnings with:

has already been imported from another assembly

Why do I get these warnings? Does anybody have a solution to add same DLL to multiple projects (except using GAC)?

答:
Change reference on the projects, set all "copy local ..." properties to false.

Source : http://developertips.blogspot.com/2008/07/ccli-warning-c4945.html


问:
wordpress update meta not working
hey i am trying to update user meta but its not updating

```<code>  $dobs=$_REQUEST['day'].'_'.$_REQUEST['month'].'_'.$_REQUEST['year'];
  $gender=$_REQUEST['gender'];
  $country=$_REQUEST['country'];
  $state=$_REQUEST['state'];
  $city=$_REQUEST['city'];

  update_user_meta( $user_id, 'date_of_birth', $dobs, true );
  update_user_meta((int) $user_id, 'gender', (int) $gender, true );
  update_user_meta( $user_id, 'country', $country, true );
  update_user_meta( $user_id, 'state', $state, true );
  update_user_meta( $user_id, 'city', $city, true );
</code>```

here i tried typecasting like (int) (string) interesting part is insert working properly don't know if there is an error in DB structure.

答:
update_user_meta() - Update user meta field based on user ID. It has only three arguments in general where the 4th is optional.  The 4th parameter is the $prev_value which in default will be the '' values alone. Hence the 4th parameter will be checking whether the meta_key updated has the previous values to it.

For Example:

```<code><?php
     $user_id = 1;
     $website_url = 'http://wordpress.org';
     update_user_meta($user_id, 'user_url', $website_url, TRUE);
    // The above statement will update the user_meta table corresponding to the user_id=1
?>
</code>```

Note: The First 3 Parameters are required. Without that it will not work.

Kindly ensure that the the 'second value' in the update_user_meta() should be existing into the database table.

As per the Question Author Scenario:

```<code>update_user_meta( $user_id, 'date_of_birth', $dobs, true );
</code>```

It must have all the 3 parameters namely $user_id,date_of_birth and the $dobs.

Title: wordpress update meta not working

Body:
hey i am trying to update user meta but its not updating

  $dobs=$_REQUEST['day'].'_'.$_REQUEST['month'].'_'.$_REQUEST['year'];
  $gender=$_REQUEST['gender'];
  $country=$_REQUEST['country'];
  $state=$_REQUEST['state'];
  $city=$_REQUEST['city'];

  update_user_meta( $user_id, 'date_of_birth', $dobs, true );
  update_user_meta((int) $user_id, 'gender', (int) $gender, true );
  update_user_meta( $user_id, 'country', $country, true );
  update_user_meta( $user_id, 'state', $state, true );
  update_user_meta( $user_id, 'city', $city, true );

here i tried typecasting like (int) (string) interesting part is insert working properly don't know if there is an error in DB structure.

Body:
update_user_meta() - Update user meta field based on user ID. It has only three arguments in general where the 4th is optional.  The 4th parameter is the $prev_value which in default will be the '' values alone. Hence the 4th parameter will be checking whether the meta_key updated has the previous values to it.

For Example:

<?php
     $user_id = 1;
     $website_url = 'http://wordpress.org';
     update_user_meta($user_id, 'user_url', $website_url, TRUE);
    // The above statement will update the user_meta table corresponding to the user_id=1
?>

Note: The First 3 Parameters are required. Without that it will not work.

Kindly ensure that the the 'second value' in the update_user_meta() should be existing into the database table.

As per the Question Author Scenario:

update_user_meta( $user_id, 'date_of_birth', $dobs, true );

It must have all the 3 parameters namely $user_id,date_of_birth and the $dobs.


问:
Killing a while loop that's running in the background without a PID
I'm a beginner in everything that is part of Linux so please take me slow.

I've created a "script" that's running in the background:

```<code>while true; do echo "I'm alive" >> alive.log ; done &
</code>```

The output of the script is saved in a file alive.log that's present in the user's home directory.
The problem is I have no ideea how to kill the loop since it's filling my disk space, if I wish to delete the file then loop will create a new file and fill it with the text "I'm alive" as I've asked it to do.

I tried using:

```<code>ps - aux | grep while
</code>```

or

```<code>ps - aux | grep alive
</code>```

The output for the two lines will give me the PID I need but the problem is that the script is a loop which means the PID will change every time it runs itself (recursive) so I can't use the PID to kill the process.

I also tried using:

```<code>pkill while
killall while
</code>```

The result for both lines is 0 (output can be seen when using pkill while -c "0" or killall while : "while: no process found";

Any suggestions please?

答:
This is an answer by @James Brown in the comments.

Type fg to get it in the foreground and kill it with ctrl-c the fastest way to solve this.

Body:
I'm a beginner in everything that is part of Linux so please take me slow.

I've created a "script" that's running in the background:

while true; do echo "I'm alive" >> alive.log ; done &

The output of the script is saved in a file alive.log that's present in the user's home directory.
The problem is I have no ideea how to kill the loop since it's filling my disk space, if I wish to delete the file then loop will create a new file and fill it with the text "I'm alive" as I've asked it to do.

I tried using:

ps - aux | grep while

or

ps - aux | grep alive

The output for the two lines will give me the PID I need but the problem is that the script is a loop which means the PID will change every time it runs itself (recursive) so I can't use the PID to kill the process.

I also tried using:

pkill while
killall while

The result for both lines is 0 (output can be seen when using pkill while -c "0" or killall while : "while: no process found";

Any suggestions please?


问:
Elastic Search query for email
I am trying to implement email search with ElasticSearch.

Here are the example documents.

```<code>{
  ...
  "email": "valeri@gmail.com"
},
{
  ...
  "email": "tom@gmail.com"
}
</code>```

So when I use the match query: { "match": { "email": "valeri@gmail.com"
 } }

I get both of "valeri@gmail.com"and "tom@gmail.com" but the result must be only "valeri@gmail.com".

I think it is because of @ character.

Any good solution to resolve this issue?

答:
You need to use the Email Tokenizer as specified here:

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-uaxurlemail-tokenizer.html

Title: Elastic Search query for email

Body:
I am trying to implement email search with ElasticSearch.

Here are the example documents.

{
  ...
  "email": "valeri@gmail.com"
},
{
  ...
  "email": "tom@gmail.com"
}

So when I use the match query: { "match": { "email": "valeri@gmail.com"
 } }

I get both of "valeri@gmail.com"and "tom@gmail.com" but the result must be only "valeri@gmail.com".

I think it is because of @ character.

Any good solution to resolve this issue?


问:
Are there any advantages to having a defer in a simple, no return, non-panicking function?
Going through the standard library, I see a lot functions similar to the following:

```<code>// src/database/sql/sql.go
func (dc *driverConn) removeOpenStmt(ds *driverStmt) {
    dc.Lock()
    defer dc.Unlock()
    delete(dc.openStmt, ds)
}
...

func (db *DB) addDep(x finalCloser, dep interface{}) {
    //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep))
    db.mu.Lock()
    defer db.mu.Unlock()
    db.addDepLocked(x, dep)
}
// src/expvar/expvar.go
func (v *Map) addKey(key string) {
    v.keysMu.Lock()
    defer v.keysMu.Unlock()
    v.keys = append(v.keys, key)
    sort.Strings(v.keys)
}
// etc...
</code>```

I.e.: simple functions with no returns and presumably no way to panic that are still deferring the unlock of their mutex. As I understand it, the overhead of a defer has been improved (and perhaps is still in the process of being improved), but that being said: Is there any reason to include a defer in functions like these?  Couldn't these types of defers end up slowing down a high traffic function?

答:
Panic is a sudden (so it could be unpredicted or unprepared) violation of normal control flow. Potentially it can emerge from anything - quite often from external things - for example memory failure. defer mechanism gives an easy and quite cheap tool to perform exit operation. Thus not leave a system in broken state. This is important for locks in high load applications  because it help not to lose locked resources and freeze the whole system in lock once.

And if for some moment code has no places for panic (hard to guess such system ;) but things evolve. Later this function would be more complex and able to throw panic.

Conclusion: Defer helps you to ensure your function will exit correctly if something “goes wring”. Also quite important it is future-proof - same reply for different failures.

So it’s a food style to put them even in easy functions. As a programmer you can see nothing is lost. And be more sure in a code.

Body:
Going through the standard library, I see a lot functions similar to the following:

// src/database/sql/sql.go
func (dc *driverConn) removeOpenStmt(ds *driverStmt) {
    dc.Lock()
    defer dc.Unlock()
    delete(dc.openStmt, ds)
}
...

func (db *DB) addDep(x finalCloser, dep interface{}) {
    //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep))
    db.mu.Lock()
    defer db.mu.Unlock()
    db.addDepLocked(x, dep)
}
// src/expvar/expvar.go
func (v *Map) addKey(key string) {
    v.keysMu.Lock()
    defer v.keysMu.Unlock()
    v.keys = append(v.keys, key)
    sort.Strings(v.keys)
}
// etc...

I.e.: simple functions with no returns and presumably no way to panic that are still deferring the unlock of their mutex. As I understand it, the overhead of a defer has been improved (and perhaps is still in the process of being improved), but that being said: Is there any reason to include a defer in functions like these?  Couldn't these types of defers end up slowing down a high traffic function?


问:
Checking if my Windows application is running
How do I check if my C# Windows application is running ?

I know that I can check the process name but the name can be changed if the exe changes.

Is there any way to have a hash key or something to make my application unique?

答:
you need a way to say that "i am running" from the app,

1) open a WCF ping service
2) write to registry/file on startup and delete on shutdown
3) create a Mutex

... i prefer the WCF part because you may not clean up file/registry correctly and Mutex seems to have its own issues


问:
How do you write a mock in Swift?
Where do I put the mocked code? Do I need to write everything again? Do I change the original code?</p>

答:
Short answer: using protocols.

If your injectable object is final, a struct, or an enum, it isn't even possible to override it to mock. Instead of using a concrete type as your dependency, use a protocol and conform your implementation to it. In addition to allowing "mocking" regardless of the real type (class, struct, enum), this lists the public interface all in one place, uninterrupted by the implementations. It also forces you to think about what needs to be part of the non-private interface.

With retroactive protocol conformance (i.e. in extensions), you can even use this to mock system classes like, e.g., CBCentralManager or CLLocationManager.

Example:

Not easily mockable:

```<code>struct Foo {
    let id: Int
    let data: Int
}

final class FooManager {
    var x: Int

    func getFoo(id: Int) -> Foo {
        return Foo(id: id, data: x)
    }
}

class FooUser {
    let fooManager: FooManager
    init(fooManager: FooManager) {
        self.fooManager = fooManager
    }
    func getData() -> Int {
        return fooManager.getFoo(id: 3).data
    }
}
</code>```

Trivially mockable:

```<code>struct Foo {
    let id: Int
    let data: Int
}

// Easy to see what's visible.
protocol FooManager {
    func getFoo(id: Int) -> Foo
}

final class RealFooManager: FooManager {
    private var x: Int

    func getFoo(id: Int) -> Foo {
        return Foo(id: id, data: x)
    }
}

class FooUser {
    let fooManager: FooManager
    init(fooManager: FooManager) {
        self.fooManager = fooManager
    }
    func getData() -> Int {
        return fooManager.getFoo(id: 3).data
    }
}

// In test target.
class MockFooManager: FooManager {
    var requestedId: Int?
    var data: Int = 17
    func getFoo(id: Int) -> Foo {
        requestedId = id
        return Foo(id, data: data)
    }
}

class FooUserTests {
    func testFooUserGetData() {
        let mock = MockFooManager()
        let user = FooUser(fooManager: mock)
        let data = user.getData()
        XCTAssertEqual(data, mock.data)
        XCTAssertEqual(mock.requestedId, 3)
    }
}
</code>```

Title: How do you write a mock in Swift?

Body:
Short answer: using protocols.

If your injectable object is final, a struct, or an enum, it isn't even possible to override it to mock. Instead of using a concrete type as your dependency, use a protocol and conform your implementation to it. In addition to allowing "mocking" regardless of the real type (class, struct, enum), this lists the public interface all in one place, uninterrupted by the implementations. It also forces you to think about what needs to be part of the non-private interface.

With retroactive protocol conformance (i.e. in extensions), you can even use this to mock system classes like, e.g., CBCentralManager or CLLocationManager.

Example:

Not easily mockable:

struct Foo {
    let id: Int
    let data: Int
}

final class FooManager {
    var x: Int

    func getFoo(id: Int) -> Foo {
        return Foo(id: id, data: x)
    }
}

class FooUser {
    let fooManager: FooManager
    init(fooManager: FooManager) {
        self.fooManager = fooManager
    }
    func getData() -> Int {
        return fooManager.getFoo(id: 3).data
    }
}

Trivially mockable:

struct Foo {
    let id: Int
    let data: Int
}

// Easy to see what's visible.
protocol FooManager {
    func getFoo(id: Int) -> Foo
}

final class RealFooManager: FooManager {
    private var x: Int

    func getFoo(id: Int) -> Foo {
        return Foo(id: id, data: x)
    }
}

class FooUser {
    let fooManager: FooManager
    init(fooManager: FooManager) {
        self.fooManager = fooManager
    }
    func getData() -> Int {
        return fooManager.getFoo(id: 3).data
    }
}

// In test target.
class MockFooManager: FooManager {
    var requestedId: Int?
    var data: Int = 17
    func getFoo(id: Int) -> Foo {
        requestedId = id
        return Foo(id, data: data)
    }
}

class FooUserTests {
    func testFooUserGetData() {
        let mock = MockFooManager()
        let user = FooUser(fooManager: mock)
        let data = user.getData()
        XCTAssertEqual(data, mock.data)
        XCTAssertEqual(mock.requestedId, 3)
    }
}


问:
Collectd not logging into Splunk
I've got an aws instance that I have collectd installed on. I can CURL from the instance to my splunk server and put messages in so there don't appear to be any network issues. I'm using the same endpoint and token as I have in my collectd configuration.

When I restart the collectd service, I get no errors:

```<code>Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "syslog" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "cpu" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "load" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "memory" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "interface" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "write_http" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "network" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "rrdtool" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: Initialization complete, entering read-loop.
</code>```

However when I view splunk there are no logs..

I am going on the assumption that the collectd is acting as both the client and the server (on the same instance).

There are log files in the /var/lib/collectd/rrd/localhost/ folder. Just not sure why they aren't going from there into splunk.

I'm sure it is something basic that I've missed.

Cheers

答:
The answer is that that the URL needs to have the token not only in the headers but as a parameter as well.

Simply replace:

```<code>`URL "https://myurl.com:8088/services/collector"

Header "Authorization: Splunk {{splunk_token}}"`
</code>```

With:

```<code>`URL "https://myurl.com:8088/services/collector/raw?channel={{splunk_token}}"

Header "Authorization: Splunk {{splunk_token}}"`
</code>```

Title: Collectd not logging into Splunk

Body:
I've got an aws instance that I have collectd installed on. I can CURL from the instance to my splunk server and put messages in so there don't appear to be any network issues. I'm using the same endpoint and token as I have in my collectd configuration.

When I restart the collectd service, I get no errors:

Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "syslog" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "cpu" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "load" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "memory" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "interface" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "write_http" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "network" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: plugin_load: plugin "rrdtool" successfully loaded.
Nov 10 00:11:31 kafka10-03 collectd[26435]: Initialization complete, entering read-loop.

However when I view splunk there are no logs..

I am going on the assumption that the collectd is acting as both the client and the server (on the same instance).

There are log files in the /var/lib/collectd/rrd/localhost/ folder. Just not sure why they aren't going from there into splunk.

I'm sure it is something basic that I've missed.

Cheers

Body:
The answer is that that the URL needs to have the token not only in the headers but as a parameter as well.

Simply replace:

`URL "https://myurl.com:8088/services/collector"

Header "Authorization: Splunk {{splunk_token}}"`

With:

`URL "https://myurl.com:8088/services/collector/raw?channel={{splunk_token}}"

Header "Authorization: Splunk {{splunk_token}}"`


问:
Error in using UIAutomatorviewer for testing Android app in Appium
I have to automate an Android application, I am doing the same through Appium.

The problem I am facing is after launching the Appium server, the app is getting installed in the emulator 4.4.2.  To inspect the element I am using UIAutomatorviewer which comes default with SDK. But while inspecting the element of the app, I am getting the error:

```<code>Error obtaining UI hierarchy
Reason:Error while obtaining UI hierarchy XML file.com.android.ddmlb.SynchException.Remote object doesn't exist.
</code>```

I tried to find the solution so that I can inspect the element so that I can script, but in vain.

Can someone please tell how to fix the issue so that I can inspect elements?

Is there any other way I can inspect element in the app apart from using UIAutomator viewer?

答:
I got it resolved

I closed the Appium Server running on my machine and opened it again.
Later open uiautomater, and it worked for me

Body:
I have to automate an Android application, I am doing the same through Appium.

The problem I am facing is after launching the Appium server, the app is getting installed in the emulator 4.4.2.  To inspect the element I am using UIAutomatorviewer which comes default with SDK. But while inspecting the element of the app, I am getting the error:

Error obtaining UI hierarchy
Reason:Error while obtaining UI hierarchy XML file.com.android.ddmlb.SynchException.Remote object doesn't exist.

I tried to find the solution so that I can inspect the element so that I can script, but in vain.

Can someone please tell how to fix the issue so that I can inspect elements?

Is there any other way I can inspect element in the app apart from using UIAutomator viewer?


问:
Need help to get started integrating lua in c++ game
I need help integrating lua in my game. I know only a little about lua, since I just started learning scripting (in general). I've read tutorials about lua, but most of them are only tell me how to bind lua in c++ code (which I've managed to do that with LuaBind), or explaining features in lua.

Let's say I have a "Player" class and "Obstacle" class.
Obstacle class have these functions :

```<code>
class Obstacle {
  // ... member vars

  // functions that will behave differently based on script :
  void onTouchPlayer(Player* player);
  void onUpdate(float deltaTime);
}
</code>```

onTouchPlayer and onUpdate is meant to behave differently based on script.

What confuses me is what to write in the script, and how to call it in c++? If I already have Player class exported to Lua with LuaBind, how can I, for example, kill player at onTouchPlayer() and move the obstacle randomly at onUpdate function with lua?

答:
The following page of the Lua Development Guide (5.0) tells you how to call lua functions from the C environment.

http://www.lua.org/pil/25.2.html

Body:
I need help integrating lua in my game. I know only a little about lua, since I just started learning scripting (in general). I've read tutorials about lua, but most of them are only tell me how to bind lua in c++ code (which I've managed to do that with LuaBind), or explaining features in lua.

Let's say I have a "Player" class and "Obstacle" class.
Obstacle class have these functions :

class Obstacle {
  // ... member vars

  // functions that will behave differently based on script :
  void onTouchPlayer(Player* player);
  void onUpdate(float deltaTime);
}

onTouchPlayer and onUpdate is meant to behave differently based on script.

What confuses me is what to write in the script, and how to call it in c++? If I already have Player class exported to Lua with LuaBind, how can I, for example, kill player at onTouchPlayer() and move the obstacle randomly at onUpdate function with lua?


问:
Can I write files into a HTML file using Xcode and then load it on a web view?
I have a file named editor.html as of right now. Its static and loads the HTML content onto the web view whenever it is called.

But as my HTML code (fixing bugs /adds new features) keeps changing always I have an API so that I can add this HTML and CSS code dynamically using the Json response.

Now in Xcode can I create / edit my existing editor.html file to populate it with the string I received from this API ?

I tried this code for testing purpose and it does not write anything, but users have responded pretty positively on that comment saying it works, can anyone please help me on this ?

```<code>NSError *error;
NSString *stringToWrite = @"/Users/name/Desktop/testHTML";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
NSString *contents = [NSString stringWithFormat:@"This is test for html"];
</code>```

[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

答:
If your file is in App bundle then first thing you have to do is copy your file into documents directory of your app at runtime then you can replace content downloaded from API inside your file.

Copy File from App bundle to document directory, replace file name and file extension with your file type.

```<code>NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

NSString *dataPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"tessdata"];
NSLog(@"Datapath is %@", dataPath);

// If the expected store doesn't exist, copy the default store.
    if ([fileManager fileExistsAtPath:dataPath] == NO)
    {
        NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:@"eng" ofType:@"traineddata"];
        [fileManager copyItemAtPath:tessdataPath toPath:dataPath error:&error];

    }

-(NSString*) applicationDocumentsDirectory{
    // Get the documents directory
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    return docsDir;
}
</code>```

Write Data into File

```<code>NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
</code>```

Body:
I have a file named editor.html as of right now. Its static and loads the HTML content onto the web view whenever it is called.

But as my HTML code (fixing bugs /adds new features) keeps changing always I have an API so that I can add this HTML and CSS code dynamically using the Json response.

Now in Xcode can I create / edit my existing editor.html file to populate it with the string I received from this API ?

I tried this code for testing purpose and it does not write anything, but users have responded pretty positively on that comment saying it works, can anyone please help me on this ?

NSError *error;
NSString *stringToWrite = @"/Users/name/Desktop/testHTML";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
NSString *contents = [NSString stringWithFormat:@"This is test for html"];

[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

Body:
If your file is in App bundle then first thing you have to do is copy your file into documents directory of your app at runtime then you can replace content downloaded from API inside your file.

Copy File from App bundle to document directory, replace file name and file extension with your file type.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

NSString *dataPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"tessdata"];
NSLog(@"Datapath is %@", dataPath);

// If the expected store doesn't exist, copy the default store.
    if ([fileManager fileExistsAtPath:dataPath] == NO)
    {
        NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:@"eng" ofType:@"traineddata"];
        [fileManager copyItemAtPath:tessdataPath toPath:dataPath error:&error];

    }

-(NSString*) applicationDocumentsDirectory{
    // Get the documents directory
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    return docsDir;
}

Write Data into File

NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];


问:
How to perform an HTTP file upload using express on Cloud Functions for Firebase (multer, busboy)
I am trying to upload a file to Cloud Functions, using Express to handle requests there, but i am not succeeding. I created a version that works locally:

serverside js

```<code>const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');

const app = express();
app.use(fileUpload());
app.use(cors());

app.post('/upload', (req, res) => {
    res.send('files: ' + Object.keys(req.files).join(', '));
});
</code>```

clientside js

```<code>const formData = new FormData();
Array.from(this.$refs.fileSelect.files).forEach((file, index) => {
    formData.append('sample' + index, file, 'sample');
});

axios.post(
    url,
    formData,
    {
        headers: { 'Content-Type': 'multipart/form-data' },
    }
);
</code>```

This exact same code seems to break when deployed to Cloud Functions, where req.files is undefined. Does anyone have any idea what is happening here?

EDIT
I also had a go at using multer, which worked fine locally, but once uploaded to Cloud Functions, this got me an empty array (same clientside code):

```<code>const app = express();
const upload = multer();
app.use(cors());

app.post('/upload', upload.any(), (req, res) => {
    res.send(JSON.stringify(req.files));
});
</code>```

答: I have been suffering from the same problem for a few days, turns out that firebase team has put the raw body of multipart/form-data into req.body with their middleware. If you try console.log(req.body.toString()) BEFORE processing your request with multer, you will see your data. As multer creates a new req.body object which is overriding the resulting req, the data is gone and all we can get is an empty req.body. Hopefully the firebase team could correct this soon.</p>

Body:
I am trying to upload a file to Cloud Functions, using Express to handle requests there, but i am not succeeding. I created a version that works locally:

serverside js

const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');

const app = express();
app.use(fileUpload());
app.use(cors());

app.post('/upload', (req, res) => {
    res.send('files: ' + Object.keys(req.files).join(', '));
});

clientside js

const formData = new FormData();
Array.from(this.$refs.fileSelect.files).forEach((file, index) => {
    formData.append('sample' + index, file, 'sample');
});

axios.post(
    url,
    formData,
    {
        headers: { 'Content-Type': 'multipart/form-data' },
    }
);

This exact same code seems to break when deployed to Cloud Functions, where req.files is undefined. Does anyone have any idea what is happening here?

EDIT
I also had a go at using multer, which worked fine locally, but once uploaded to Cloud Functions, this got me an empty array (same clientside code):

const app = express();
const upload = multer();
app.use(cors());

app.post('/upload', upload.any(), (req, res) => {
    res.send(JSON.stringify(req.files));
});


问:
how do I add an azure role using a json within the azure cli?
I am using the Azure CLI 2.0 and don't see any documentation on adding a custom role via a json document. Can someone help?

I assume it starts out like this: $  az role create .. but that doesn't exist, apparently.

答:
For Azure CLI 2.0, you can create a new custom role via JSON file containing the role definition using the Azure CLI command as below.

```<code>az role definition create --role-definition @ad-role.json
</code>```

where ad-role.json is the JSON file which has the valid role definition residing in the same directory from where you run the command above.

You can refer to this Microsoft documentation for examples on how to use the latest Azure CLI to create the custom role.

Hope this helps.

Body:
For Azure CLI 2.0, you can create a new custom role via JSON file containing the role definition using the Azure CLI command as below.

az role definition create --role-definition @ad-role.json

where ad-role.json is the JSON file which has the valid role definition residing in the same directory from where you run the command above.

You can refer to this Microsoft documentation for examples on how to use the latest Azure CLI to create the custom role.

Hope this helps.


问:
PHP Authorization header not found
I am working on the codeigniter basic authentication by using Rest_controller. Currently i having the issue on getting anyone of them in the list below from my $_SERVER array object.

PHP_AUTH_USER

PHP_AUTH_PW

HTTP_AUTHORIZATION

HTTP_AUTHENTICATION

Based on my research, the problem is because of the Server API on my server. The Server API of this server is using CGI/FastCGI.

I even tried add all these to my .htaccess but none of them is working for me.

```<code>RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
CGIPassAuth on
Header set Access-Control-Allow-Headers: "Authorization"
</code>```

The array below is what is get from my $_SERVER when i try call my api from the postman.

```<code>     array(52) {
    ["PATH"]=>
    string(28) "/usr/local/bin:/usr/bin:/bin"
    ["TZ"]=>
    string(16) "America/New_York"
    ["REDIRECT_HANDLER"]=>
    string(28) "application/x-httpd-ea-php56"
    ["REDIRECT_STATUS"]=>
    string(3) "200"
    ["UNIQUE_ID"]=>
    string(27) "Wgu-pu3SJZU707d76yB41AAAAAE"
    ["SCRIPT_URL"]=>
    string(24) "/index.php/test_api/test"
    ["SCRIPT_URI"]=>
    string(49) "https://www.river-app.com/index.php/test_api/test"
    ["HTTPS"]=>
    string(2) "on"
    ["SSL_TLS_SNI"]=>
    string(17) "www.river-app.com"
    ["HTTP_HOST"]=>
    string(17) "www.river-app.com"
    ["HTTP_CONNECTION"]=>
    string(10) "keep-alive"
    ["CONTENT_LENGTH"]=>
    string(1) "0"
    ["HTTP_CACHE_CONTROL"]=>
    string(8) "no-cache"
    ["HTTP_ORIGIN"]=>
    string(51) "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop"
    ["HTTP_USER_AGENT"]=>
    string(121) "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
    ["HTTP_POSTMAN_TOKEN"]=>
    string(36) "12be9c43-7d88-3244-b407-ff0a160434ce"
    ["HTTP_ACCEPT"]=>
    string(3) "*/*"
    ["HTTP_ACCEPT_ENCODING"]=>
    string(17) "gzip, deflate, br"
    ["HTTP_ACCEPT_LANGUAGE"]=>
    string(38) "en-US,en;q=0.8,zh-CN;q=0.6,zh-TW;q=0.4"
    ["HTTP_COOKIE"]=>
    string(43) "ci_session=ne4ip07sqkrree86dgmjfackgbn4f4bk"
    ["HTTP_X_HTTPS"]=>
    string(1) "1"
    ["SERVER_SIGNATURE"]=>
    string(0) ""
    ["SERVER_SOFTWARE"]=>
    string(6) "Apache"
    ["SERVER_NAME"]=>
    string(17) "www.river-app.com"
    ["SERVER_ADDR"]=>
    string(14) "67.225.226.183"
    ["SERVER_PORT"]=>
    string(3) "443"
    ["REMOTE_ADDR"]=>
    string(15) "118.200.235.133"
    ["DOCUMENT_ROOT"]=>
    string(26) "/home/riverapp/public_html"
    ["REQUEST_SCHEME"]=>
    string(5) "https"
    ["CONTEXT_PREFIX"]=>
    string(8) "/cgi-sys"
    ["CONTEXT_DOCUMENT_ROOT"]=>
    string(26) "/usr/local/cpanel/cgi-sys/"
    ["SERVER_ADMIN"]=>
    string(23) "webmaster@river-app.com"
    ["SCRIPT_FILENAME"]=>
    string(36) "/home/riverapp/public_html/index.php"
    ["REMOTE_PORT"]=>
    string(5) "60875"
    ["REDIRECT_URL"]=>
    string(24) "/index.php/test_api/test"
    ["GATEWAY_INTERFACE"]=>
    string(7) "CGI/1.1"
    ["SERVER_PROTOCOL"]=>
    string(8) "HTTP/1.1"
    ["REQUEST_METHOD"]=>
    string(4) "POST"
    ["QUERY_STRING"]=>
    string(0) ""
    ["REQUEST_URI"]=>
    string(24) "/index.php/test_api/test"
    ["SCRIPT_NAME"]=>
    string(10) "/index.php"
    ["PATH_INFO"]=>
    string(14) "/test_api/test"
    ["PATH_TRANSLATED"]=>
    string(40) "/home/riverapp/public_html/test_api/test"
    ["ORIG_PATH_INFO"]=>
    string(24) "/index.php/test_api/test"
    ["ORIG_SCRIPT_NAME"]=>
    string(17) "/cgi-sys/ea-php56"
    ["ORIG_SCRIPT_FILENAME"]=>
    string(34) "/usr/local/cpanel/cgi-sys/ea-php56"
    ["ORIG_PATH_TRANSLATED"]=>
    string(50) "/home/riverapp/public_html/index.php/test_api/test"
    ["PHP_SELF"]=>
    string(24) "/index.php/test_api/test"
    ["REQUEST_TIME_FLOAT"]=>
    float(1510719398.04)
    ["REQUEST_TIME"]=>
    int(1510719398)
    ["argv"]=>
    array(0) {
    }
    ["argc"]=>
    int(0)
    }
</code>```

What could be the thing causing this issue.

答:
Try adding this line to top of your controller</p>

```<code>header('Content-Type: application/json');
</code>```

Title: PHP Authorization header not found

Body:
I am working on the codeigniter basic authentication by using Rest_controller. Currently i having the issue on getting anyone of them in the list below from my $_SERVER array object.

PHP_AUTH_USER

PHP_AUTH_PW

HTTP_AUTHORIZATION

HTTP_AUTHENTICATION

Based on my research, the problem is because of the Server API on my server. The Server API of this server is using CGI/FastCGI.

I even tried add all these to my .htaccess but none of them is working for me.

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
CGIPassAuth on
Header set Access-Control-Allow-Headers: "Authorization"

The array below is what is get from my $_SERVER when i try call my api from the postman.

     array(52) {
    ["PATH"]=>
    string(28) "/usr/local/bin:/usr/bin:/bin"
    ["TZ"]=>
    string(16) "America/New_York"
    ["REDIRECT_HANDLER"]=>
    string(28) "application/x-httpd-ea-php56"
    ["REDIRECT_STATUS"]=>
    string(3) "200"
    ["UNIQUE_ID"]=>
    string(27) "Wgu-pu3SJZU707d76yB41AAAAAE"
    ["SCRIPT_URL"]=>
    string(24) "/index.php/test_api/test"
    ["SCRIPT_URI"]=>
    string(49) "https://www.river-app.com/index.php/test_api/test"
    ["HTTPS"]=>
    string(2) "on"
    ["SSL_TLS_SNI"]=>
    string(17) "www.river-app.com"
    ["HTTP_HOST"]=>
    string(17) "www.river-app.com"
    ["HTTP_CONNECTION"]=>
    string(10) "keep-alive"
    ["CONTENT_LENGTH"]=>
    string(1) "0"
    ["HTTP_CACHE_CONTROL"]=>
    string(8) "no-cache"
    ["HTTP_ORIGIN"]=>
    string(51) "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop"
    ["HTTP_USER_AGENT"]=>
    string(121) "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
    ["HTTP_POSTMAN_TOKEN"]=>
    string(36) "12be9c43-7d88-3244-b407-ff0a160434ce"
    ["HTTP_ACCEPT"]=>
    string(3) "*/*"
    ["HTTP_ACCEPT_ENCODING"]=>
    string(17) "gzip, deflate, br"
    ["HTTP_ACCEPT_LANGUAGE"]=>
    string(38) "en-US,en;q=0.8,zh-CN;q=0.6,zh-TW;q=0.4"
    ["HTTP_COOKIE"]=>
    string(43) "ci_session=ne4ip07sqkrree86dgmjfackgbn4f4bk"
    ["HTTP_X_HTTPS"]=>
    string(1) "1"
    ["SERVER_SIGNATURE"]=>
    string(0) ""
    ["SERVER_SOFTWARE"]=>
    string(6) "Apache"
    ["SERVER_NAME"]=>
    string(17) "www.river-app.com"
    ["SERVER_ADDR"]=>
    string(14) "67.225.226.183"
    ["SERVER_PORT"]=>
    string(3) "443"
    ["REMOTE_ADDR"]=>
    string(15) "118.200.235.133"
    ["DOCUMENT_ROOT"]=>
    string(26) "/home/riverapp/public_html"
    ["REQUEST_SCHEME"]=>
    string(5) "https"
    ["CONTEXT_PREFIX"]=>
    string(8) "/cgi-sys"
    ["CONTEXT_DOCUMENT_ROOT"]=>
    string(26) "/usr/local/cpanel/cgi-sys/"
    ["SERVER_ADMIN"]=>
    string(23) "webmaster@river-app.com"
    ["SCRIPT_FILENAME"]=>
    string(36) "/home/riverapp/public_html/index.php"
    ["REMOTE_PORT"]=>
    string(5) "60875"
    ["REDIRECT_URL"]=>
    string(24) "/index.php/test_api/test"
    ["GATEWAY_INTERFACE"]=>
    string(7) "CGI/1.1"
    ["SERVER_PROTOCOL"]=>
    string(8) "HTTP/1.1"
    ["REQUEST_METHOD"]=>
    string(4) "POST"
    ["QUERY_STRING"]=>
    string(0) ""
    ["REQUEST_URI"]=>
    string(24) "/index.php/test_api/test"
    ["SCRIPT_NAME"]=>
    string(10) "/index.php"
    ["PATH_INFO"]=>
    string(14) "/test_api/test"
    ["PATH_TRANSLATED"]=>
    string(40) "/home/riverapp/public_html/test_api/test"
    ["ORIG_PATH_INFO"]=>
    string(24) "/index.php/test_api/test"
    ["ORIG_SCRIPT_NAME"]=>
    string(17) "/cgi-sys/ea-php56"
    ["ORIG_SCRIPT_FILENAME"]=>
    string(34) "/usr/local/cpanel/cgi-sys/ea-php56"
    ["ORIG_PATH_TRANSLATED"]=>
    string(50) "/home/riverapp/public_html/index.php/test_api/test"
    ["PHP_SELF"]=>
    string(24) "/index.php/test_api/test"
    ["REQUEST_TIME_FLOAT"]=>
    float(1510719398.04)
    ["REQUEST_TIME"]=>
    int(1510719398)
    ["argv"]=>
    array(0) {
    }
    ["argc"]=>
    int(0)
    }

What could be the thing causing this issue.

Body:
Try adding this line to top of your controller

header('Content-Type: application/json');


问:
How can I see all the data that solr is indexing?
So I have a solr server running as part of a chef server. Some of my nodes just aren't coming up in searches. I can use ?q=*:* to show the documents but most of the chef data is indexed as dynamicFields, so I don't see it in the xml documents.

I'm hoping that if I can find a way to see either:

what's coming into solr as it's indexed or

the full set of indexed documents with their dynamic fields

Thanks in advance!

答: As rfeak said, you can use Luke to inspect your index. Solr comes with a built-in Luke handler.</p>


问:
Setting user agent of a java URLConnection
I'm trying to parse a webpage using Java with URLConnection. I try to set up the user-agent like this:

```<code>java.net.URLConnection c = url.openConnection();
c.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
</code>```

But the resulting user agent is the one I specify, with "Java/1.5.0_19" appended to the end. Is there a way to truly set the user agent without this addition?

答:
its work for me
set the User-Agent in the addRequestProperty.

```<code>URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
</code>```

Body:
I'm trying to parse a webpage using Java with URLConnection. I try to set up the user-agent like this:

java.net.URLConnection c = url.openConnection();
c.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

But the resulting user agent is the one I specify, with "Java/1.5.0_19" appended to the end. Is there a way to truly set the user agent without this addition?

Body:
its work for me
set the User-Agent in the addRequestProperty.

URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");


问:
merge two pandas data frame and skip common columns of right
I am using pandas DataFrame as a lightweight dataset to maintain some status and need to dynamically/continuously merge new DataFrames into existing table. Say I have two datasets as below:

df1:

```<code>   a  b
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9
</code>```

df2:

```<code>    b   c
0  10  11
1  12  13
2  14  15
3  16  17
4  18  19
</code>```

I want to merge df2 to df1 (on index), and for columns in common (in this case, it is 'b'), simply discard the common column of df2.

```<code>   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19
</code>```

My code was checking common part between df1 and df2 by using SET， so that I manually drop common part in df2. I wonder is there any much efficient way to do this?

答:
First identify the columns in df2 not in df1

```<code>cols = df2.columns.difference(df1.columns)
</code>```

Then pd.DataFrame.join

```<code>df1.join(df2[cols])

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19
</code>```

Or pd.concat will also work

```<code>pd.concat([df1, df2[cols]], axis=1)

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19
</code>```

Body:
I am using pandas DataFrame as a lightweight dataset to maintain some status and need to dynamically/continuously merge new DataFrames into existing table. Say I have two datasets as below:

df1:

   a  b
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

df2:

    b   c
0  10  11
1  12  13
2  14  15
3  16  17
4  18  19

I want to merge df2 to df1 (on index), and for columns in common (in this case, it is 'b'), simply discard the common column of df2.

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19

My code was checking common part between df1 and df2 by using SET， so that I manually drop common part in df2. I wonder is there any much efficient way to do this?

Body:
First identify the columns in df2 not in df1

cols = df2.columns.difference(df1.columns)

Then pd.DataFrame.join

df1.join(df2[cols])

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19

Or pd.concat will also work

pd.concat([df1, df2[cols]], axis=1)

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19


问:
RecursionError when python copy.deepcopy
I have a problem in python.

I have a class whis custom __getattr__

```<code>class ChoiceNumToName(object):
    def __init__(self, django_choice_tuple):
        self.ods_choice_tuple = django_choice_tuple
        self.choice_data = {}
        self.choice_point = -1
        for choice_value, choice_name in django_choice_tuple:
            self.choice_data.setdefault(choice_name, choice_value)

    def __getattr__(self, item):
        if item in self.choice_data:
            return self.choice_data[item]
        else:
            raise AttributeError("no attribute %s" % item)

    def __str__(self):
        return str(self.ods_choice_tuple)

    def __iter__(self):
        self.choice_point = -1
        return self

    def __next__(self):
        self.choice_point += 1
        try:
            return self.ods_choice_tuple[self.choice_point]
        except IndexError:
            raise StopIteration()
</code>```

when I execute this

```<code>a = ChoiceNumToName((
    (1, "running"),
    (2, "stopped"),
))
b = copy.deepcopy(a)
</code>```

It raise RecursionError: maximum recursion depth exceeded while calling a Python object

To fix this problem is sample, change __getattr__ function to this

```<code>def __getattr__(self, item):
    if item == "__setstate__":
        raise AttributeError(item)
    if item in self.choice_data:
        return self.choice_data[item]
    else:
        raise AttributeError("no attribute %s" % item)
</code>```

It work well.

I know this solution from here
https://github.com/python-babel/flask-babel/commit/8319a7f44f4a0b97298d20ad702f7618e6bdab6a

But can anyone tell me why?

答:
TLDR: your __getattr__ is called before choice_data has been added to the instance dictionary which causes it to endlessly recurse. A better way to address the problem is to immediately raise AttributeError for any attributes beginning with __ to catch any other special or internal attributes.

This happens because when an object is copied the __init__ method is not called. Rather, a new, empty object is created. This new object has an empty __dict__. Python's pickle protocol (which is also used for the copy module) has a hook __setstate__ that allows customization of applying a state (normally just the contents for __dict__ but, e.g. if __getstate__ is provided, it can be any object). To see if that hook is present hasattr(newobj, '__setstate__') is called which, since there isn't any __setstate__ in the MRO nor in the __dict__ causes your __getattr__ to be called. Your __getattr__ then tries to access self.choice_data but, as we've noted earlier the __dict__ is currently empty. This causes the __getattr__ method to be invoked again to get the choice_data attribute which starts the infinite recursion.

Special casing __setstate__ stops the recursion from being triggered by bailing out early for the lookup of __setstate__. When that fails, the default mechanism for copying takes effect which initializes the new object's __dict__ from the state. In my mind special casing only __setstate__ is not the best solution. I think it is best to immediately raise AttributeError for any special or internal attributes, i.e. the ones that begin with __, since that prevents other strange situations from occurring. Another possibility is to avoid using attribute lookup within __getattr__ by writing self.__dict__['choice_data'] or object.__getattribute__(self, 'choice_data'). You can also ensure that choice_data will be present by implementing __new__ and assigning it to the object there.

Body:
I have a problem in python.

I have a class whis custom __getattr__

class ChoiceNumToName(object):
    def __init__(self, django_choice_tuple):
        self.ods_choice_tuple = django_choice_tuple
        self.choice_data = {}
        self.choice_point = -1
        for choice_value, choice_name in django_choice_tuple:
            self.choice_data.setdefault(choice_name, choice_value)

    def __getattr__(self, item):
        if item in self.choice_data:
            return self.choice_data[item]
        else:
            raise AttributeError("no attribute %s" % item)

    def __str__(self):
        return str(self.ods_choice_tuple)

    def __iter__(self):
        self.choice_point = -1
        return self

    def __next__(self):
        self.choice_point += 1
        try:
            return self.ods_choice_tuple[self.choice_point]
        except IndexError:
            raise StopIteration()

when I execute this

a = ChoiceNumToName((
    (1, "running"),
    (2, "stopped"),
))
b = copy.deepcopy(a)

It raise RecursionError: maximum recursion depth exceeded while calling a Python object

To fix this problem is sample, change __getattr__ function to this

def __getattr__(self, item):
    if item == "__setstate__":
        raise AttributeError(item)
    if item in self.choice_data:
        return self.choice_data[item]
    else:
        raise AttributeError("no attribute %s" % item)

It work well.

I know this solution from here
https://github.com/python-babel/flask-babel/commit/8319a7f44f4a0b97298d20ad702f7618e6bdab6a

But can anyone tell me why?


问:
How to get the user to auto fill framework setting screen pro-grammatically in android 8.0
I want to get the user to auto-fill framework settings screen to enable the AutoFill framework to auto-fill the login form in third-party apps.

So, how can I get the user programmatically to the auto-fill settings screen in Oreo devices?

答:
After a long search i have found answer from gitup projects.

The code to get the user to auto fill settings screen pro-grammatically is below

```<code>   if (mAutofillManager != null && !mAutofillManager.hasEnabledAutofillServices()) {
        Intent intent = new Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE);
        intent.setData(Uri.parse("package:com.example.android"));
        startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT);
    }
</code>```

Body:
After a long search i have found answer from gitup projects.

The code to get the user to auto fill settings screen pro-grammatically is below

   if (mAutofillManager != null && !mAutofillManager.hasEnabledAutofillServices()) {
        Intent intent = new Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE);
        intent.setData(Uri.parse("package:com.example.android"));
        startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT);
    }


问:
Scale up a nodejs app on AWS
I have nodejs app running on AWS EC2.

I would like to scale it up by creating more instances of it.

I don't quite understand how to do it on the networking side.

Lets say I create another instance and it's listening to a different port.
Should I change the client side to request from two different ports? I believe this could lead to race conditions on the DB

Am I suppose to listen on one port on the EC2 machine and direct the request to one of the instances? In that case the port will be busy until the instance is done with the request instead of processing requests in parallel with the other instance

Does anyone has some pointers or maybe can point me to some documents about this subject?

答:
At the basic level, you'll have multiple instances of your Node.js application, connecting to a common database backend.  (Your database should be clustered as well, but that's a topic for another post.)

If you're following best practices already, one request will be one response, and it won't matter if subsequent requests land on a different application server.  That is, the client could hit any of them at any time and there won't be any side effects.  If not, you'll need some sort of server pinning (usually done via cookie or similar methods) to ensure clients always land on the same application server.

The simplest way to load balance is to have your clients connect to a host name, and that hostname resolved round-robin style to several hosts.  This will spread the traffic around, but not necessarily correctly.  For instance, a particular command or issue on one host could mean it can only handle 5 requests, while the other servers can handle 5000.  Most cloud providers have management of load balancing.  AWS certainly does.

Since you're already on AWS, I'd recommend you deploy your application via Elastic Beanstalk.  It automates the spin-up/tear-down as-configured.  You could certainly roll your own solution, but it's probably just easier to use what's already there.  The load balancer is configured with Beanstalk.

Title: Scale up a nodejs app on AWS


问:
Persistence mechanism used by Orbeon Forms

Is orbeon using JDBC or any other ORM technique to persist the data.

I have downloaded the orbeon CE source code from GitHub provided by Orbeon. It would be better if someone suggested me the code flow of Orbeon Forms.

答:
Is orbeon using JDBC or any other ORM technique to persist the data.

JDBC yes, ORM no.

For details on the tables, see the links to the DLL in database setup

I have downloaded the orbeon CE source code from GitHub provided by Orbeon. It would be better if someone suggested me the code flow of Orbeon Forms.

That would be way beyond the scope of a simple StackOverflow question.


问:
how do I compare 2 functions in javascript
How do I compare 2 functions in javascript?
I am not talking about internal reference. Say

```<code>var a = function(){return 1;};
var b = function(){return 1;};
</code>```

Is it possible to compare a and b ?

答:
toString() on a function returns the exact declaration. You can modify jfriend00's code to test it out.

This means you can test to see if your functions are exactly the same, including what spaces and newlines you put in it.

But first you have to eliminate the difference in their names.

```<code>function foo1() {
    return 1;
}

function foo2() {
    return 1;
}

//Get a string of the function declaration exactly as it was written.
var a = foo1.toString();
var b = foo2.toString();

//Cut out everything before the curly brace.
a = a.substring(a.indexOf("{"));
b = b.substring(b.indexOf("{"));

//a and b are now this string:
//"{
//    return 1;
//}"
alert(a == b); //true.
</code>```

As the others said, this is unreliable because a single whitespace of difference makes the comparison false.

But what if you're employing it as a protective measure? ("Has someone altered my function since I created it?") You may actually desire this kind of strict comparison then.

Body:
How do I compare 2 functions in javascript?
I am not talking about internal reference. Say

var a = function(){return 1;};
var b = function(){return 1;};

Is it possible to compare a and b ?

Body:
toString() on a function returns the exact declaration. You can modify jfriend00's code to test it out.

This means you can test to see if your functions are exactly the same, including what spaces and newlines you put in it.

But first you have to eliminate the difference in their names.

function foo1() {
    return 1;
}

function foo2() {
    return 1;
}

//Get a string of the function declaration exactly as it was written.
var a = foo1.toString();
var b = foo2.toString();

//Cut out everything before the curly brace.
a = a.substring(a.indexOf("{"));
b = b.substring(b.indexOf("{"));

//a and b are now this string:
//"{
//    return 1;
//}"
alert(a == b); //true.

As the others said, this is unreliable because a single whitespace of difference makes the comparison false.

But what if you're employing it as a protective measure? ("Has someone altered my function since I created it?") You may actually desire this kind of strict comparison then.