text:
Q: Android Asynchronous http for network call issue with 4.4,4.2 android-async-http An Asynchronous HTTP Library for Android https://github.com/loopj/android-async-http
I am using asynchronous http for network calls. Lollipop and above Lollipop it's working perfectly. But below this version my code gives below error.
com.example.administrator.login E/dalvikvm: Could not find class 'com.loopj.android.http.RequestParams$1', referenced from method com.loopj.android.http.RequestParams.<init>
05-29 04:04:11.388 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 8577 (Lcom/loopj/android/http/RequestParams$1;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.388 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x0000
05-29 04:04:11.388 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity', referenced from method com.loopj.android.http.RequestParams.createFormEntity
05-29 04:04:11.388 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 9001 (Lcz/msebera/android/httpclient/client/entity/UrlEncodedFormEntity;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.388 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x0000
05-29 04:04:11.388 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve static field 34133 (log) in Lcom/loopj/android/http/AsyncHttpClient;
05-29 04:04:11.388 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x62 at 0x000d
05-29 04:04:11.388 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'com.loopj.android.http.JsonStreamerEntity', referenced from method com.loopj.android.http.RequestParams.createJsonStreamerEntity
05-29 04:04:11.388 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 8574 (Lcom/loopj/android/http/JsonStreamerEntity;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.388 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x0000
05-29 04:04:11.388 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'com.loopj.android.http.SimpleMultipartEntity', referenced from method com.loopj.android.http.RequestParams.createMultipartEntity
05-29 04:04:11.388 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 8582 (Lcom/loopj/android/http/SimpleMultipartEntity;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.388 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x0000
05-29 04:04:11.388 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'cz.msebera.android.httpclient.message.BasicNameValuePair', referenced from method com.loopj.android.http.RequestParams.getParamsList
05-29 04:04:11.388 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 9302 (Lcz/msebera/android/httpclient/message/BasicNameValuePair;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.388 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x00f1
05-29 04:04:11.388 5843-5843/com.example.administrator.login I/dalvikvm: Could not find method cz.msebera.android.httpclient.client.utils.URLEncodedUtils.format, referenced from method com.loopj.android.http.RequestParams.getParamString
05-29 04:04:11.388 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve static method 61456: Lcz/msebera/android/httpclient/client/utils/URLEncodedUtils;.format (Ljava/util/List;Ljava/lang/String;)Ljava/lang/String;
05-29 04:04:11.388 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x71 at 0x0006
05-29 04:04:11.392 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'cz.msebera.android.httpclient.message.BasicNameValuePair', referenced from method com.loopj.android.http.RequestParams.getParamsList
05-29 04:04:11.392 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 9302 (Lcz/msebera/android/httpclient/message/BasicNameValuePair;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.392 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x001b
05-29 04:04:11.392 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'com.loopj.android.http.RequestParams$FileWrapper', referenced from method com.loopj.android.http.RequestParams.put
05-29 04:04:11.392 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 8578 (Lcom/loopj/android/http/RequestParams$FileWrapper;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.392 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x0012
05-29 04:04:11.392 5843-5843/com.example.administrator.login I/dalvikvm: Could not find method com.loopj.android.http.RequestParams$StreamWrapper.newInstance, referenced from method com.loopj.android.http.RequestParams.put
05-29 04:04:11.396 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve static method 59098: Lcom/loopj/android/http/RequestParams$StreamWrapper;.newInstance (Ljava/io/InputStream;Ljava/lang/String;Ljava/lang/String;Z)Lcom/loopj/android/http/RequestParams$StreamWrapper;
05-29 04:04:11.396 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x71 at 0x0006
05-29 04:04:11.396 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'com.loopj.android.http.RequestParams$FileWrapper', referenced from method com.loopj.android.http.RequestParams.put
05-29 04:04:11.396 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve new-instance 8578 (Lcom/loopj/android/http/RequestParams$FileWrapper;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.396 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x22 at 0x001b
05-29 04:04:11.396 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve static field 34133 (log) in Lcom/loopj/android/http/AsyncHttpClient;
05-29 04:04:11.396 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x62 at 0x0005
05-29 04:04:11.396 5843-5843/com.example.administrator.login E/dalvikvm: Could not find class 'cz.msebera.android.httpclient.message.BasicNameValuePair', referenced from method com.loopj.android.http.RequestParams.toString
05-29 04:04:11.396 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to resolve check-cast 9302 (Lcz/msebera/android/httpclient/message/BasicNameValuePair;) in Lcom/loopj/android/http/RequestParams;
05-29 04:04:11.396 5843-5843/com.example.administrator.login D/dalvikvm: VFY: replacing opcode 0x1f at 0x0106
05-29 04:04:11.400 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xe6d8 at 0x02 in Lcom/loopj/android/http/RequestParams;.<init>
05-29 04:04:11.400 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xef74 at 0x08 in Lcom/loopj/android/http/RequestParams;.createFormEntity
05-29 04:04:11.400 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xe6d1 at 0x15 in Lcom/loopj/android/http/RequestParams;.createJsonStreamerEntity
05-29 04:04:11.400 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856e at 0xa2 in Lcom/loopj/android/http/RequestParams;.createJsonStreamerEntity
05-29 04:04:11.400 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856e at 0xac in Lcom/loopj/android/http/RequestParams;.createJsonStreamerEntity
05-29 04:04:11.400 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856f at 0xae in Lcom/loopj/android/http/RequestParams;.createJsonStreamerEntity
05-29 04:04:11.400 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856d at 0xb0 in Lcom/loopj/android/http/RequestParams;.createJsonStreamerEntity
05-29 04:04:11.400 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856c at 0xb2 in Lcom/loopj/android/http/RequestParams;.createJsonStreamerEntity
05-29 04:04:11.400 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xe712 at 0x04 in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856e at 0x8d in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856f at 0x97 in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856e at 0x9b in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856d at 0x9f in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856b at 0xd1 in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x8569 at 0xd5 in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856a at 0xd9 in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856b at 0x11b in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.404 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x8569 at 0x11f in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.408 5843-5843/com.example.administrator.login I/dalvikvm: DexOpt: unable to optimize instance field ref 0x856a at 0x123 in Lcom/loopj/android/http/RequestParams;.createMultipartEntity
05-29 04:04:11.408 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xf69b at 0xf9 in Lcom/loopj/android/http/RequestParams;.getParamsList
05-29 04:04:11.408 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xf69b at 0x29 in Lcom/loopj/android/http/RequestParams;.getParamsList
05-29 04:04:11.408 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xe6d9 at 0x14 in Lcom/loopj/android/http/RequestParams;.put
05-29 04:04:11.408 5843-5843/com.example.administrator.login D/dalvikvm: DexOpt: unable to opt direct call 0xe6d9 at 0x1d in Lcom/loopj/android/http/RequestParams;.put
05-29 04:04:11.412 5843-5843/com.example.administrator.login D/dalvikvm: GC_FOR_ALLOC freed 278K, 11% free 3279K/3664K, paused 1ms, total 2ms
05-29 04:04:11.416 5843-5843/com.example.administrator.login D/dalvikvm: GC_FOR_ALLOC freed 62K, 10% free 3428K/3804K, paused 2ms, total 2ms
05-29 04:04:11.416 5843-5843/com.example.administrator.login I/dalvikvm-heap: Grow heap (frag case) to 4.526MB for 1127532-byte allocation
05-29 04:04:11.420 5843-5852/com.example.administrator.login D/dalvikvm: GC_FOR_ALLOC freed 1K, 8% free 4528K/4908K, paused 4ms, total 4ms
05-29 04:04:11.428 5843-5843/com.example.administrator.login W/dalvikvm: VFY: unable to find class referenced in signature ([Lcz/msebera/android/httpclient/Header;)
05-29 04:04:11.428 5843-5843/com.example.administrator.login W/dalvikvm: VFY: returning Ljava/lang/Object; (cl=0x0), declared [Ljava/lang/Object; (cl=0x0)
05-29 04:04:11.428 5843-5843/com.example.administrator.login W/dalvikvm: VFY:  rejecting opcode 0x11 at 0x0002
05-29 04:04:11.428 5843-5843/com.example.administrator.login W/dalvikvm: VFY:  rejected Lcom/loopj/android/http/AsyncHttpResponseHandler;.getRequestHeaders ()[Lcz/msebera/android/httpclient/Header;
05-29 04:04:11.428 5843-5843/com.example.administrator.login W/dalvikvm: Verifier rejected class Lcom/loopj/android/http/AsyncHttpResponseHandler;
05-29 04:04:11.428 5843-5843/com.example.administrator.login D/AndroidRuntime: Shutting down VM
05-29 04:04:11.428 5843-5843/com.example.administrator.login W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4cabb20)
05-29 04:04:11.428 5843-5843/com.example.administrator.login E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.administrator.login, PID: 5843
                                                                               java.lang.VerifyError: com/loopj/android/http/AsyncHttpResponseHandler
                                                                                at com.example.administrator.login.activity.LoginActivity.checkLogin(LoginActivity.java:146)
                                                                                at com.example.administrator.login.activity.LoginActivity$1.onClick(LoginActivity.java:109)
                                                                                at android.view.View.performClick(View.java:4438)
                                                                                at android.view.View$PerformClick.run(View.java:18422)
                                                                                at android.os.Handler.handleCallback(Handler.java:733)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                                at dalvik.system.NativeStart.main(Native Method)

I am using below code for login. It's working in Lollipop 5.0,5.1,6.0
But in 4.4,4.2 am getting the above mentioned error. What should I do? Techgeeks please help me.
onHttpRequest.post("login", requestParams, new AsyncHttpResponseHandler() {

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        hideDialog();
        try {

            String s=new String(responseBody);
            JSONObject jObj = new JSONObject(s);
            boolean error = jObj.getBoolean("error");

            // Check for error node in json
            if (!error) {
                // user successfully logged in
                // Create login session

                // Now store the user in SQLite

                JSONObject user = jObj.getJSONObject("user");
                String name = user.getString("name");
                String email = user.getString("email");

                // Starting a session
                userSessionManager.createUserLoginSession(name,
                        email);

                // Launch main activity
                Intent intent = new Intent(LoginActivity.this,
                        SplashActivity.class);
                intent.putExtra("email",email);
                startActivity(intent);
                finish();
            } else {
                // Error in login. Get the error message
                String errorMsg = jObj.getString("error_msg");
                Toast.makeText(getApplicationContext(),
                        errorMsg, Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            // JSON error
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        hideDialog();
        // When Http response code is '404'
        if(statusCode == 404){
            Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
        }
        // When Http response code is '500'
        else if(statusCode == 500){
            Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
        }
        // When Http response code other than 404, 500
        else{
            Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
        }

    }
});


text:
Q: Django url end href error: Reverse for '' with arguments '('',)' and keyword arguments '{}' not found as a beginner in Django, I have a problem with producing the correct link to the edit form.
If you manually type in the address

localhost:8000/edit/1

from your browser i receive a form for editing.
views.py
def edit(request, stat_id):
    stat = fms.objects.get(pk=stat_id)
    if request.method == 'POST':
        form = fmsForm(request.POST, instance=stat)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/fmstat/')
    else:
        form = fmsForm(instance=stat)

    return render(request, 'fmstat/edit.html', {'form': form,})

url.py
url(r'^edit/(?P<stat_id>(\d+))', 'fmstat.views.edit'),

link in template:
link

A: You are not passing the stat_id
{% url fmstat.views.edit stat_id=some_id %}

Also its a good approach to use the url name in url tag:
url(r'^edit/(?P<stat_id>(\d+))',
     'fmstat.views.edit', {},
      name='stat_edit'),

then:
{% url stat_edit stat_id=some_id %}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Table , localStorage, js I have code:
function inicjalizacja(){
    var pracownicy = localStorage.getItem('Pracownicy');
    if (pracownicy === null) {
         localStorage.setItem('Pracownicy',JSON.stringify([]));
    }
}

function Pracownik(imie, drugie_imie, nazwisko, ulica, miejscowosc, kod_pocztowy, telefon, email, wynagrodzenie) {
    this.imie = imie;
    this.drugie_imie=drugie_imie;
    this.nazwisko=nazwisko;
    this.ulica=ulica;
    this.miejscowosc=miejscowosc;
    this.kod_pocztowy=kod_pocztowy;
    this.telefon=telefon;
    this.wynagrodzenie=wynagrodzenie;
}

function Zapisz() {
    inicjalizacja();
    var formularz=document.forms.formularz;
    var nowy_pracownik = new Pracownik(formularz.imie.value,formularz.drugie_imie.value,formularz.nazwisko.value,formularz.ulica.value,
        formularz.miejscowosc.value, formularz.kod_pocztowy.value,formularz.telefon.value,formularz.email.value,formularz.wynagrodzenie.value);

    var pracownicyString = localStorage.getItem('Pracownicy');
    var pracownicy = JSON.parse(pracownicyString);
    pracownicy.push(nowy_pracownik);
    localStorage.setItem('Pracownicy',JSON.stringify(pracownicy));
    confirm("Dodano nowego pracownika!");
}

where I save my data in localStorage. Now, I would like to read the data, so i'm doing like this:
function Wyswietl(){

    var zawartosc = localStorage.getItem('Pracownicy');
    document.write(zawartosc)
}

but it shows me this disordered . I would like to ask , how could I do this to me right away that displayed a table ? I'am begginer in js.

A: The easiest way would be sorting an array after you get it from the localStorage. This way you will have an array always in the same order. In the real world scenario you should always have an employeeId property or any other key which you can use in the sort method.


text:
Q: How to convert Datetime into only Date format lblAppointmentDate.Text = dt.Rows[0]["AppDate"].ToString();

This is my code giving the output as:

AppointmentDate: 11/19/2014 12:00:00 AM.

I want only Date as 19/11/2014.

A: You can format the date however you like.
Use ToString() on the DateTime and pass in the appropriate format string.
Try one of the format strings from here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
someDateTime.ToString("MM/dd/yyyy)

A: You need to format it like following. Before that don't forget to convert to datetime type. Following is just an example only.
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("dd/MM/yyyy"));


text:
Q: FitNesse: Flow Mode using SetUp page to define enclosing table in .NET I'm working my way through the eBook Test Driven .NET Development with FitNesse (PDF) and I've run into a problem creating a test page using flow mode with a DoFixture (Chapter 8 Coordinating fixtures).  Following through the tutorial in the chapter you create a test page using flow mode then refactor it to move the setup, including the first two tables, into a separate SetUp page (the refactoring starts on page 99 of the book).
I was able to create the initial flow mode test page successfully but I can't get the refactored version working, with the separate SetUp page.  I figure I'm missing something obvious but I can't see it.
Here is the contents of SettlementTests.SetUp:
!define COMMAND_PATTERN {%m -r fitnesse.fitserver.FitServer %p}
!define TEST_RUNNER {FitSharp\Runner.exe}
!path C:\...\Tristan.Test.dll

!|Tristan.Test.SettlementTest|

|Accounts before the draw|
|player|balance|
|Arthur|100|
|Ford|100|
|Trisha|100|
|Marvin|100|

And this is the SettlementTests.OneWinnerSixBallsFirstTry page:
|Tickets in the Draw|
|player|numbers|value|
|Ford|2,11,22,33,39,18|50|
|Arthur|1,5,4,7,9,20|50|
|Trisha|10,21,30,6,16,26|50|
|Marvin|12,13,14,15,16,17|50|

|Draw results are|1,5,4,20,9,7|

|Accounts after the Draw|
|Player|Balance?|
|Arthur|118|
|Ford|50|
|Trisha|50|
|Marvin|50|

For each table I'm getting the error message:

Could not find fixture: Tristan.Test.SettlementTest.

(or whatever the fixture name specified in the table is)
I've created a parent SettlementTests suite page, and tried setting the SetUp page as both a Static page and as a Test page.  I get the same results in both cases.  The classpath is the same as the all-in-one page that works.
Is there something special I need to do to get flow mode working when I define the enclosing table in the SetUp page?

A: Move the !define and !path lines out of the SetUp page and onto the parent page.


text:
Q: Deleting old SVN Externals Running svn version 1.8
I have a directory with some svn externals in it defined using TortoiseSVN properties.
Also defined in this directory are some older externals - I have no idea where these are defined.
If I define a new external (for example, FreeRTOS pointing to tag 7.4) with the same name as an old external (for example, FreeRTOS pointing to tag 5.1), upon checking out, the old external will take priority.
If I type propset -R svn:externals, only the new externals are listed.
How are these old externals defined and how can I delete them?

A: Thanks Lazy Badger, your comment provided the inspiration required. The issue was the svn externals being defined in the parent folder.
I used svn pl -v -R in the root directory to list all properties recursively and found the externals from there.


text:
Q: How to get info from pyscopg2 connection object? How can I retrieve information about the host from the connection object?
import psycopg2
connection = psycopg2.connect("host='localhost'")

In this case, I would want to know which port is being connected to. In another case I may simply want to parse out the host name for logging.
I could parse the connection.dsn but there must be cleaner way since psycopg2 has already done the work of parsing this information (or has it?).

A: You can use the method get_dsn_parameters (docs) to get a dictionary containing all the dsn parameters, including the port. Also available as .info.dsn_parameters (docs).
For example:
port = connection.get_dsn_parameters()["port"]

or
port = connection.info.dsn_parameters["port"]

Whichever you like better.


text:
Q: working with html on python code so in PHP it's possible to have an entire section of php source be filled with direct raw html:
    <?php
    function doThis(){
    ?>

    LOOL

    <?php
    }

    doThis();

    ?>

and calling doThis() will print out all the html code between the curly braces...is there a similar functionality in Python? or do I have to virtually print all the HTML individually using the print command? python's indentation seems to make it really inconvenient to write HTML on python code

A: Python is not a pseudo-template language like PHP, if you want to generate HTML use a template engine like Jinja2.

A: I'm not certain I fully understand your question, but if you need to have long blocks of arbitrary text in Python the best way I've found is like so:
myHTML = """

<title>I am an HTML Page<title>

Some content here.

"""

The key is the triple Quotes.  It allows you to put any other content between them, including line breaks, spacing, etc.

A: First, multiline strings:
"""\

LOOL
"""

Second, if you're writing something significant, you should use a web framework and a template language for the page layout and static content.

A: Use some template languages like jinja or mako

A: Well, you could put the code into a file and make python print out the file.
OR
use string suppression to escape everything:
def printHTML():
    HTML = """ all this
is
considered to be
    ONE
        GIANT
            STRING
"""
    print HTML

Hope this helps


text:
Q: ubuntu 16.04 owner rights I have a brand new installation of Ubuntu 16.04 on my HP stream 11-001nd. It's the only OS on installed without any partitions.
Now I want to create /etc/pm/config.d/config.
I clicked on the right mouse button to select new document. This appears to be not selectable. So I went to properties, permissions, and there is shown at the bottom of that window, You are not the owner, so you cannot change these permissions.
Well, if I'm not the owner, who is? How can I change this so I'll be able to create that file.

A: The mentioned folder is owned by root, so you should create and edit the file as root. To achieve that, you can press Alt+F2 and type

gksu gedit /etc/pm/config.d/config

You will be prompted for root password.
If you are familiar with terminal, you can easily create the file with command

sudo nano /etc/pm/config.d/config

(substitute nano with your favorite text editor)

A: There are (at least) two users in any Ubuntu installation. Both are in your control.
The two are

*

*Your user

*root user - Linux equivalent of administrator account. Has all powers. Handles administrative tasks.

Now, your user only has access to your personal files. All other files, which are essential configuration and system files, are owned by root.
How do I access them?
The root account can only (unless you willingly workaround this) is by using sudo. sudo is the program that allows normal users (like you) to run programs with powers of the administrative root user.
Hit Alt+F2 and type gksudo nautilus in it and hit Enter.
A dialog asking for a password will appear. Enter your password and hit Enter or Click OK.
The file manager should open, but this time it is run with root's powers. You can now do anything, including creating that file.
Why are there two accounts if I can access it anyway?
Privilege separation — the idea that you should only get the power to do/destroy anything when you need it. A major contributor to Linux's excellent reputation for security is due to the fact that it separates admin from user.
If you would run as root all the time, any virus could destroy your system very easily.

A: Use the following command
su administrator

"Enter root password of admin"
cd "path of the file"

sudo gedit "filename"

Root is the equivalent default super user to administrator. As your standard account does not have permission, you have to switch back to administrator or root user. su command will switch the username passed as a root user.

A: This is happening because you don't own the file.
To get access to file just do the following.

*

*Open the terminal and type:
$sudo -s

*Type the administrator password.

*Then do, (don't forget to substitute the username)
$cd /home/[username]/.config
$chmod 777 opera


text:
Q: Neo4j: label vs. indexed property? Suppose you're Twitter, and:

*

*You have (:User) and (:Tweet) nodes;

*Tweets can get flagged; and

*You want to query the list of flagged tweets currently awaiting moderation.

You can either add a label for those tweets, e.g. :AwaitingModeration, or add and index a property, e.g. isAwaitingModeration = true|false.
Is one option inherently better than the other?
I know the best answer is probably to try and load test both :), but is there anything from Neo4j's implementation POV that makes one option more robust or suited for this kind of query?
Does it depend on the volume of tweets in this state at any given moment? If it's in the 10s vs. the 1000s, does that make a difference?
My impression is that labels are better suited for a large volume of nodes, whereas indexed properties are better for smaller volumes (ideally, unique nodes), but I'm not sure if that's actually true.
Thanks!

A: UPDATE: Follow up blog post published.
This is a common question when we model datasets for customers and a typical use case for Active/NonActive entities.
This is a little feedback about what I've experienced valid for Neo4j2.1.6 :
Point 1. You will not have difference in db accesses between matching on a label or on an indexed property and return the nodes
Point 2. The difference will be encountered when such nodes are at the end of a pattern, for example
MATCH (n:User {id:1})
WITH n
MATCH (n)-[:WRITTEN]->(post:Post)
WHERE post.published = true
RETURN n, collect(post) as posts;

-
PROFILE MATCH (n:User) WHERE n._id = 'c084e0ca-22b6-35f8-a786-c07891f108fc'
> WITH n
> MATCH (n)-[:WRITTEN]->(post:BlogPost)
> WHERE post.active = true
> RETURN n, size(collect(post)) as posts;
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| n                                                                                | posts |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Node[118]{_id:"c084e0ca-22b6-35f8-a786-c07891f108fc",login:"joy.wiza",password:"7425b990a544ae26ea764a4473c1863253240128",email:"hayes.shaina@yahoo.com"} | 1     |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row

ColumnFilter(0)
  |
  +Extract
    |
    +ColumnFilter(1)
      |
      +EagerAggregation
        |
        +Filter
          |
          +SimplePatternMatcher
            |
            +SchemaIndex

+----------------------+------+--------+----------------------+----------------------------------------------------------------------------+
|             Operator | Rows | DbHits |          Identifiers |                                                                      Other |
+----------------------+------+--------+----------------------+----------------------------------------------------------------------------+
|      ColumnFilter(0) |    1 |      0 |                      |                                                      keep columns n, posts |
|              Extract |    1 |      0 |                      |                                                                      posts |
|      ColumnFilter(1) |    1 |      0 |                      |                                           keep columns n,   AGGREGATION153 |
|     EagerAggregation |    1 |      0 |                      |                                                                          n |
|               Filter |    1 |      3 |                      | (hasLabel(post:BlogPost(1)) AND Property(post,active(8)) == {  AUTOBOOL1}) |
| SimplePatternMatcher |    1 |     12 | n, post,   UNNAMED84 |                                                                            |
|          SchemaIndex |    1 |      2 |                 n, n |                                                {  AUTOSTRING0}; :User(_id) |
+----------------------+------+--------+----------------------+----------------------------------------------------------------------------+

Total database accesses: 17

In this case, Cypher will not make use of the index :Post(published).
Thus the use of labels is more performant in the case you have a ActivePost label for e.g. :
neo4j-sh (?)$ PROFILE MATCH (n:User) WHERE n._id = 'c084e0ca-22b6-35f8-a786-c07891f108fc'
> WITH n
> MATCH (n)-[:WRITTEN]->(post:ActivePost)
> RETURN n, size(collect(post)) as posts;
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| n                                                                                | posts |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Node[118]{_id:"c084e0ca-22b6-35f8-a786-c07891f108fc",login:"joy.wiza",password:"7425b990a544ae26ea764a4473c1863253240128",email:"hayes.shaina@yahoo.com"} | 1     |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row

ColumnFilter(0)
  |
  +Extract
    |
    +ColumnFilter(1)
      |
      +EagerAggregation
        |
        +Filter
          |
          +SimplePatternMatcher
            |
            +SchemaIndex

+----------------------+------+--------+----------------------+----------------------------------+
|             Operator | Rows | DbHits |          Identifiers |                            Other |
+----------------------+------+--------+----------------------+----------------------------------+
|      ColumnFilter(0) |    1 |      0 |                      |            keep columns n, posts |
|              Extract |    1 |      0 |                      |                            posts |
|      ColumnFilter(1) |    1 |      0 |                      | keep columns n,   AGGREGATION130 |
|     EagerAggregation |    1 |      0 |                      |                                n |
|               Filter |    1 |      1 |                      |     hasLabel(post:ActivePost(2)) |
| SimplePatternMatcher |    1 |      4 | n, post,   UNNAMED84 |                                  |
|          SchemaIndex |    1 |      2 |                 n, n |      {  AUTOSTRING0}; :User(_id) |
+----------------------+------+--------+----------------------+----------------------------------+

Total database accesses: 7

Point 3. Always use labels for positives, meaning for the case above, having a Draft label will force you to execute the following query :
MATCH (n:User {id:1})
WITH n
MATCH (n)-[:POST]->(post:Post)
WHERE NOT post :Draft
RETURN n, collect(post) as posts;

Meaning that Cypher will open each node label headers and do a filter on it.
Point 4. Avoid having the need to match on multiple labels
MATCH (n:User {id:1})
WITH n
MATCH (n)-[:POST]->(post:Post:ActivePost)
RETURN n, collect(post) as posts;

neo4j-sh (?)$ PROFILE MATCH (n:User) WHERE n._id = 'c084e0ca-22b6-35f8-a786-c07891f108fc'
> WITH n
> MATCH (n)-[:WRITTEN]->(post:BlogPost:ActivePost)
> RETURN n, size(collect(post)) as posts;
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| n                                                                                | posts |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Node[118]{_id:"c084e0ca-22b6-35f8-a786-c07891f108fc",login:"joy.wiza",password:"7425b990a544ae26ea764a4473c1863253240128",email:"hayes.shaina@yahoo.com"} | 1     |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row

ColumnFilter(0)
  |
  +Extract
    |
    +ColumnFilter(1)
      |
      +EagerAggregation
        |
        +Filter
          |
          +SimplePatternMatcher
            |
            +SchemaIndex

+----------------------+------+--------+----------------------+---------------------------------------------------------------+
|             Operator | Rows | DbHits |          Identifiers |                                                         Other |
+----------------------+------+--------+----------------------+---------------------------------------------------------------+
|      ColumnFilter(0) |    1 |      0 |                      |                                         keep columns n, posts |
|              Extract |    1 |      0 |                      |                                                         posts |
|      ColumnFilter(1) |    1 |      0 |                      |                              keep columns n,   AGGREGATION139 |
|     EagerAggregation |    1 |      0 |                      |                                                             n |
|               Filter |    1 |      2 |                      | (hasLabel(post:BlogPost(1)) AND hasLabel(post:ActivePost(2))) |
| SimplePatternMatcher |    1 |      8 | n, post,   UNNAMED84 |                                                               |
|          SchemaIndex |    1 |      2 |                 n, n |                                   {  AUTOSTRING0}; :User(_id) |
+----------------------+------+--------+----------------------+---------------------------------------------------------------+

Total database accesses: 12

This will result in the same process for Cypher that on point 3.
Point 5. If possible, avoid the need to match on labels by having well typed named relationships
MATCH (n:User {id:1})
WITH n
MATCH (n)-[:PUBLISHED]->(p)
RETURN n, collect(p) as posts

-
MATCH (n:User {id:1})
WITH n
MATCH (n)-[:DRAFTED]->(post)
RETURN n, collect(post) as posts;

neo4j-sh (?)$ PROFILE MATCH (n:User) WHERE n._id = 'c084e0ca-22b6-35f8-a786-c07891f108fc'
> WITH n
> MATCH (n)-[:DRAFTED]->(post)
> RETURN n, size(collect(post)) as posts;
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| n                                                                                | posts |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Node[118]{_id:"c084e0ca-22b6-35f8-a786-c07891f108fc",login:"joy.wiza",password:"7425b990a544ae26ea764a4473c1863253240128",email:"hayes.shaina@yahoo.com"} | 3     |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row

ColumnFilter(0)
  |
  +Extract
    |
    +ColumnFilter(1)
      |
      +EagerAggregation
        |
        +SimplePatternMatcher
          |
          +SchemaIndex

+----------------------+------+--------+----------------------+----------------------------------+
|             Operator | Rows | DbHits |          Identifiers |                            Other |
+----------------------+------+--------+----------------------+----------------------------------+
|      ColumnFilter(0) |    1 |      0 |                      |            keep columns n, posts |
|              Extract |    1 |      0 |                      |                            posts |
|      ColumnFilter(1) |    1 |      0 |                      | keep columns n,   AGGREGATION119 |
|     EagerAggregation |    1 |      0 |                      |                                n |
| SimplePatternMatcher |    3 |      0 | n, post,   UNNAMED84 |                                  |
|          SchemaIndex |    1 |      2 |                 n, n |      {  AUTOSTRING0}; :User(_id) |
+----------------------+------+--------+----------------------+----------------------------------+

Total database accesses: 2

Will be more performant, because it will use all the power of the graph and just follow the relationships from the node resulting in no more db accesses than matching the user node and thus no filtering on labels.
This was my 0,02€


text:
Q: taskwarrior, delete multiple recurring tasks without request for deleting all pending Returning from holidays, I want to delete all recurrent daily routines not done during absence. For this i use:
task 100-200 delete

Then I confirm the request:
Delete task 100 'Drink: water, 0.7l, before 10:00'? (yes/no/all/quit)

with a (for all)
And then I have to answer for each task (here 101x):
Do you want to delete all pending recurrences of this same task

with n (for no). This part is annoying and I want to get rid of this step. I consider if someone would want to apply delete to all tasks with a, it should be at least be possible to avoid answering if he wants to delete recurrences with n or never (for none).
Do you know some way how to avoid this mess? Or do I'm -- as sometimes -- missing something?
PS: It should be noticed that, if you confirm the discussed 2nd request with y (for yes), the parent/template task is deleted too! What makes this request even dangerous, since in a hurry you might delete a whole recurrent task by accident -- e.g. pay rent.

A: Adding
recurrence.confirmation=no

to your .taskrc should do what you want.
More information from man taskrc:
recurrence.confirmation=prompt
    Controls whether changes to recurring tasks propagates to other child tasks with or with‐
    out confirmation. A value of 'yes' means propagate changes without confirmation. A  value
    of  'no'  means  do  not  propagate  changes  and  don't ask for confirmation. A value of
    'prompt' prompts you every time. Defaults to 'prompt'.


text:
Q: MudBlazor: Mudlink in a MudTable I am trying to customize the link of a MudLink in a MudTable.
This works:
<MudTable Items="@TicketList" >
    <RowTemplate>
        <MudTd DataLabel="Subject">@context.Subject</MudTd>
    </RowTemplate>
</MudTable>

But this does not: (Compiler error: The name 'context' does not exist in the current context.)
<MudTable Items="@TicketList" >
    <RowTemplate>
        <MudTd DataLabel="Subject"><MudLink Href="/ticket/Edit/@context.Id">@context.Subject</MudLink></MudTd>
    </RowTemplate>
</MudTable>

How do I generate the Href in the MudLink based on the row's bound data?

A: I don't see how the code you've posted could result in the error you mentioned. The error you'd get when trying <MudLink Href="/ticket/Edit/@context.Id"> is something like this: "Component attributes do not support complex content (mixed C# and markup)...". Instead, you should do: <MudLink Href="@($"/ticket/Edit/{context.Id}")">.
Here's a demo that works:
<MudTable Items="@this.tickets">
  <HeaderContent>
    <MudTh>Id</MudTh>
    <MudTh>Subject</MudTh>
    <MudTh>Link</MudTh>
  </HeaderContent>
  <RowTemplate>
    <MudTd DataLabel="Id">
      @context.Id
    </MudTd>
    <MudTd DataLabel="Subject">
      @context.Subject
    </MudTd>
    <MudTd DataLabel="Link">
      <MudLink Href="@($"/ticket/Edit/{context.Id}")">@context.Id</MudLink>
    </MudTd>
  </RowTemplate>
</MudTable>

@code {
  private List<Ticket> tickets = new();

  protected override void OnInitialized()
  {
    this.tickets = new List<Ticket>
    {
      new() { Id = "123", Subject = "mu" },
      new() { Id = "456", Subject = "foo" }
    };
  }

  public class Ticket
  {
    public string Id { get; set; }

    public string Subject { get; set; }
  }
}

Try online: https://try.mudblazor.com/snippet/cumGuVltGdrWbDqC


text:
Q: If the prefix "a-" means not, shouldn't "await" or "awaiting" mean, "Not waiting?" If:

*

*Apolitical means "not political"

and

*

*Amuse means...well, it should mean, "not thinking"

then why does await or awaiting not mean "not waiting?"
I read this earlier question (Is there a real difference between wait and await?) but this seems interested in the meaning.
One co-worker passed it off as "another example of why English makes no sense."
I'm hoping for a better explanation or at least some literary historic context.

A: The prefix a- has not one source but several different sources. Webster lists six different prefixes of the kind a-.
prefix 1 - shortening of in/on/at
prefix 2 - as in arise. Webster's explanation of this a- is a bit vague and dubious. My idea: arise might be connected with Latin oriri meaning to rise/arise
prefix 3 - as athirst/akin/anew - Webster: from/of
prefix 4 - as achromatic - Webster: without/not - No mention of the Greek prefix.
prefix 5 - related with Latin ab- meaning coming/moving from a point.
prefix 6 - related with Latin ad- meaning moving to a point and similiar ideas.
Source: Webster's Comprehensive Dictionary of the English Language.
I'm not sure whether Webster has all sources. He doesn't show the relation between English await and German er-warten or English awake and German erwecken/erwachen. The German prefix er- also has several meanings; in erwecken/erwachen it expresses the beginning of an action. Er- in erwarten makes warten transitiv. There are a lot more of these connections.

A: Because the a- prefix came into English from at least two different sources. In ancient Greek, the privative a was used to indicate the negation or absence of the word to which it was attached. It is often used with words with Greek origins, and is treated as "productive," meaning that people still use it to coin new words that negate old ones.
Meanwhile, a- was also used in Middle English as sort of a mild intensifier and flexible preposition, the rules for which are not entirely clear to me. That use of a- is generally confined to words that come from Old or Middle English (await, abed, etc.), is no longer productive, and often feels vaguely archaic.

A: English is a hodgepodge of various linguistic origins.
In this case await means "at wait."  It is similar to "a sea" meaning at sea. It is derived from Middle English (and Old English).  See this
A- as a prefix in other cases means not.  You will note that this usage is frequently pronounced using the long-A sound.  This usage is derived from Greek.
It is only used with words starting with a consonant.  If the word starts with a vowel, an- is used (e.g anionic). See here for reference

A: All general rules are false.
Not all words beginning with "a-" are of the form "not (something)";
otherwise an "atom" would be Dick, Harry, or anybody other than Tom.
Similarly, "pre-" means "before (something)",
but a "preference" is not an earlier "ference".


text:
Q: iOS remote push notifications are queueing up after the first when app is in background When my app is in the background, remote push notifications seem to be getting queued up after I receive the first, then dequeued when the app returns to the foreground.
It doesn't happen all the time; sometimes I can receive more than one, but I haven't figured out what determines that yet.
Here is the code:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"received remote push notification);
    ... process push notification
    completionHandler(UIBackgroundFetchResultNewData);
}

When the app is in the background, what I see happening is:
1. I send a push notification.
2. I see "received remote push notification" in the console.
3. I send another push notification.
4. Nothing happens.
5. I tap my app icon to bring it to the foreground.
6. Once the app returns to the foreground, I see "received remote push notification" in the console.
What I want to happen is I see the console output as soon as I receive the push notification.
Thanks in advance!


text:
Q: Spivak Absolute Value Problem (Prologue 9-v) I'm working on the following problem

Express the following with at least one less pair of absolute value signs
$$|(| \sqrt2 + \sqrt3| - |\sqrt5 - \sqrt7|)|$$

Now I can see that the expression can be written as $|\sqrt2 + \sqrt3 + \sqrt5 - \sqrt7|$ and that satisfies the requirement of the problem (ie I've eliminated at least one pair of absolute value signs), but the solution in the back of the book is $\sqrt2 + \sqrt3 + \sqrt5 - \sqrt7$ without the absolute value sign.
Is there a way to show that $\sqrt2 + \sqrt3 + \sqrt5 > \sqrt7$ ?

A: Note that $\sqrt{2}, \sqrt{3}, \sqrt{5} > 1$ but $\sqrt{7} < 3$.

A: Square both sides. The left is at least $2 + 3 + 5 = 10$ and the right is equal to $7$.
Explicitly:
$$(\sqrt{2} + \sqrt{3} + \sqrt{5})^2 = 2 + 3 + 5 + 2\sqrt{6} +2\sqrt{10} + 2\sqrt{15} > 10$$


text:
Q: How to identify the maximum in list of lists V = [[10,20,30,40],[30,40,50,-50,-70]]
V_max_result = max(V)
V_max_result_index = V.index(max(V))
print(V_max_result,V_max_result_index)

Presently, it is giving output like [30, 40, 50, -50, -70] 1
I wanted it to show something like [[40,3],[50,2]] where 40 is maximum in first list and it is located at 3.

A: V = [[10,20,30,40], [30,40,50,-50,-70]]
print([[max(per_v), per_v.index(max(per_v))] for per_v in V])

Output:

[[40, 3], [50, 2]]

A: While the answer by @atline works, it has to iterate three times over each sublist, once to get the maximum, a second time to get the maximum again and then a third time to find its position in the list.
Instead it is easier to find the maximum of tuples, where each tuple is like (value, index). This is almost what enumerate returns (index, value), just reversed. We can use zip(values, itertools.count()) for that. It works, because tuples sort by first sorting according to the first entry, then the second.
from itertools import count

V = [[10,20,30,40], [30,40,50,-50,-70]]
print([max(zip(per_v, count())) for per_v in V])
# [(40, 3), (50, 2)]

If you insist on the inner tuples being lists as well:
print([list(max(zip(per_v, count()))) for per_v in V])
# [[40, 3], [50, 2]]


text:
Q: What does "screenSize" in Android Manifest do? Hello I have got an Activity, where I have multiple Fragments inside, where AsyncTasks are running. My current problem is, when I change the orientation of device, while AsyncTask is doin stuff, App is crashing. As far as I could read from some threats, the addigin "screenSize" like:
android:configChanges="orientation|screenSize|keyboardHidden">

should solve that problem. But now, my app is crashing every time I change the orientation - what does screenSize exactly do, and why is my app crashing while changing its orientation?
edit: is there any special thing I have to give attention while using screenSize concerning my fragments - so the app does not crash?
thank u

A: See this link for your error: https://gist.github.com/daichan4649/2480065
If you don't want to re-create the fragment on OnCreate, you should use setRetainInstance(true) as described in the link.


text:
Q: restrict fields according to user permissions in django I'm building an API using Django rest framework. I have to restrict access to fields (both read or write access) according to the kind of user logged in. How do I go about it ? I'm considering writing separate serializers for different user roles (I will get an access token with every request using which I can authenticate the user, the next step will get me the user's roles, according to which I want to restrict what fields the user can see/edit).

A: In case you want to give certain users model level permissions to conduct certain actions you can do this with custom permissions like so:
class T21Turma(models.Model):
    class Meta:
        permissions = (("can_view_boletim", "Can view boletim"),
                       ("can_view_mensalidades", "Can view mensalidades"),)

Then you can either make several serializers and swap them out in the views based on the permissions, or you can modify the fields of the serializer dynamically.


text:
Q: Mod_evasive No logs, No IP blocking, No errors - What's going on? I'm experiencing an anomaly on my Ubuntu 16.04 Machine. I installed LAMP, ufw, fail2ban e now as a DOS protection I installed mod_evasive.
Mod_evasive doesn't seem to block anything, doesn't log anything and the only log I see in var/log/apache2/error.logs when I reload a page fast enough to trigger it is:
[evasive20:error] [pid 17849] [client *..***.179:9189] client denied by server configuration:..

Beside that NOTHING.
I went through all the steps, created a log directory, give permissions, reinstalled, tried all sort of things but the problem doesn't seem to be fixed AT ALL!
This is my current configuration:
<IfModule mod_evasive20.c>
DOSHashTableSize    3097
DOSPageCount        1
DOSSiteCount        5
DOSPageInterval     1
DOSSiteInterval     1
DOSBlockingPeriod   15

#DOSEmailNotify      you@yourdomain.com
#DOSSystemCommand    "su - someuser -c '/sbin/... %s ...'"
DOSLogDir           "/var/log/apache2/evasive.log"
</IfModule>

Any idea?
EDIT:
I'm now able to see the logs-> IT basically logs files named DOS-203.33.**.* for each presumed attack.
But still it doesn't block anything! From my understanding it has to block the ip address at the Apache level but it doesnt..

A: I believe you are missing the firewall-part.
if you are using iptables you should set the following DOSSystemCommand:
"sudo /root/scripts/ban_ip.sh %s":

be sure to add your apache user to sudoers and allow access to the script and 'iptables' and 'at' command.
Script content:
#!/bin/sh

IP=$1
IPTABLES=/sbin/iptables

$IPTABLES -A banned -s $IP -p TCP --dport 80 -j DROP

echo "$IPTABLES -D banned -s $IP -p TCP --dport 80 -j DROP" | at now + 2 hours

sudoers:
www-data ALL=(ALL) NOPASSWD: /sbin/iptables *, /usr/bin/at *, /root/scripts/ban_ip.sh

cheers!


text:
Q: javascript using function passed parmeter in a varable after function I'm still learning JavaScript so please forgive if this is a rookie question. Is it possible to use the value passed as a function parameter as a variable later in the script? This does not work for me even if I declare the variable in the global scope:
var parm;

function a(parm) {
  console.log(parm); //"Hello"
}

a("Hello");
console.log(parm); // undefined

This works of course...
function a(parm) {
  console.log(parm); //"Hello"
}

parm = "Hello"
a(parm);
console.log(parm); // "Hello"

I was just wondering if there was a way to assign a value to a variable from a function parameter directly.

A: There are two ways :
1st Way :
    var param;

    function a(local_param){
     param = local_param;
    }

    a("Hello");

    console.log(param); //hello

2nd Way
var parm;

function a(local_param) {
  console.log(local_param); //"Hello"
  return local_param;
}

parm = a("Hello");
console.log(parm); //Hello

A: So, here's the thing, you are atributing the value to parm, on the function call. So, the value is valid only inside the function. If you want to use the value other times, you need to define a value to parm on the declaring variable, like this: parm = 'hello'. Otherwise, the value is only valid inside the function.
Other solution, is changing the value inside the function, so that it returns the value you want. That way the variable is overwritten inside the function!
Any questions, just ask!


text:
Q: .htaccess is ignored on Apache I've made a website in PHP, tested it locally and it works fine. Now I pushed it to my actual webserver and now I'm having trouble, because my .htaccess - file should redirect all calls, but it's getting ignored.
This is my .htaccess - file
AddDefaultCharset UTF-8

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
    RewriteRule ^(controllers/|core/|models/|views/) - [F,L,NC]
</IfModule>

I've already searched for a solution and came up with running these commands:
a2enmod rewrite
a2enmod expires
a2ensite default-ssl

After each command i restarted the server.
The last command in the list above gives me an error:
apache2: Syntax error on line 224 of /etc/apache2/apache2.conf: Syntax error on line 166 of /etc/apache2/sites-enabled/default-ssl.conf: Expected </VirtualHost> but saw </IfModule>
Action 'configtest' failed.

Does someone have a solution for this?

A: Look in your /etc/apache2/sites-enabled/default-ssl.conf file. Does it have one <VirtualHost> opening entry without the corresponding </VirtualHost> closing entry?


text:
Q: Switch issue - only one option visible I want to use switch in an android application. I tried it but main issue is

*

*if i have selected ON , it won't display off text.

*if i have selected OFF , it won't display on text.

Off text is not displayed but we can select OFF by clicking in black area of switch.
Code
<Switch android:id="@+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="26dp"
android:height="50dp"
android:text="ON OFF"
android:textSize="20sp"
android:switchMinWidth="50sp"
android:switchPadding="50sp"/>

On State

Off state

How i can display both text at the same time?
Can i change text of switch for both state ON/OFF?
Any Help would be appreciated.
Thanks in advance.

A: Here is my solution, which creates a custom widget to mimic the Switch control. I'm using Xamarin, but this code can easily be translated to Java.
SwitchImageView.cs:
public class SwitchImageView : RelativeLayout {
        private View view;

        private bool isChecked;
        private int imageResourceIdOn = Resource.Drawable.switch_on;
        private int imageResourceIdOff = Resource.Drawable.switch_off;

        public SwitchImageView(Context context): base(context) {
            Init ();
        }

        public SwitchImageView(Context context, IAttributeSet attrs) : base(context, attrs) {
            Init ();
        }

        public SwitchImageView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) {
            Init ();
        }

        private void Init () {
            var layoutInflater = (LayoutInflater)ApplicationContext.Activity.GetSystemService (Context.LayoutInflaterService);
            layoutInflater.Inflate (RPR.Mobile.Resource.Layout.SwitchImageView, this, true);

            this.Click += (object sender, EventArgs e) => {
                Checked = !Checked;
            };
        }

        public int ImageResourceIdOn {
            get {
                return imageResourceIdOn;
            }
            set {
                imageResourceIdOn = value;
                if (isChecked) {
                    this.SetBackgroundResource (value);
                }
            }
        }

        public int ImageResourceIdOff {
            get {
                return imageResourceIdOff;
            }
            set {
                imageResourceIdOff = value;
                if (!isChecked) {
                    this.SetBackgroundResource (value);
                }
            }
        }

        public string TextOn {
            get {
                return this.FindViewById <TextView> (Resource.Id.switch_on_text).Text;
            }
            set {
                this.FindViewById <TextView> (Resource.Id.switch_on_text).Text = value;
            }
        }

        public string TextOff {
            get {
                return this.FindViewById <TextView> (Resource.Id.switch_off_text).Text;
            }
            set {
                this.FindViewById <TextView> (Resource.Id.switch_off_text).Text = value;
            }
        }

        public bool Checked {
            get {
                return isChecked;
            }
            set {
                isChecked = value;
                this.SetBackgroundResource (value ? ImageResourceIdOn : ImageResourceIdOff);
                this.FindViewById <TextView> (Resource.Id.switch_on_text).SetTextColor (value ? Color.White : Color.Black);
                this.FindViewById <TextView> (Resource.Id.switch_off_text).SetTextColor (value ? Color.Black : Color.White);
                if (CheckedChange != null) {
                    CheckedChange (this, value);
                }
            }
        }

        public event EventHandler<bool> CheckedChange;
    }

SwitchImageView.axml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/switch_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <View
        android:id="@+id/strut"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:visibility="invisible"
        android:layout_centerInParent="true" />
    <TextView
        android:id="@+id/switch_off_text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textColor="@color/black"
        android:text="On"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:paddingLeft="10dp"
        android:paddingTop="3dp" />
    <TextView
        android:id="@+id/switch_on_text"
        android:layout_toRightOf="@+id/strut"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textColor="@color/white"
        android:text="Off"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:paddingRight="5dp"
        android:paddingLeft="10dp"
        android:paddingTop="3dp" />
</RelativeLayout>

A: There is one made by 2 Standard buttons and a LinearLayout. There are bunch of xml files to import but it works perfect on all versions and very easy to use. Check the following Github Page
Preview
Custom Switch With 2 Buttons
usage

*

*Copy XML files under res/drawable to your project's res/drawable folder.

*Copy LinearLayout from layout.xml to your layout file.

*Copy values from values/colors.xml and values/dimens to your own files.

*Initilize the switch with following code

SekizbitSwitch mySwitch = new SekizbitSwitch(findViewById(R.id.sekizbit_switch));
        mySwitch.setOnChangeListener(new SekizbitSwitch.OnSelectedChangeListener() {
            @Override
            public void OnSelectedChange(SekizbitSwitch sender) {
                if(sender.getCheckedIndex() ==0 )
                {
                    System.out.println("Left Button Selected");
                }
                else if(sender.getCheckedIndex() ==1 )
                {
                    System.out.println("Right Button Selected");
                }
            }
        });


text:
Q: Maven war plugin: archiveClasses without archiving resources There is an archiveClasses option in maven-war-plugin, which packages all the classes in a single .jar, and then creates .war file with that jar in lib/ folder.
I need to do the same, but leave resource files in classes directory, so that they are still accessible from the classpath but easy to modify.
What is the easiest way to do that?

A: Maybe you can try to configure your resources folder as a WebResource in the
plugin configuration.
<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <archiveClasses>true</archiveClasses>
        <webResources>
            <resource>
                <directory>src/main/resources</directory>
                <targetPath>WEB-INF/classes</targetPath>
                <filtering>true</filtering>
            </resource>
        </webResources>
    </configuration>
</plugin>

A:
One line answer :  There are no options provided in maven-war-plugin to exclude the resources from the jar created using archiveClasses flag.

The possible and easiest workaround for this problem is to move the files present under src/main/java/resources directory to src/main/java/webapp/WEB-INF/classes directory.

A: You should just be able to specify where those resources are.  It usually looks in src/main/resources for resources, but if you need them in the java source tree you could try:
<resources>
    <resource>
        <directory>${basedir}/src/main/java</directory>
        <filtering>true</filtering>
        <includes>
            <include>*.xml</include>
        </includes>
    </resource>
</resources>

A: you can do like this to solve the problem:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <warName>${project.war.name}</warName>
        <warSourceExcludes>**/*.class</warSourceExcludes>
        <archiveClasses>true</archiveClasses>
    </configuration>
</plugin>


text:
Q: Vert.x Json.decodeValue list Does anyone know how to decode a json string to List<Foo> in vert.x?
You can convert a string to object easily with Json.decodeValue(data, Foo.class); but I can't seem to figure out how to do so in case of lists.
So far I've gotten the data out with Json.decodeValue(data, List.class); but you can't really do anything with the result apart from print it out.

A: You'll have to declare a container object, but otherwise, it's quite simple:
// This is your Foo
public class MyObj {
    public String key;

    // Just for clarity
    @Override
    public String toString() {
        return "MyObj{" +
                "key='" + this.key + '\'' +
                '}';
    }
}

// This is the container
public class MyArray {
   // Property is mandatory in this case
   @JsonProperty("objs")
   List<MyObj> objs;
}

And now the parsing
public static void main(final String[] args) {

    // Your input is a JSON array, not a JSON object
    final String input = "[{\"key\":\"a\"}, {\"key\":\"b\"}, {\"key\":\"c\"}]";

    // We format it to be a JSON object, so we can parse it
    final MyArray res = Json.decodeValue(String.format("{\"objs\":%s}", input), MyArray.class);

    // Get your List out
    System.out.println(res.objs);
}

A: Try this
List<Foo> fooList = Json.decodeValue(bodyAsString, new TypeReference<List<Foo>>(){});
TypeReference is Jackson reference for your information

A: The Json class use Jackson to decode the string.
I recommend you to use a Foo[] instead of a List. If you really need a List, you can easily create one "Arrays.asList(arr)".
Or you can use one of the examples on this site: http://www.baeldung.com/jackson-collection-array


text:
Q: Is NodeList an array or a list or something else? I'm writing a presentation on java performance, and I'm trying to determine if this is a bad practice.  Im a c++ guy, so I don't know everything about java just yet.  I don't have the source code for item() and I needed a quick answer!
Is this bad for performance:
NodeList elems;  // public abstract interface org.w3c.dom.NodeList
for (int i = 0; i < elems.getLength(); i++) {
  elem = elems.item(i);
  if (elem.getNodeType() == Node.ELEMENT_NODE) {
    // do something with a node
  }
}

My first concern is NodeList might be implemented with a linked list in which case item(i) would be a disaster.
Any other thoughts?

A: NodeList is an Interface, without knowing which implementation you are/will be using, its not possible to say how it is implemented.
The Interface looks something like this:
interface NodeList {
  int getLength();
  Node item(int index);
}

Docs say:

The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.

A: It depends on the implementation. For instance OpenJDK provides a linked list implementation.
public Node item(int index) {
     if (index < 0) {
         return null;
     }

     Node child = getFirstChild();
     while (child != null && index-- > 0) {
         child = child.getNextSibling();
     }
     return child;
 }

More precisely, Node is an interface. Unlike the List interface, its documentation makes no guarantees on performance. The above implementation is IIOMetadataNode. This class again makes no performance guarantees in its documentation, but the source is above and answers the question.
There are many implementations:
com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl
com.sun.org.apache.xml.internal.dtm.ref.DeepNodeListImpl
com.sun.org.apache.xml.internal.security.utils.HelperNodeList
// ...

That may make other performance guarantees. You should try to determine the implementing class for the NodeList you are dealing with and inspect its source code.

A: The WC3 standard stipulates the underlying data structure for a NodeList, so whether it's an array or linked list (or both) would be up to the implementation of the DOM. However, the NodeList interface only defines "getLength()" and "item(i)", so the code you wrote is just about the only way to accomplish your task regardless of performance.

A: According to the Java Doc (https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NodeList.html)
A nodeList is an ordered collection of nodes, thus I would assume that it is a list of sorts. If memory serves me right, an ArrayList uses the logic behind regular arrays under the hood. The reason I suspect it is a list is mainly due to its name "nodeLIST."
As for item(index), it will either return the item at the index or it will return null. Again this comes from the API. Hope this helps, I haven't really used nodeLists much.


text:
Q: Detect If Current Record is Deleted on Access Bound Form If user #1 deletes a record in our Access 2007 database (SQL Server ODBC Linked Tables), other users will likely show #Deleted# in that record (on Datasheet View form). On some occasions this can cause problems because I have code that runs on the Form's current event and simply assumes that a valid record (or new record) exists.
Is there any reliable way to detect if the current record has been deleted? I'd like to wrap it in a function like this:
Public Function IsRecordDeleted(ByRef r As DAO.Recordset)
   'what goes here?
End Function

I did find a RecordStatus property in the DAO reference at MSDN but that property appears to only be valid if the RecordSet is configured for batch updating. When I try to check it's value I get: Run-time error 3251 - Operation is not supported for this type of object.
I actually posted on another forum about this same problem a year or two ago. The recommendations given do not work:

*

*DCount()

*Bookmark and NoMatch of recordset

*Checking for #Deleted in the PK or FK field

A: To me, this looks more like a general application design oversight than a simple problem that has a simple work-around.
If you make assumptions on the availability of records in important places, then you must take into account the possibility of deleted records as a major (and valid) state of your data.
It's possible -but I think unlikely- that you will find a workaround, but I think you should take a closer look at your overall design itself.
Some ways to tackle the issue, that may or may not be useful in your case, depending on how your data is contained and accessed by users:

*

*Simply do not rely on the existence of records if you can't be sure they will be there.
Basically, rework your assumptions and modify your existing code to avoid relying on the mandatory existence of records.

*Separation of responsibilities
Don't allow different users to have the same create/edit/delete rights to the same data. For instance, a Purchase Orders should belong to the user who created it. Don't allow other users to delete that order or its items separately.

*Don't actually delete the entity, just allow the user to mark it as 'Cancelled' or 'Obsolete' and keep it in the database for historical reasons (or purge them later).

*Alternatively, don't actually delete records, but add a hidden boolean field to mark them as 'deleted' when the user wants to remove them. You can then do some clean-up, say every night, and actually remove the marked records.
Of course, you will have to exclude these 'deleted' records from your queries and forms, etc, but data integrity will be preserved.

*Make reports and lists of records read-only so users can't just delete them anywhere. For instance, if users can view Purchase Order items, don't allow them to remove that data except when they actually open the Purchase order details form.

*Cache records locally so that if they disappear from the backend database, they would still be shown to the user viewing them until they refresh the list.
This is often useful for read-only reports: load the result of a query into a local table and bind that table instead of the query using live data.
The data being viewed may be slightly stale because it won't update in real-time (since it's cached locally) but for reports, it's generally ok (just provide a 'Refresh' button on your form to allow users to force the refresh).

*Experiment with the various locking options (see database options and form record locking) to disallow deletion of records if someone else is accessing them.

*Manage your own locking scheme.
As a last resort, you could record in a 'LockingStatus' table the ID and records that are currently being viewed or edited by someone else. For instance:
Table: LockStatus
Field: LockNature:   Whether the record is being Edited or Viewed
Field: LockedTable:  Name of the table of the record being locked
Field: LockedRecord: ID of the record being locked
Field: User:         Name of the user holding the lock
Field: LockTime:     DateTime of the lock creation, so you can detect
                     and remove stale locks

When a user is viewing or editing a record, first check if there is an existing entry in the table for that record. If there is one, then tell the user they can't perform the operation because someone else is viewing the data. If there is no existing entry, add one, allow edits, and remove the record once the edit is complete.
This is fraught with complexities since you need to track when a user is moving to another record so you can unlock the previous one, and if you're not careful, you may end-up with lots of stale locks, but it's been done before.

*If you still really want to circumvent the deleted record issue, have a look where, in your VBA code, the Error 3167 "Record Deleted" occurs when you delete a record from another location.
Once you know where it occurs in your code, trap that error using On Error 3167 Goto YourErrHandler to handle that particular error gracefully (that will really depend on how your forms are designed and how you use your data).

*Another alternative is to use a global error handler for access.
I know only of vbWatchdog. It's not free but it works extremely well and is very simple to integrate into an application.
This add-in integrates in your application and doesn't need to be installed separately for each user. Once setup, your application will be able to catch all errors at a high-level. So you will be able to catch 'Record Deleted' errors and deal with them in one place.

A: I ran into the same thing via code in the Form_Current event, and ended up here.
Error handling is the best (and only?) way to go here.  For my own purposes, I was just running a few simple control updates in the current event, and so I wrote the error handler to recover from the errors I was getting
Private Sub Form_Current()
    On Error GoTo handler

    'do intended things here, e.g. attempt to access the value
    'of a control even though the record may be deleted

    Exit Sub

  handler:
    If Err.Number = 438 Or Err.Number = 13 Then
        'type mismatch, probably due to deleted record, skip it
        Resume Next
    ElseIf Err.Number = 3167 Then
        'record is deleted, skip it
        Resume Next
    Else
        Err.Raise Err.Number, Err.Source, Err.Description
    End If
End Sub

I was not reliably getting 3167 (record deleted), but when attempting to access value properties I seemed to be getting just the 3 errors trapped above.
If your current event is longer, or if it's risky to run over code like this, you could use a similar technique but deliberately provoke the error at the beginning the method (dummyvalue = SomeBoundControl.Value should do the trick) and then change the "Resume Next"s in the error handler to "Exit Sub".

A: You could check a field which is not blank for sure if the record still exists.
I use a date updated or date created field which is autofilled by the default value =Now() once the form is opened for the first time.
Since its value seems to change to an empty string if the record has been deleted, I can trigger
If Me.DateUpdated = "" Then

on the form itself (e.g. to skip actions in the closing procedure). This check might also work from other forms.


text:
Q: Spring boot external application.properties I am developing a spring boot application
I want to override some properties in src/main/resources/application.properties with an external file (e.g. /etc/projectName/application.properties).
I tried several methods:

*

*@PropertySource("file:/etc/projectName/application.properties") as annotation at ApplicationConfig.java

*spring.config.location=/etc/projectName/application.properties in my application.properties in resources
I tested it with spring.port. The first method only added properties but didn't override them.

A: I had the same requirement like yours( war package instead of a fat jar)  and I manged to externalize the configuration file:
In my main class I made this configuration:
@SpringBootApplication
@PropertySource("file:D:\\Projets\\XXXXX\\Config\\application.properties")
public class WyApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(WyApplication.class, args);
    }

}

Hope this will help you.
Good luck.

A: I always use --spring.config.location= in the command line as specified in the documentation, and you can put various files in this, one with default values and another with the overridden ones.
Edit:
Alternatively, you could also use something like :
@PropertySources({
    @PropertySource("classpath:default.properties")
    , @PropertySource(value = "file:${external.config}", ignoreResourceNotFound = true)
})

and specify a external.config in your application.properties.
This would provide a default path for overridding config, that is still overriddable itself by specifying a --external.config in the command line.
I use this with ${external.config} being defined as a system env variable, but it should work with a application.properties variable too.

A: Notes
1) Tomcat allows you to define context parameters
2) Spring Boot will read the properties defined in Tomcat context parameters as if you are defining them as -Dsomething=some_value
Options
Option 1: Hence a possible way is for you to define spring.config.location at the Tomcat context paramter:
<Context>
    <Parameter name="spring.config.location" value="/path/to/application.properties" />
</Context>

Option 2: define a system property at the Tomcat's setenv.sh file
Dspring.config.location=/path/to/application.properties

Option 3: define an environment variable: SPRING_CONFIG_LOCATION

A: If you do not want to use any solution from above, you could do the following in the start of your main(String args[]) method (before the usage of SpringApplication.run(MyClass.class, args):
//Specifies a custom location for application.properties file.
System.setProperty("spring.config.location", "target/config/application.properties");

A: Note: The following solution will replace the old application.properties entirely
You can place your application.properties in one of the following locations:

*

*Under /config sub-directory of the current directory

*The current directory

*A classpath /config package

*The classpath root

And then exclude the default one under resources directory, like:
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <excludes>
                <exclude>**/application.properties</exclude>
            </excludes>
        </resource>
    </resources>
</build>

Find more details in this link

A: Based on @JR Utily response this "format" work for me when use email config and multiple properties (I tried to use a PropertySourcesPlaceholderConfigurer Bean but for any reason don't take the email config):
@SpringBootApplication
@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource(value = "file:/path/to/config1.properties", ignoreResourceNotFound = true),
    @PropertySource(value = "file:/path/to/config2.properties", ignoreResourceNotFound = true),
    @PropertySource(value = "file:/path/to/config3.properties", ignoreResourceNotFound = true)
})
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

A: Yes we can add application.properties file from external folder. The simplest way is
@SpringBootApplication
public class ExternalAppPropertiesTest{

    public static void main(String[] args) {
        System.setProperties("spring.config.location","D:\\yourfoldername where application.properties added");
        SpringApplication.run(ExternalAppPropertiesTest.class, args);
    }
}

N.B. - In case of externally application.properties access please don't use @PropertySources annotation and file path. It will not access your logging properties e.g. logging.file.name=yourlogfilename.log
Here is one more suggestion, for code maintenance you can put your applcation.properties by renaming the file name in your src folder of spring boot application and maintain the changes which is done in external file.


text:
Q: Reduction formula for $\int\frac{dx}{(ax^2+b)^n}$ I recently stumbled upon the following reduction formula on the internet which I am so far unable to prove.
$$I_n=\int\frac{\mathrm{d}x}{(ax^2+b)^n}\\I_n=\frac{x}{2b(n-1)(ax^2+b)^{n-1}}+\frac{2n-3}{2b(n-1)}I_{n-1}$$
I tried the substitution $x=\sqrt{\frac ba}t$, and it gave me
$$I_n=\frac{b^{1/2-n}}{a^{1/2}}\int\frac{\mathrm{d}t}{(t^2+1)^n}$$
To which I applied $t=\tan u$:
$$I_n=\frac{b^{1/2-n}}{a^{1/2}}\int\cot^{n-1}u\ \mathrm{d}u$$
I then used the $\cot^nu$ reduction formula to find
$$I_n=\frac{-b^{1/2-n}}{a^{1/2}}\bigg(\frac{\cot^{n-2}u}{n-2}+\int\cot^{n-3}u\ \mathrm{d}u\bigg)$$
$$I_n=\frac{-b^{1/2-n}\cot^{n-2}u}{a^{1/2}(n-2)}-b^2I_{n-2}$$
Which is a reduction formula, but not the reduction formula.
Could someone provide a derivation of the reduction formula? Thanks.

A: Hint The appearance of the term in $\frac{x}{(a x^2 + b)^{n - 1}}$ suggests applying integration by parts with $dv = dx$ and thus $u = (a x^2 + b)^{-n}$. Renaming $n$ to $m$ we get
$$I_m = u v - \int v \,du = \frac{x}{(a x^2 + b)^m} + 2 m \int \frac{a x^2 \,dx}{(a x^2 + b)^{m + 1}} .$$
Now, the integral on the right can be rewritten as a linear combination $p I_{m + 1} + qI_m$, so we can solve for $I_{m + 1}$ in terms of $I_m$ and replace $m$ with $n - 1$.

A: To prove that the integral $$I_n=\int\frac{\mathrm{d}x}{(ax^2+b)^n} $$
has a reduction formula
$$I_n=\frac{x}{2b(n-1)(ax^2+b)^{n-1}}+\frac{2n-3}{2b(n-1)}I_{n-1},$$
which is equivalent to $$
2 b(n-1) J_{n} -(2 n-3) J_{n-1} =\frac{x}{\left(a x^{2}+b\right)^{n-1}}
\begin{aligned}
\Leftrightarrow & \frac{d}{d x}\left[\frac{x}{\left(a x^{2}+b\right)^{n-1}}\right] =\frac{b-(2 n-3) a x^{2}}{\left(a x^{2}+b\right) ^n}
\end{aligned}
$$
In fact, using quotient rule prove that
$$
\begin{aligned}
& \frac{d}{d x}\left[\frac{x}{\left(a x^{2}+b\right)^{n-1}}\right] \\
=& \frac{\left(a x^{2}+b\right)^{n-1}-x(n-1)\left(a x^{2}+b\right)^{n-2}(2 a x)}{\left(a x^{2}+b\right)^{2 n-2}} \\
=& \frac{\left(a x^{2}+b\right)-x(n-1)(2 a x)}{\left(a x^{2}+b\right)^{n}} \\
=& \frac{b-(2 n-3) a x^{2}}{\left(a x^{2}+b\right)^{n}},
\end{aligned}
$$
which complete the proof.


text:
Q: Quais as vantagens e desvantagens de usar paginação e scroll infinito em sites? O que o usuário ganha ou perde quando se escolhe um deles? Consequentemente o que proprietário do site tem algum ganho em função da melhor experiência do usuário.
Quando optar por cada um? Existe um tipo de site ou aplicação web que se adéqua melhor?
Entre as desvantagens tem algo que pode dar errado?
Eu sei que o ideal é conduzir estudos com o público alvo. Mas queria saber o que já se concluiu de forma geral sobre o tema.
Quanto mais referências puder fornecer, melhor. Não quero saber o que você gosta ou usa. Procuro informações objetivas de quem entende realmente do assunto.

A: Hoje o scroll é uma tendência cada vez maior. Rolar o site não é mais um problema como antigamente - as pessoas estão mais habituadas.
A possibilidade de deixar todos os posts conforme a demanda é uma solução interessante para os usuários, e acredito que sem muita carga na performance. Como o script é acionado apenas no fim da rolagem, teria o mesmo efeito de uma paginação, porém, sem mudar de página. Com isso, o tempo que a pessoa fica na página é maior - você pode se aproveitar disso, para monetizar ou fazer qualquer outra ação desejada.
Não consigo ver nenhum contra a não ser performance, que - dependendo do servidor - pode ter o efeito visual contrário. Se o loading não termina (ou demora muito), o usuário vai ter sérios problemas em continuar navegando.

A:
O que o usuário ganha ou perde quando se escolhe um deles?
  Consequentemente o que proprietário do site tem algum ganho em função
  da melhor experiência do usuário.

Do ponto de vista do usuário: na paginação ele tem mais controle (ou, ao menos, sensação de controle) sobre o conteúdo, enquanto que na rolagem infinita o usuário tem menos esforço.
Imagine um cenário de um site tipo o Flickr, que contém apenas imagens, e em que o usuário está fazendo uma busca por uma imagem de algo desejado. Em certo momento ele encontra uma de que gosta, mas decide continuar procurando um pouco mais. Na paginação ele tem facilidade de memorizar onde está o item que gostou. Pode ser pela posição de uma barra de rolagem, pode ser pelo número da página, pode até mesmo ser pela posição relativa (número de cliques ou pagedowns dados). Isso já não é tão fácil na rolagem infinita.
Imagine que nesse mesmo cenário, as fotos exibem informações quando o mouse está posicionado sobre elas, que são importantes na decisão do usuário pelo item procurado. Nesse caso, ter de mover o mouse ou mesmo a mão do mouse para o teclado para controlar a rolagem gera mais esforço. Pode parecer pouco, mas dependendo do contexto (se for um profissional que passa o dia usando esse site) pode ser bastante cansativo ou reduzir a produtividade. Nesse sentido a rolagem infinita pode ajudar a reduzir o esforço.
Do ponto de vista do proprietário do site: na paginação ele dá o controle para o usuário, na rolagem infinita o proprietário conduz a experiência. O usuário deve ser sempre o foco de atenção ao se projetar a interação de qualquer produto, mas ainda assim essa decisão pode decorrer da experiência intencionada. Citaram em outras respostas a ideia de aumentar o tempo que a pessoa passa no site, por exemplo. A rolagem infinita gera essa sensação de que há muito mais por se ver, e por isso estimula o usuário permanecer mais tempo. Além disso, se por qualquer motivo não se deseja estimular o usuário a "voltar" (isto é, se deseja dar preferência para que ele veja conteúdo novo ao invés de conteúdo já visto), a rolagem infinita pode ser mais apropriada. Pode ser o caso de sites ou aplicações de notícias, como alternativa ao famoso serviço do tipo Push.
Uma solução híbrida é difícil porque dificulta a percepção de estado do usuário (mesmo que você use uma barra de rolagem, ela vai mudar de proporção conforme mais dados são exibidos) e requer muito mais memória do sistema porque essencialmente você vai ter que manter tudo em memória.

Quando optar por cada um? Existe um tipo de site ou aplicação web que
  se adéqua melhor?

No sentido do que foi discutido, a rolagem infinita talvez seja mais apropriada para sites em que o conteúdo é fugaz, existe em enorme quantidade, ou é gerado por diversas fontes distintas. Nas redes sociais, por exemplo, o conteúdo é produzido por outros usuários, comumente contém imagens, vídeos curtos ou links que são abertos ou "processados" imediatamente (o usuário lê, ri, se ofende ou curte, e passa para o próximo; links são abertos e lidos imediatamente ou guardados em outra aba, independente da paginação).
Caso contrário, provavelmente é melhor utilizar a paginação mesmo. :)

Entre as desvantagens tem algo que pode dar errado?

Na rolagem infinita, do ponto de vista técnico tem a possibilidade do sistema simplesmente não conseguir exibir tudo o que o usuário quer ver. Isso pode ser contornado ao descartar os itens muito antigos lá do começo da rolagem, e é o que geralmente se faz ao meu ver. Na paginação, o problema potencial é desestimular o usuário. Se o resultado de uma busca for muito grande, ele pode não se interessar por usar. O Google é uma situação atípica porque apesar de ele mostrar um bestilhão de resultados o usuário sabe que os primeiros são os mais relevantes (por convenção e por costume, já que essa informação não é necessariamente explícita - isto é, não há um número com a relevância na frente de cada resposta).

Eu sei que o ideal é conduzir estudos com o público alvo. Mas queria
  saber o que já se concluiu de forma geral sobre o tema.

Essa é uma boa pergunta. Mas é difícil ter uma única resposta pra ela, porque depende do domínio de problema. Como vc mesmo aponta, o ideal é conduzir estudos com o público alvo, mas esse público muda dependendo da área. Na área de e-commerce, por exemplo, parece ser condizente com o que eu apontei anteriormente. Há esse estudo muito bem feito e que inclui também uma distinção entre a paginação e o uso de botões "Carregar Mais" (carregamento em partes). O resumo é dado lá no texto mesmo, e é o seguinte (em tradução livre):
"Paginação ainda é a forma mais popular de carregar novos itens em um website porque já existe por padrão em quase todas as plataformas de e-commerce. Entretanto, nossos testes de usabilidade indicaram que botões "Carregar Mais" combinados com lazy-loading (carregamento preguiçoso) tendem a ser uma implementação superior, resultando em uma experiência mais contínua (sem costuras). Nós descobrimos que a rolagem infinita pode ser bastante prejudicial à usabilidade — em particular, na busca por resultados e em dispositivos móveis. Ainda assim, isso não é preto e branco, porque o desempenho de cada método varia de acordo com o contexto da página."

A: O que é Scroll Infinito?
Scroll Inifino é uma forma de ter uma página infinita (se você possuir dados para isso, claro). Desta forma, à medida que o usuário chega ao final da página, novos registros serão adicionados automaticamente.
Vantagens

*

*Carrega o conteúdo definido sem necessitar de clicks do usuário;

*Não requer reajustes visuais, sendo o mesmo padrão de layout.

*O usuário não precisa entender do sistema para saber utilizar o recurso, basta ir ao final da página;

*Excelente experiência para dispositivos móveis;

*"prisão" do usuário no site.

Desvantagens

*

*Rodapé do site quase não será visto;

*Sem filtros para buscas, ou seja, caso queira salvar aquele "estado", poderá ter problemas;

*Sensação de "perda de controle" por parte do usuário;

*Possíveis problemas de performance por carregar muito conteúdo;

Quando utilizar?
Não existe uma regra para isso. Como você mesmo disse, a melhor forma seria realizar um estudo com o público alvo para definir o melhor cenário.
Dito isto, existem cenários onde o Scroll Infinito é mais utilizado, como em redes sociais, dando assim uma certa "graça" ao navegar pelo Oceano de Informações gerado pelos usuários em uma rede social.
Também é comum ser utilizado para lista de imagens, pois o padrão das informações dá uma sensação de conforto ao usuário quando ele recebe mais informações.
O próprio Google possui duas formas de paginações, o scroll infinito para pesquisas de imagens e a paginação normal para pesquisas Web.
Segundo relatos o mesmo estaria pensando em alterar estas pesquisas para scroll inifito, mas não posso afirmar a veracidade da informação.
E sobre SEO?
O Google afirma que o scroll infinito pode ser utilizado pelo GoogleBot. Porém, deve ser levado alguns fatores na implementação. A lista de recomendações você pode ver no webmastes.googleblog.
Conclusão Pessoal
Eu particularmente acho elegante o uso de scroll infinito, mas em certas ocasiões.
Em redes sociais, lugares onde a paginação não é significante para mim ou para aplicativos mobiles, eu prefiro utilizar algo com o scroll infinito, pois me apresenta uma sensação melhor de usabilidade.
já em tabelas, notícias, blogs, sites institucionais, ou lugares com informações que contenham realmente leituras, eu prefiro ter o controle de conclusão, ou ao menos pensar que tenho esse controle.
Referências:
Bom, eu não sou ninguém para poder falar essas coisas, então abaixo eu listarei algumas referências que me levaram à esta conclusão.

*

*Infinite Scrolling: Let's Get To The Bottom Of This

*Complexities of an Infinite Scroller - Google Developers

*Infinite Scrolling, Pagination Or "Load More" Buttons? Usability Findings In eCommerce

*Infinite Scrolling: Is It Good or Bad for Your Website?

*Pavination Vs. Infinite Scroll in Datagrids

*Scroll-able website vs infinite scroll website

A:
Em dispositivos móveis (celulares e tablets)

O ruim da paginação em dispositivos móveis é ter que clicar em botões. Como tais dispositivos são mais baseados em toque e "arrasto do dedo sobre a tela", o scroll infinito torna a navegação mais confortável e agradável (eu diria até mais lúdica).

Como alguns dispositivos móveis podem variar no tamanho de tela — uns maiores e outros menores —, o clique em botões pode ser uma tarefa cansativa e chata, pois além do usuário ter que "mirar" o dedo sobre o botão, quando o tamanho da tela for muito baixo, há risco de errar o toque. Além do que é muito mais confortável arrastar o dedo sem se preocupar em que posição específica da tela isso é feito, ainda mais em relação a pessoas com algum tipo de deficiência, seja visual ou motora. Ou seja, em termos de acessibilidade, o scroll infinito se mostra bem mais adequado em termos de UX nesses dispositivos.

Usando ponteiro (notebooks e desktops)

Creio que o princípio seja o mesmo em relação ao dito na seção "dispositivos móveis" acima.
Usando o mouse wheel se torna bem mais confortável o scroll infinito do que ter que clicar em botões.

Mas também creio que isso seja muito relativo ao público alvo e ao tipo de conteúdo do site. Muitas vezes a paginação se torna melhor porque pela quantidade de botões o usuário tem como saber a quantidade de informações disponíveis, já no scroll infinito não há como saber. O usuário vai rolando a tela e nunca sabe quando vai terminar.

Logo, o scroll infinito se torna melhor:

*

*Quando não há preocupação em saber a quantidade de informações.

*Mais confortável de navegar (principalmente em dispositivos baseados em toque).

*Quando as informações são atualizações ou uma lista onde o objetivo é mais a visualização e não muito de controle sobre elas.

Paginação:

*

*Quando é importante explicitar a quantidade de informações a exibir ou disponíveis.

*Quando se quer ter a possibilidade de selecionar itens em lote para alguma ação específica.

*Proporciona melhor organização e controle para o usuário.

Entre as desvantagens tem algo que pode dar errado?

Qualquer coisa pode dar errado tanto nas vantagens quanto nas desvantagens. Confesso que não ficou muito claro esse ponto.

Procuro informações objetivas de quem entende realmente do assunto.

"Mexo" há 20 anos com front-end (12 anos profissionalmente) e essa é a minha opinião e percepção do que tenho visto ao longo do tempo em que as coisas vão mudando de acordo com as atualizações e tecnologias.

A: Usar scroll infinito implica assumir que o lado cliente tem bastante memória RAM e placa gráfica, o que não é verdade se for um dispositivo móvel.
O que eu já vi de Facebook dando crash no meu Android não tá escrito. Às vezes, até o Android dá crash!
Seria muito melhor ter um botão híbrido de paginação e/ou scrolling widget bem visível, na tela. Não, na verdade seria melhor nem ter botão: o padrão seria mudar de página, com uma barra de progresso mostrando quanto tempo falta para mudar a página, e, caso eu quisesse frear a paginação, eu seguraria o dedo no LCD.