text:
Q: MongoDB find query in list of dictionaries I have a collection as below
            {
            "state" : "VIC",
            "sites" :
            [
                {
                    "name" : "VIC01",
                    "pes" :
                        [
                            {
                                "id" : "1",
                                "longname" : "rdnvej300exh0443",
                                "shortname" : "RVE4-E-043",
                                "location" : "Exhibition"
                            },
                            {
                                "id" : "2",
                                "longname" : "rdnvej160pee0343",
                                "shortname" : "RV3W-E-043",
                                "location" : "Windsor"
                            },
                            {
                                "id" : "3",
                                "location" : "my home"
                            }
                        ],
                    "partners" :
                        [
                            {
                                "id" : "REACH",
                                "fnns" : ["N54321R","N24686R","N46818R","N10461R"]
                            },
                            {
                                "id" : "NCS_CORE",
                                "fnns" : [ "N54320R","N71311R","N35797R","N57919R"]
                            }
                        ]
                },

                {
                    "name" : "CLAYTON",
                    "pes" :
                        [
                            {
                                "id" : "1",
                                "longname" : "rdnvej1822da0o43",
                                "shortname" : "RVCZ-E-043",
                                "location" : "Clayton"
                            },
                            {
                                "id" : "2",
                                "longname" : "rdnvej1822da0o44",
                                "shortname" : "RVCZ-E-044",
                                "location" : "Clayton"
                            }
                        ],
                    "partners" :
                        [
                            {
                                "id" : "NCS_CORE",
                                "fnns" : ["N54331R","N24686R","N46818R","N10461R"]
                            },
                            {
                                "id" : "NCS_CLAYTON_OPS2",
                                "fnns" : [ "N54321R","N71311R","N35797R","N57919R"]
                            }
                        ]
                }
            ]
            }

I am trying to retrieve

{state, sites.name,sites.partners.id}

from all the documents having "N54321R" in "fnns" list.
I tried below queries but for the above it is giving all sites.partners.id.
1. db.topology.find( {"sites.partners.fnns" : { "$elemMatch" : { "$eq" : "N54321R" } } }, {"state" : 1 , "sites.name" : 1, "sites.partners.id" : 1 , "sites.partners.fnns" : 1} )

2. db.topology.find( {"sites.partners.fnns" : { $in : ["N54321R"] } }, {"state" : 1 , "sites.name" : 1, "sites.partners.id" : 1 , "sites.partners.fnns" : 1} )

3. db.topology.find( {"sites.partners.fnns" : "N54321R"} , {"state" : 1 , "sites.name" : 1, "sites.partners.id" : 1 , "sites.partners.fnns" : 1} )

Correct output should be (just showing sites.partners.id)
{ REACH , NCS_CLAYTON_OPS2 }

but it is giving all sites.partners.id i.e.
{ REACH , NCS_CORE , NCS_CORE , NCS_CLAYTON_OPS2 }

What should I modify in the query to achieve the results?
If schema change required then please tell me what should be the correct schema?
Thanks.

A: The basic "projection" offered through the .find() method is not able to filter content from arrays in the way you are asking. The positional $ match for more than one element at the outer level or specifying specific elements of subdocuments is just not handled here.
Instead you need .aggregate() in order to filter out the content, so in order to just return those "partners" elements that have the matching value the most efficient way possible at present is this:
Just Solving for the lazy or impatient
db.collection.aggregate([
    { "$match": { "sites.partners.fddn": "N54321R" } },
    { "$project": {
        "state": 1,
        "sites": {
            "$setDifference": [
                { "$map": {
                    "input": "$sites",
                    "as": "site",
                    "in": {
                        "$let": {
                            "vars": {
                                "partners": {
                                    "$setDifference": [
                                        { "$map": {
                                            "input": "$$site.partners",
                                            "as": "partner",
                                            "in": {
                                                "$cond": [
                                                    { "$setIsSubset": [ ["N54321R"], "$$partner.fnns" ] },
                                                    "$$partner",
                                                    false
                                                ]
                                            }
                                        }},
                                        [false]
                                    ]
                                }
                            },
                            "in": {
                                "$cond": [
                                    { "$eq": [{ "$size": "$$partners" }, 0] },
                                    false,
                                    {
                                        "name": "$$site.name",
                                        "pes": "$$site.pes",
                                        "partners": "$$partners"
                                    }
                                ]
                            }
                        }
                    }
                }},
                [false]
            ]
        }
    }}
])

Which will return the filtered result like:
{
    "_id" : ObjectId("564433c2f7a4adee6c13205b"),
    "state" : "VIC",
    "sites" : [
            {
                    "name" : "VIC01",
                    "pes" : [
                            {
                                    "id" : "1",
                                    "longname" : "rdnvej300exh0443",
                                    "shortname" : "RVE4-E-043",
                                    "location" : "Exhibition"
                            },
                            {
                                    "id" : "2",
                                    "longname" : "rdnvej160pee0343",
                                    "shortname" : "RV3W-E-043",
                                    "location" : "Windsor"
                            },
                            {
                                    "id" : "3",
                                    "location" : "my home"
                            }
                    ],
                    "partners" : [
                            {
                                    "id" : "REACH",
                                    "fnns" : [
                                            "N54321R",
                                            "N24686R",
                                            "N46818R",
                                            "N10461R"
                                    ]
                            }
                    ]
            },
            {
                    "name" : "CLAYTON",
                    "pes" : [
                            {
                                    "id" : "1",
                                    "longname" : "rdnvej1822da0o43",
                                    "shortname" : "RVCZ-E-043",
                                    "location" : "Clayton"
                            },
                            {
                                    "id" : "2",
                                    "longname" : "rdnvej1822da0o44",
                                    "shortname" : "RVCZ-E-044",
                                    "location" : "Clayton"
                            }
                    ],
                    "partners" : [
                            {
                                    "id" : "NCS_CLAYTON_OPS2",
                                    "fnns" : [
                                            "N54321R",
                                            "N71311R",
                                            "N35797R",
                                            "N57919R"
                                    ]
                            }
                    ]
            }
    ]
}

Explaination of what is happening for the curious
There are a few things going on here, especially if you are not familiar with the aggregation framework so it's best to step through them.
First there is the $match pipeline stage, which is essentially a "query" just like you issue as the first argument to .find(). The path used there will select documents that acutally have the matching element:
    { "$match": { "sites.partners.fddn": "N54321R" } },

So sites.partners.fddn is the "path" to match correctly for the value you are looking for. "Dot notation" is the correct form for this at this stage. It matches a document, but looking at the positional $ operator the array match is really only counted as the element of sites, and just the first one where a match occurred. So that is why this "projection" is of no use for your purpose, but you still should $match to narrow down the documents you actually want.
Then there is $project, which is an extended form of what can be done with standard projection and actually allows complete document manipulation that cannot be done with .find().
Within this you have compounded arrays, and these are what you need to inspect and filter. The tools for this are $map and $setDifference respectively.
Essentially, $map looks at each element of the array and allows conditions to be processed against each element. In this case the operation you want is $cond which is a ternary operator. It returns a value depending on the condition in it's first argument, being either the second argument where true or the third argument where false.
If you first look at the innermost part of this:
{ "$map": {
    "input": "$$site.partners",
    "as": "partner",
    "in": {
        "$cond": [
            { "$setIsSubset": [ ["N54321R"], "$$partner.fnns" ] },
            "$$partner",
            false
        ]
    }
}},

This is looking at each element of the inner "partners" array and doing another comparison on it's "ffns" array. Speeding this up a bit is $setIsSubset, which compares your value ( specified as an array/set itself ) to see if it is actually a "subset" ( contained member(s) ) of the array/set being tested. This is another logical true/false result also fed to a $cond, which is either returning the element or false where the condition was not met.
The $setDifference shown in various places is always doing the same job, which is since $map is just returning either wanted values of the false result for each element, this comparison removes all false elements, just leaving behind the content with matching values.
Finally there is $let which allows declaration of variables to avoid repeated declarations of logic. Though it does not apply to your data in this sample, it is a possibility that the resulting filtering of "partners" could in fact be an empty array. This would generally not be desired in the results.
Therefore in the $map processing of the "sites" array, we work out each filtered result for "partners" first, then test that result to see if it actually has some length. If it does not, then a similar false is returned, otherwise the content from the element is returned "with" the filtered version of "partners" in place of the original array for each member. The same filtering of $false is then applied.
It can be a bit to take in, but worth studying and understanding. It is also possible to process using stages with $unwind, but should be avoided since that would have a significant performance impact. However the aggregation pipeline as shown here has basically the same performance characteristics of any standard query, with very little additional overhead.

A: Your collection only has one document. It has a complex substructure with nested arrays of objects but db.topology.find() is always going to return either 0 or 1 document on this collection. That document is going to include all the elements of all the nested arrays.
Think of $elemMatch as find me all the complete documents where any of the array elements contain the value specified. That's very different from what you're trying to do which is find me all the array elements from a document that contain the value specified and exclude the ones that do not.
To be able to search partners independently you can create separate collections for sites, pes, and partners and have pes and partners include keys that reference the parent site.


text:
Q: Not inserting data form into database table PHP I've been trying to insert data from a form into a database table, but it seems like an impossible task. I've tried to follow all tutorials I've seen but so far nothing is working. Could you please lend me a hand? (ATM I just want to insert the data into the table, I know I have to work on this code)
<?php
    date_default_timezone_set('Europe/Madrid');
    $link = mysqli_connect("localhost", "root", "root");
    if(!$link){
        die("Conexion fallida: ". mysqli_error());
    }
    if(isset($_POST['enviar'])){
        $nombre = $_POST["nombre"];
        $email = $_POST["email"];
        $nombreReceta = $_POST["nombre-receta"];
        $pasosReceta = $_POST["pasos-receta"];
        $query = "INSERT INTO datosformulario (nombre, email, nombrereceta, pasosreceta) VALUES ('$nombre', '$email', '$nombreReceta', '$pasosReceta')";
        mysqli_query($link, $query);
        mysqli_commit($link);
    }
    mysqli_close($link);
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="formulario-recetas" onsubmit="return validarFormulario();">
    <input type="text" name="nombre" size="40" placeholder="Nombre">
    <input type="email" name="email" size="40" placeholder="Email">
    <input type="nombre-receta" name="nombre-receta" size="40" placeholder="Nombre de la receta">
    <textarea name="pasos-receta" cols="42" rows="10" placeholder="Introduce todos los pasos necesarios para la receta"></textarea>
    <br>
    <input type="submit" name="enviar" value="Enviar" class="send-btn">
    <input type="button" value="Ayúdame a rellenarlo" class="send-btn" onclick="rellenarFormulario();">
</form>

I'll appreciate any help you can give me.
Thanks in advance.

A: The $link you are using for database connection must have a name of database,
like this:
       $link = mysqli_connect("host", "user", "password", "dbname");
For more information you can visit the Documentation on mysqli_connect(), here
mysqli_connect

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xamarin iOS backgrounding app termination I'm currently developing a timer app for android and iOS. I really care more about iOS for the time being, and even after following Xamarin's documentation on backgrounding, using messaging center calls to the appDelegate.cs class and then launching a background task with the platform specific code, I'm still having my app terminated.
Is there any way to put an iOS app as a foreground service, like on android.  Or is a background service still the way to go? I am trying to allow the user to set a timer up to 23 hours in advance and show count down.

A: To those interested, another strategy I found was just setting a notification to go off, regardless of if the app is running or not.  Then, you can just handle persistence instead of trying to make the app keep running!
Good luck to everyone!


text:
Q: Core Data Relationship For Unidirectional One to Many What is the best practice for creating Unidirectional One to Many Relationships in Core Data?
For example...
Lets take two classic entity examples, "teacher" and "student".
Each student has one teacher, and each teacher has many students.
In CoreData right now you are forced to provide an inverse such that teacher is forced to have a reference to a 'student'.  If you don't you get this nice warning that says something along the lines of...
file:///Users/josephastrahan/Documents/VisualStudioProjects/Swift3WorkOrders/WorkOrders/WorkOrders/WorkOrders.xcdatamodeld/WorkOrders.xcdatamodel/: warning: Misconfigured Property: Teacher.student should have an inverse

What if I don't want teacher to have a reference to student?
Some other posts have brought up that I should just allow the inverse anyways but I think this inverse may be causing an issue with one of my projects.
That said let me explain my exact issue.
Lets say that our teacher has a unique attribute int64 called 'id'.  Lets say the students also have unique attribute int64 called 'id'.
The int64 is enforced to be unique by adding a constraint on the model for teacher on id. (refer to image below to see how that is done)

Every year there is new students but the teachers stay the same.  So I decided that I want to delete all the students without deleting the reference to the teacher.  So I set the delete rule to 'nullify' for the relationship for the teacher to student and 'nullify' for the student to teacher.
Now when I create a new student I want to assign one of the existing teachers to that student... (something like student.teacher = teacher object with id of 1 or the same id as before) however!! , because the teacher has the inverse relationship to a student that no longer exists (which in theory should be null) the program crashes!
I know this is the case as I've used print console logs to narrow it down the exact point that it occurs.  Also I know this because if I add the delete rule of cascade for student the crash will go away but...then I lose my teacher! which I don't want...
Some things that I think might be the issue:
1.) When I do my testing I do it at the startup of the program which creates a new context everytime.  Could it be that because I never deleted teacher it still thinks it refers to a student from a context that no longer exists? (if I'm even saying this right...)
I'm not sure the best solution to acheive what I'm trying to do with Coredata and any advice is much appreciated!
Note:
Forgot to mention I also have the Merge Policy of: NSMergeByPropertyObjectTrumpMergePolicy, which will overwrite the old data with the new.  When I'm creating new students I'm creating new teachers also just using the same id which should follow this policy.

A: You are almost there.

*

*The advice to keep the inverse relationship is a good one. Keep it.

*Your issue is likely caused by different contexts. Instead of holding on to a teacher object in memory, you should fetch the teacher (based on the id) in the context in which you intend to use it.

*Your nullified students should not have any impact. A to-many relationship is really a Set<Student>. Make sure the set is empty.

NB:
If you want to keep the student in the database (for historical purposes) - it seems from your description that this is the case - you might also consider another scheme: give your students another attribute (such as a year) and use that to filter the student list. You would not have to delete or nullify anything. You could also do some more interesting time-based queries on the data.

A: Unique Constraints are available with iOS9. Which have helped iOS Developers with adding and updating records in CoreData.
Unique Constraints make sure that records in an Entity are unique by the given fields. But unique constraints along with To-Many relationship leads to a lot of weird issues while resolving conflicts.
e.g. "Dangling reference to an invalid object."
This post is basically focused to a small problem that may take days to fix.
http://muhammadzahidimran.com/2016/12/08/coredata-unique-constraints-and-to-many-relationship/


text:
Q: Determine a number is transcendental/algebraic
Determine: $(0.064)^{\frac{1}{3}}$ is transcendental or algebraic

To show a number is transcendental/algebraic do I need to show there is a monic polynomial with integer coefficients such that the number is/is not its root ?
in this case:
$x=(0.064)^{\frac{1}{3}}\iff x=\frac{2}{5}\iff x-\frac{2}{5}=0$
How can I continue?

A: Either a monic polynomial with rational coefficients, or any polynomial with integer coefficients.
For example $5x^3 -29x^2+3x+11 = 0$ has integer coefficients, and is equivalent to $x^3 - \frac{29}5 x^2 + \frac 3 5 x + \frac{11}5 =0\vphantom{\dfrac11}$, which is monic and has rational coefficients.
For that matter, a non-monic polynomial with rational coefficients can serve.  For example if you have $\frac 7 6 x^3 + \frac 3 8 x^2 + 5x + \frac 1 2 = 0\vphantom{\dfrac11}$ you observe that the smallest common multiple of the denominators $6$, $8$, and $2$ is $24$, and multiplying both sides by that, you get $28x^3 + 9x^2 +120x + 12 =0\vphantom{\dfrac11}$, and then if you want it to be monic, just divide every term on both sides by $28$.

A: https://en.wikipedia.org/wiki/Algebraic_number
A number is algebraic if it is a root of a non-zero polynomial with rational coefficients. There is no demand that the polynomial be monic.

A: A number $y$ is algebraic if it satisfies a polynomial $p(\alpha)$ having rational numbers as coefficients; that is, if $p(y) = 0$ where $p(\alpha) \in \Bbb Q[\alpha]$.  Note we may in fact assume $p(\alpha)$ is monic, since $p(y) = 0$ if and only if $\lambda^{-1} p(y) = 0$, where $\lambda \in \Bbb Q$ is the leading coefficient of $p(\alpha)$; clearly $rp(\alpha) \in \Bbb Q[\alpha]$ for any $r \in \Bbb Q$.
These things being the case, in the present instance we have
$x = (.064)^{1/3}, \tag{1}$
$x^3 =.064, \tag{2}$
whence
$x^3 - .064 = 0; \tag{3}$
note that
$.064 = \dfrac{64}{1000} = \dfrac{16}{250}$
$= \dfrac{8}{125} \in \Bbb Q; \tag{4}$
thus
$x^3 - \dfrac{8}{125} = 0; \tag{5}$
$x$ is therefore algebraic over $\Bbb Q$, satisfying as it does the cubic polynomial
$\alpha^3 - \dfrac{8}{125} \in \Bbb Q[\alpha]. \tag{6}$


text:
Q: how to keep order of sorted dictionary passed to jsonify() function? I'm trying to pass sorted dictionary to jsonify() function and then use it from within JS code to take out values. What I see there is that even though I pass correct values, they are reordered by jsonify for some reason.

json_data = {
    "11": {
        "j_id": "out",
    },
    "aa": {
        "j_id": "in",
    },
    "bb": {
        "j_id": "out",
    },
}

jkeys=json_data.keys()
sorted_json = sorted(jkeys, key=lambda x: json_data[x]['j_id'], reverse=False)

new_sorted=OrderedDict()
for rec in sorted_json:
    new_sorted[rec]=json_data[rec]

print('sort dict: {}'.format(new_sorted))

The output is correct and I can see proper values which in my case should be: aa, 11, bb
>>> from collections import OrderedDict
>>>
>>> json_data = {
...     "11": {
...         "j_id": "out",
...     },
...     "aa": {
...         "j_id": "in",
...     },
...     "bb": {
...         "j_id": "out",
...     },
... }
>>>
>>> jkeys=json_data.keys()
>>> sorted_json = sorted(jkeys, key=lambda x: json_data[x]['j_id'], reverse=False)
>>>
>>> new_sorted=OrderedDict()
>>> for rec in sorted_json:
...     new_sorted[rec]=json_data[rec]
...
>>> print('sort dict: {}'.format(new_sorted))
sort dict: OrderedDict([('aa', {'j_id': 'in'}), ('11', {'j_id': 'out'}), ('bb', {'j_id': 'out'})])

Unfortunately, when I pass this to jsonify() function and then for example console.log() output of flask data, the orderd becomes like that: 11, aa, bb. Additionally to that, I've done some research and found this stackoverflow answer, leading to some good documentation notes which clearly states that setting JSON_SORT_KEYS to False is not recommended way. Then I checked this github issue and it seems that problem is not fully resolved in flask.
What would be the best way to fix it in my case?

A: Add this config line to your code after the app definition:
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False

A: By default, keys from json are sorted to true.
You need to override this in your project config as follows:
app.config['JSON_SORT_KEYS'] = False

A: JSON objects are unordered structures, and your browser could easily end up discarding the order of your JSON keys again.
From the JSON standard:

An object is an unordered set of name/value pairs.

Bold emphasis mine. To remain standards compliant, use a list (JSON array) to capture a specific order.
That said, Flask can be made to preserve the order you set with OrderedDict.

*

*Disable sorting app-wide, with JSON_SORT_KEYS = False.
With this setting at the default True, jsonify() sorts keys to provide stable HTTP responses that are cacheable. The documentation warns against disabling this only to make you aware of the downside of setting this to False.
However, if you are using Python 3.6 or newer this concern doesn't actually play because as of that version the built-in dict type also preserves insertion order, and so there is no problem with the order changing from one Python run to the next.

*Instead of using jsonify(), use flask.json.dumps() directly, and create your own Response object. Pass in sort_keys=False:
from flask import json

response = current_app.response_class(
    json.dumps(new_sorted, sort_keys=False),
    mimetype=current_app.config['JSONIFY_MIMETYPE'])


text:
Q: Radio buttons in nested ng-repeat I am new to angular and I was stuck on an issue where I have a nested ng-repeat inside an ng-repeat as follows:

Q{{$index+1}}. {{question.Ques.questiontxt}}

                        <input type="radio" name="question{{$parent.$index}}" value="{{answer.answertxt}}{{$parent.$index}}"/>         {{answer.answertxt}}

Here, main.questions is an array of questions. For each question there are multiple options which are iterated through the second ng-repeat block. However, when I try to use ng-model for the radio button input as follows:
<input type="radio" name="question{{$parent.$index}}" value="{{answer.answertxt}}{{$parent.$index}}" ng-model="main.formData"/> {{answer.answertxt}}

, I am only able to select one option for all the questions combined (ideally should be able to select 1 option for each question.). And when I don't use ng-model, then I am able select one option for each question (as should be) but unable to capture the value of the selected input.
Can you please guide me on what can be the issue here? Is there a better way of achieving what I am trying to do here? I need to capture the value of each selected option and add it to a JSON object.

A: Check here : plunkerCode

Q{{$index+1}}. {{question.questiontxt}}

       <input type="radio"
          name="question{{$parent.$index}}"
          ng-value="{{answer.answertxt}}{{$parent.$index}}"/>
            {{answer.answertxt}}

I tried to simulate your code.

A: I made an example for you. I think that you have to modify this in function of your main object. The key is use the ng-value and the ng-model in the input radio

function testCtrl($scope) {

  $scope.main = {};
  $scope.main.questions = [{
    Ques: {
      questiontxt: 'Question 1'
    },
    Answer: [{
      answertxt: "option 11",
      value: false,
      values: [true, false]
    }, {
      answertxt: "option 12",
      value: false,
      values: [true, false]
    }]
  }, {
    Ques: {
      questiontxt: 'Question 2'
    },
    Answer: [{
      answertxt: "option 21",
      value: false,
      values: [true, false]
    }, {
      answertxt: "option 22",
      value: false,
      values: [true, false]
    }]
  }, ];

}

Q{{$index+1}}. {{question.Ques.questiontxt}}

      {{answer.answertxt}}
      <input type="radio" ng-value="true" ng-model="answer.value" />true
      <input type="radio" ng-value="false" ng-model="answer.value" />false

  {{main}}

A: You can just take out the "name" property of the radio button and reference them by the model they have.
That worked for me.


text:
Q: Angular Directive: use $watch or pass in binded value I have a controller which calls a service returning a list of courses.
Each course has an property called 'percentageDone'
I want to assign some CSS to my div depending on this value.
there are 2 ways I have found to do this.  There are probably more, I am a newbie at Angular.  Thing is I am not sure what is the best way.  In terms of performance and general best Angular practice.  I realize I could use ng-class, but I am using this exercise to learn Angular.
So my Div

with this directive
myApp.directive('completionColor', function () {
  return {
   restrict: 'A',
   link: function (scope, el, attrs) {
    var donePerc = attrs['completionColor'];
     if (donePerc < 33) {
      el.addClass('progress-bar-danger');
     }
     else if (donePerc >= 33 && newVal < 66) {
      el.addClass('progress-bar-warning');
     }
     else if (donePerc >= 66) {
      el.addClass('progress-bar-success');
     }
   }
  };
});

or another way

and js
myApp.directive('completionColor', function () {
    return {
        restrict: 'A',
        link: function (scope, el, attrs) {
            scope.$watch(attrs['completionColor'], function (newVal) {
                if (newVal < 33) {
                    el.addClass('progress-bar-danger');
                }
                else if (newVal >= 33 && newVal < 66) {
                    el.addClass('progress-bar-warning');
                }
                else if (newVal >= 66) {
                    el.addClass('progress-bar-success');
                }
            });
        }
    };
});

I like that I don't have to put the {{}} in my directive, but in general the data will not change much.  So not sure I need to use a $.watch.

A: I'd say $watch is the last thing you should use here.
I myself see no problem with using {{}}, that's what they are for. But you have another option if you want, you could use One Time Binding (https://docs.angularjs.org/guide/expression) if you're using angular 1.3.X and that way you're improving performance, since angular doesn't keep watch for that:

And work with a scope in your directive (you can use isolated as well):
scope: {
    completionColor: "@"
},

Now you can use scope.completionColor in your link function.


text:
Q: Defining methods in super class for sub classes How would one go about defining a method in a super class but leave the implementation to the sub classes?

A: Leave the method abstract:
abstract class A {
    abstract void doStuff();
}

class B extends A {
    void doStuff() {
        // stuff
    }
}

Note that...

If a class includes abstract methods, the class itself must be declared abstract

Abstract classes can't be constructed (so new A() would be an error, but new B() would be fine), and subclasses need to implement all abstract methods unless they're also abstract.
abstract class A {
    abstract void doStuff();
}

abstract class B extends A {
    // This is fine since B is abstract
}

class C extends A {
    // This is an error since doStuff() isn't implemented
}

With an abstract class, you can mix abstract and normal methods:
abstract class A {
    abstract void doStuff();

    void doOtherStuff() {
        // Subclasses don't need to implement this
    }
}

If all of the methods are abstract, it may make more sense to use an interface, since classes an implement multiple interfaces:
interface DoesStuff {
    void doStuff();
}

interface DoesOtherStuff {
    void doOtherStuff();
}

class B implements DoesStuff, DoesOtherStuff {
    void doStuff() {
        // stuff
    }

    void doOtherStuff() {
        // other stuff
    }
}

Note: Methods in an interface are automatically abstract and public, unlike methods in classes, which are by default package private and not abstract.

A: Make super class as abstract class and define method as abstract method which forces subclasses to provide implementations (or) make themselves as abstract.
Example:
abstract class Super {
    abstract void absMethod();
}

class Sub extends Super {
    void absMethod() {
        // implementation
    }
}

A: You would create an abstract method in the super class.
abstract class SuperClass {
   public abstract void mustImplement();
}

class SubClass extends SuperClass {
   public void mustImplement() {
       // Do stuff here
   }
}

A: It should declared abstract. e.g.
abstract class MyBaseClass
{
  protected abstract void myMethod();
}

class MyChildClass extends MyBaseClass
{
  protected void myMethod()
  {
    // here is my implementation!
  }
}


text:
Q: Seeking for Android Java AES Encryption , NDK C/C++ Decryption and viceversa source code example I am looking for any Android java AES 256 or AES 512 crypto library which is compatible with NDK openSSL library in C/C++ source code example. I want to encrypt in Java and pass it to C and decrypt there and vice versa depending on our application scenario. Please help me out with any example . I tried myself with the following code in java and c .but it is not working .
my java side is :
  SecretKeySpec skeySpec = new SecretKeySpec(key, "AES/CBC/PKCS5Padding");
  Cipher cipher = Cipher.getInstance("AES")
  cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

On NDK side i am using
 EVP_BytesToKey(
     EVP_aes_256_cbc(),
     EVP_sha1(),         // SHA1
     Salt,               // 0
     KeyData,
     KeyLength,
     Rounds,             // 0
     aes_key, aes_iv);   // return buffers

Appreciate any responses ....

A: Bouncy castle is the option. Used it working fine.


text:
Q: Are Java 6's performance improvements in the JDK, JVM, or both? I've been wondering about the performance improvements touted in Java SE 6 - is it in the compiler or the runtime? Put another way, would a Java 5 application compiled by JDK 6 see an improvement run under JSE 5 (indicating improved compiler optimization)? Would a Java 5 application compiled by JDK 5 see an improvement run under JSE 6 (indicating improved runtime optimization)?
I've noticed that compiling under JDK 6 takes almost twice as long as it did under JDK 5 for the exact same codebase; I'm hoping that at least some of that extra time is being spent on compiler optimizations, hopefully leading to more performant JARs and WARs. Sun's JDK info doesn't really go into detail on the performance improvements they've made - I assume it's a little from column A, and a little from column B, but I wonder which is the greater influence. Does anyone know of any benchmarks done on JDK 6 vs. JDK 5?

A: javac, which compiles from Java source to bytecodes, does almost no optimisation. Indeed optimisation would often make code actually run slower by being harder to analyse for later optimisation.
The only significant difference between generated code for 1.5 and 1.6 is that with -target 1.6 extra information is added about the state of the stack to make verification easier and faster (Java ME does this as well). This only affects class loading speeds.
The real optimising part is the hotspot compiler that compile bytecode to native code. This is even updated on some update releases. On Windows only the slower client C1 version of hotspot is distributed in the JRE by default. The server C2 hotspot runs faster (use -server on the java command line), but is slower to start up and uses more memory.
Also the libraries and tools (including javac) sometimes have optimisation work done.
I don't know why you are finding JDK 6 slower to compile code than JDK 5. Is there some subtle difference in set up?

A: I have not heard about improvements in the compiler, but extensive information has been published on the runtime performance improvements.
Migration guide:
http://java.sun.com/javase/6/webnotes/adoption/adoptionguide.html
Performance whitepaper:
https://www.oracle.com/java/technologies/javase/6performance.html

A: Its almost 100% the runtime.  While it is possible for some basic compilation tricks to make it into the Java compiler itself, I don't believe there are any significant improvements between Java 1.5 and 1.6.

A: There's been a lot of new improvements and optimization in the new java virtual machine. So the main part you'll see improved performance is while running java with the version 6 jvm.
Compiling old java code using the Java 6 JDK will probably yield more efficient code, but the main improvements lie in the virtual machine, at least that's what I've noticed.


text:
Q: How to use scaffolding and form_for in RoR with Mustache I'm using mustache templates in my rails app with mustache-rails
. I wanted to do scaffolding and use the form_for helper, but I can't get the submit button working. I found this https://gist.github.com/954994 , but I don't want to do it so generic. I just wanted to turn a my scaffolding to a template based version.
this is my view class
module Views
  module Slideshows
    class New < Layouts::Application

       def form
         form_for(@slideshow) do |f|
          {
              :submit => f.submit
          }
         end
       end

       def errors?
           @slideshow.errors.any?
       end

       def error_header
           "#{pluralize(@slideshow.errors.count, "error")} prohibited this post from being saved:"
       end

       def errors
         @slideshow.errors.full_messages
       end

       def back_link
         link_to 'Back', slideshows_path
       end

    end
  end
end

this is my template class

New slideshow

{{#form}}
  {{#errors?}}

{{error_header}}

      {{#errors}}

{{.}}

      {{/errors}}

  {{/errors?}}

    {{submit}}

{{/form}}

{{back_link}}

In my opinion the problem is I cant access :submit in the form_for block.


text:
Q: Excluding fields in generic CRUD views I have a model named Domain which looks like this:
class Domain(models.Model):
    """
    Model for storing the company domains
    """
    user = models.ForeignKey(
        User
    )
    host = models.CharField(
        null=False, verbose_name="Host", max_length=128, unique=True
    )

I'd like to use Django's generic views for doing CRUD operations on this. There is one field in this model that needs user input but the foreign key field doesn't need any user input. How can I exclude that field from the form that my generic view generates but assign it the value of the current authenticated user.
Thanks.

A: Have a look at Russel's answer to a similar question on the django-users group earlier this week.
Quoting the answer*:

Forms and Views solve different problems.
The View is solving the problem of "how do I handle this request and
  convert it into a response?". The Form is solving the problem of "How
  do I convert the POST data in this request into a model object (or a
  change to a model object)?".
Very roughly, a view is doing the following:

*

*View gets a request

*View works out whether this is a GET or a POST

*If its a POST, View asks the Form to turn the Post into a model change

*Form returns success or failure

*View responds to the success or failure of the Form.

*View returns a response.

  The functionality of the Form is a complete subset of the
  functionality of the View -- and for this reason, it's a completely
  interchangable internal component.
Now, in simple situations, it's possible for a View to guess all the
  defaults for the form -- all it needs to know is that you're dealing
  with a Foo model, and it can construct a default Foo ModelForm.
  However, if you have more sophisticated form requirements, you're
  going to need a customized Form.
We could have implemented this by exposing all the options of
  ModelForm on the View class; but in order to keep everything clean, we
  kept the ModelForm isolated, and provided the View with a way to
  specify which Form class it's going to use.
So - to cover your use case of excluding fields, you define a
  ModelForm that excludes the fields, then let the CreateView know the
  form you want to use:

class CampaignForm(forms.ModelForm):

    class Meta:
        model = Campaign
        exclude = ('user', 'name', 'content_inlined')

class CreateCampaignView(CreateView):
    form_class = CampaignForm
    template_name = "forms/create.html"

I'm guessing when you say "fix a values for a field", you mean setting
  the values of user, name and content_inlined before you save the new
  Campaign instance; to do this, you need to inject some extra code into
  the form processing logic of the form:

class CreateCampaignView(CreateView):
    form_class = CampaignForm
    template_name = "forms/create.html"

    def form_valid(self, form):
        form.instance.user = ... (something meaningful.. e.g., self.request.user)
        return super(CreateCampaignView, self).form_valid(form)

This overrides the default behavior when the form is valid, and sets
  the extra values. The super() implementation of form_valid() will then
  save the instance.
For the record, this could also be done by overriding the save()
  method on the ModelForm -- however, if you do that, you lose the
  request object, which you will need if you're trying to set the
  instance values to something that is request-sensitive.

*the original answer set self.object.user instead of form.instance.user. This gives an AttributeError so I have changed it above.


text:
Q: JavaFX SceneBuilder cant open fxml document with an fx:include I have a JavaFX Application that I am building with SceneBuilder, I just found out about the nifty fx:include tag that allows you include FXML files into others.  I have one main FXML doc called Manager.fxml, this is a simple view with a header and a TabPane.  Each tab in the TabPane has its own fxml document and controller - messages, contacts, and products.
Here is the section of the code that is causing SceneBuilder to think its an invalid fxml file, specifically the fx:include part, if I remove that it works.  It even works in Java code if I inject the tab and set its content to the loaded FXML I am trying to include below.
<TabPane id="theTabs" prefHeight="849.0" prefWidth="1200.0" tabClosingPolicy="UNAVAILABLE">
    <tabs>
      <Tab text="System Messages">
        <content>
           <fx:include source="/fxml/manager_message_tab2.fxml" fx:id="systemMessage" />
        </content>
      </Tab>
      <Tab fx:id="productsTab" onSelectionChanged="#goToProducts" text="Product" >
        <content>
           <fx:include source="/fxml/manager_products_tab.fxml" fx:id="product" />
        </content>
      </Tab>
      <Tab fx:id="contactsTab" onSelectionChanged="#goToContacts" text="Contact">
        <content>
           <fx:include source="/fxml/manager_contacts_tab.fxml" fx:id="contact" />
        </content>
      </Tab>
    </tabs>
</TabPane>

Althought SceneBuilder says its invalid, eclipse is able run it no problem.  I have tried using the built in tool in SceneBuilder 2.0 using File -> Include -> FXML but that fails also with - "Failed to include fxml_document.fxml under 'Tab'".  Root node of manager.fxml is a BorderPane - the root node of all the includes is also a BorderPane, so I am trying to include a border pane as the center element of a border pane.  Scenebuilder lets me drag a an empty border pane where I want it but doesn't let me fx:include one.
But that is exactly how I structured it when manually, as you can see in the code above.
My problem now is that if I try to open my manually edited FXML (the one with the included fx:include tags) it says its an invalid file and I cant edit it.
Anyone have a similar problem?


text:
Q: php json decode with variables that contains dashes {"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color":"#ffffff"
 }
}

I have this json string,  I know that php variable names doesn't support dashes. So what to do in this case ?

A: You can use an array format like this. Hyphened keys will work.
<?php

$json = '{"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color":"#ffffff"
 }
}';

$array = json_decode($json, true);

echo $array['general']['border-stroke']; // prints 2

?>

Here's a demo

A: When dealing with valid json you don't need to do anything special to use the result in php as long as you don't use extract().
Admiditly it looks cleaner to let json_decode return an array here as Jay Bhatt suggests but you are also free to use a normal object as return (which is an instance of stdclass).
The properties of the returned object can be nearly anything. You just need to use the property name as a php-string instead of a hardcoded literal.
$obj->{'a sentence with spaces and umlauts äüö is valid here'}
<?php

$json = <<<JSON
{"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color äü??$%§":"#ffffff"
 }
}
JSON;

$obj = json_decode($json);

$keyName = "round-corner";
var_dump($obj->general->{'round-corner'});
var_dump($obj->general->$keyName);
var_dump($obj->general->{'background-color äü??$%§'});

Result


text:
Q: Can't run the SPRING BOOT application with @EnableWebMvc configuration I'm new to spring boot and i'm very much interested to learn this technology. Here is the issue,  I got one configuration file with @configuration tag. so i can't run the application when i try to add @enablemvc annotation or if i add new file with @enablemvc annoation in the spring boot application. i really appreciate if some one can help me with thisss.
log
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanInitializationException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.configureAsChildIfNecessary(SpringApplicationBuilder.java:147) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at com.boot.main.ClientMain.main(ClientMain.java:31) [bin/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_131]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.9.RELEASE.jar:1.5.9.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanInitializationException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 23 common frames omitted
Caused by: org.springframework.beans.factory.BeanInitializationException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry.getHandlerMapping(ResourceHandlerRegistry.java:150) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:446) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c7bc0fe.CGLIB$resourceHandlerMapping$28(<generated>) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c7bc0fe$$FastClassBySpringCGLIB$$d042f6eb.invoke(<generated>) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c7bc0fe.resourceHandlerMapping(<generated>) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_131]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 24 common frames omitted
Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup date [Sat Feb 10 09:34:19 EST 2018]; root of context hierarchy
    at org.springframework.web.context.support.WebApplicationObjectSupport.getWebApplicationContext(WebApplicationObjectSupport.java:112) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.context.support.WebApplicationObjectSupport.getServletContext(WebApplicationObjectSupport.java:128) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.initContentNegotiationStrategy(ResourceHttpRequestHandler.java:306) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.afterPropertiesSet(ResourceHttpRequestHandler.java:268) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry.getHandlerMapping(ResourceHandlerRegistry.java:147) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 35 common frames omitted

AutoConfiguration.java
@Configuration
//@EnableAutoConfiguration
@ConditionalOnClass(MyClass.class)
@EnableConfigurationProperties(MyProperties.class)
@ComponentScan({ "com.boot", "com.jspClient" })
@SpringBootApplication
public class AutoConfiguration {

    private static Log log = LogFactory.getLog(AutoConfiguration.class);

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    /*@Bean
    public UrlBasedViewResolver urlBasedViewResolver() {
      UrlBasedViewResolver resolver = new UrlBasedViewResolver();
      resolver.setPrefix("/WEB-INF/jsp/");
      resolver.setSuffix(".jsp");
      resolver.setViewClass(JstlView.class);
      return resolver;
    }*/

    //http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/simple-mapping-exception-resolver/
    //https://github.com/paulc4/mvc-exceptions/blob/master/src/main/java/demo/config/ExceptionConfiguration.java
    @Bean
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
      SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
      Properties errorMaps = new Properties();
      errorMaps.setProperty(UserNotFoundException.class.getName(), "myError");
      errorMaps.setProperty("Exception", "generic_error");
      resolver.setExceptionMappings(errorMaps);
      resolver.setDefaultErrorView("generic_error");
      resolver.setExceptionAttribute("exc");
      return resolver;
   }

    @Bean
    WebMvcConfigurer configurer () {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addResourceHandlers (ResourceHandlerRegistry registry) {
                ResourceHandlerRegistration resourceRegistration  = registry
                        .addResourceHandler("/pages/**")
                        .addResourceLocations("/resources/","classpath:/images/")  //Configuring Multiple Locations for a Resource
                        .setCachePeriod(3600);            //The resources served will be cached in the browser for 3600 seconds
                registry.addResourceHandler("resources/**").addResourceLocations("/resources/");
                //registry.addResourceHandler("/css/**").addResourceLocations("/css/");
                //registry.addResourceHandler("/img/**").addResourceLocations("/img/");
                //registry.addResourceHandler("/js/**").addResourceLocations("/js/");
            }
        };
    }
}

AppConfig.java
@Configuration
@ComponentScan("com.boot.controllers")
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
      SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
      Properties errorMaps = new Properties();
      errorMaps.setProperty("ElectricityNotFoundException", "error");
      errorMaps.setProperty("NullPointerException", "error");
      resolver.setExceptionMappings(errorMaps);
      resolver.setDefaultErrorView("globalerror");
      resolver.setExceptionAttribute("exc");
      return resolver;
   }
}

WebAppInitializer.java
public class WebAppInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(AppConfig.class);
        ctx.setServletContext(servletContext);
        Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        dynamic.addMapping("/");
        dynamic.setLoadOnStartup(1);
   }
}

ClientMain.java
@ComponentScan("com.boot") // to scan controller under com.boot -> com.boot.controllers
@SpringBootApplication
public class ClientMain {

    private static SpringApplicationBuilder start(Class<?>... sources) {
        return new SpringApplicationBuilder(ClientMain.class)
            .child(sources);
    }

    public static void main(String[] args) throws Exception {

        // using just Spring alone
        /*ApplicationContext context = new AnnotationConfigApplicationContext(AutoConfiguration.class);

    }

}

JspClientMain.java
@ComponentScan("com.boot")
@SpringBootApplication
public class JspClientMain {

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

A: In general, the @EnableWebMvc should not be used in Spring boot applications.  I quote an article by Boz Hogan:

It turns out that Spring Boot doesn't mix well with the standard Spring MVC @EnableWebMvc. What happens when you add the annotation is that Spring Boot's autoconfiguration is disabled.
The bad part (that wasted me a few hours) is that in no guide you can find that explicitly stated. (...)

Here's a quote from the Spring Boot documentation:

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. (...)
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

So, to use @EnableWebMvc in a Spring Boot app, you need to take complete control of Spring MVC—I read that as you need to be a Spring wiz.
We had a problem with a Spring boot 1.5.9 application that had a dependency to a shared lib that contained a class annotated with @EnableWebMvc. Removing the annotation solved the problem.

A: It seems the issue is caused by mixing two different kind of initializers i.e WebApplicationInitializer and ApplicationContextInitializer.
Both WebApplicationInitializer and ApplicationContextInitializer serve fairly different purposes.
The WebApplicationInitializer is used by a Servlet Container at startup of the web application and provides a way for programmatic creating a web application(replacement for a web.xml file),
ApplicationContextInitializer provides a hook to configure the Spring application context before it gets fully created.
For a non spring boot application/normal spring mvc app it is programmatic configuration of web.xml. like you have done in your code in WebAppInitializer.java
public class WebAppInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws
     ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();

            ctx.register(AppConfig.class);
        ctx.setServletContext(servletContext);
        Dynamic dynamic = servletContext.addServlet("dispatcher", new
            DispatcherServlet(ctx));
        dynamic.addMapping("/");
        dynamic.setLoadOnStartup(1);
   }
}

ApplicationContextInitializer is essentially code that gets executed before the Spring application context gets completely created. A good use case for using an ApplicationContextInitializer would be to set a Spring environment profile programmatically, along these lines.
For Spring-Boot based application then registering an ApplicationContextInitializer could be done like below:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class SampleWebApplication {

 public static void main(String[] args) {
  new SpringApplicationBuilder(SampleWebApplication.class)
    .initializers(new DemoApplicationContextInitializer())
    .run(args);
 }
}

public class DemoApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

 @Override
 public void initialize(ConfigurableApplicationContext ac) {
  ConfigurableEnvironment appEnvironment = ac.getEnvironment();
  appEnvironment.addActiveProfile("demo");

 }
}


text:
Q: How to return manytomanyfield as object in Django RestFramework API I tried to create an API with Django RestFramework, so i created 2 models Note and Task and have a ManyToManyField in Note model so i can put many Task in a Note but the API i created don't return full object feature but just the id. Here is my code:
class NoteAPI(ListAPIView):
    serializer_class = NoteSerializer
    queryset = Note.objects.all()

Here is my models:
class Task(models.Model):
    task = models.CharField(max_length=255, null=False, blank=False)
    detail = models.CharField(max_length=255, null=True, blank=True)
    completed = models.BooleanField(default=False)
    priority = models.IntegerField(default=0)
    def __str__(self):
        return self.task

class Note(models.Model):
    title = models.CharField(max_length=255, null=False, blank=False)
    priority = models.CharField(max_length=1, choices=PRIORITY_CHOICES, default="B")
    detail = models.CharField(max_length=255, null=True, blank=True)
    completed = models.BooleanField(default=False)
    task = models.ManyToManyField(Task, related_name="note_task", blank=True)
    process = models.IntegerField( default=0, validators=[max_int_value])
    def __str__(self) -> str:
        return self.title + " is "+ str(self.process) + "% completed"

And i want the out put can looks like:
 [
    {
            "id": 2,
            "title": "Sleep",
            "priority": "F",
            "detail": "Don't do it, stay awake and do your job",
            "completed": false,
            "process": 0,
            "task": [
                      {
                         "id": 1,
                         "task": "Go to bed",
                         "completed": false
                      },
                     {
                         "id": 2,
                         "task": "Start counting",
                         "completed": false
                      }
                    ]
     }
 ]

But it actually be like this
 [
    {
            "id": 2,
            "title": "Sleep",
            "priority": "F",
            "detail": "Don't do it, stay awake and do your job",
            "completed": false,
            "process": 0,
            "task": [
                      1,
                      2
                 ]
     }
 ]

So what i can do to have the out put like that?

A: You need to tell NoteSerializer how to serialize Task objectcs.
class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ("id", "task", "completed")

class NoteSerializer(models.Model):
    task = TaskSerializer(many=True)

You probably also want to prefetch tasks to keep the number of DB queries to minimum.
class NoteAPI(ListAPIView):
    serializer_class = NoteSerializer
    queryset = Note.objects.prefetch_related("task").all()


text:
Q: Increase the heap size of a Java applet I ported one of my programs from a standalone Java application to a Java applet. The application processes large image files so I need more heap space so load them into the memory. The images are then used as texture data in an openGL window for which I used JOGL
The application works fine inside of eclipse (as applet aswell as standalone) and if I export the standalone application as an executable jar. I tested this on various systems (Windows XP 32 with 4 gig ram, Windows XP 64 with 12 gig ram and Windows 7 64 bit with 4 and with 8 gig ram).
The problem occures when I export the applet version of the program. After I signed the jar and try to run it in a browser (tested Firefox and IE) the application always crashes with an OutOfMemory exception on the 64 bit machines described above.
On the Windows XP 32bit machine however it worked after a bit of fiddling but I don't know why because all I did was to try different solutions and somehow one of them worked even if this way also lead to a crash in a previous attempt.
There are four ways I tried to increas the heap space
In the html file I tried:
<PARAM name="java_arguments" value="-Xmx1600m">

which didn't work.
Then I tried to increase the heap directly via the Java menu (Start -> Control Panel -> Java tab -> Java Runtime Environment Settings) with the -Xmx1600M argument. This hat also no impact.
After that I used a jnlp file from the guys at Jogamp. There I added
<j2se version="1.6+" java-vm-args="-Xmx1600m"
    href="http://java.sun.com/products/autodl/j2se"/>

inside the resource tag. This had initially also no effect.
Lastly I added
<j2se version="1.6+" initial-heap-size="256M" max-heap-size="1600M"
    href="http://java.sun.com/products/autodl/j2se"/>

inside the resource tag and somehow after a few tries were I circled through the four different solutions and clearing the applet cache it worked (but only on the 32 bit WinXP machine).
But I hat no success trying to run the applet on the 64 bit machines and I have absolutly no clue what to do now because after some research those four methos seem to be the only one.
Thanks for your help in advance.
I will add the two jnlp files and the html files that starts the applet.
Html:
<html>
<head>
    <title>Some title</title>
</head>
<body>
<center>
    <applet code="guiconcepts/AppletTest.class"
            width=1600
            height=1010
            archive="SConfigTest.jar">
        <param name="codebase_lookup" value="false">
        <param name="subapplet.classname" value="SConfigTest">
        <param name="subapplet.displayname" value="SConfigTest">
        <param name="noddraw.check" value="true">
        <param name="progressbar" value="true">
        <param name="jnlpNumExtensions" value="1">
        <param name="jnlpExtension1"
                 value="http://download.java.net/media/jogl/jsr-231-2.x-
                           webstart/jogl-core.jnlp">
        <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
        <param name="jnlp_href" value="AppletTest.jnlp">
    </applet>
</center>
</body>
</html>

AppletTest.jnlp:
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.5+" codebase="./"
      href="AppletTest.jnlp">

<information>
    <title>Some title</title>
    <vendor>Some vendor</vendor>
    <homepage href="http://www.somePage.com"/>
    <description>Java Applet Test</description>
    <description kind="short">Test of a Java Applet</description>
    <offline-allowed/>
</information>
<update check="background" policy="always"/>

<resources>
   <j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se"/>
   <property name="sun.java2d.noddraw" value="true"/>
   <extension name="JOGL" href="JOGL.jnlp" />
   <jar href="jai_core.jar" />
   <jar href="jai_codec.jar" />
   <jar href="mlibwrapper_jai.jar" />
   <jar href="SConfigTest.jar" main="true"/>
</resources>

<applet-desc
   name="AppletTest"
   main-class="guiconcepts.AppletTest"
   width="1600"
   height="1010">
</applet-desc>
</jnlp>

JOGL.jnlp:
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="./"
  href="JOGL.jnlp">

  <information>
    <title>JOGL libraries</title>
    <vendor>JogAmp Community</vendor>
    <homepage href="http://jogamp.org/"/>
    <description>JOGL libraries</description>
    <description kind="short">
                  All JARs and native libraries for JOGL.</description>
    <offline-allowed/>
  </information>
  <update check="background" policy="always"/>

  <security>
    <all-permissions/>
  </security>

  <resources>
    <jar href="gluegen-rt.jar" />
    <jar href="jogl.all.jar" />
  </resources>

  <resources os="Windows" arch="x86">
    <nativelib href = "gluegen-rt-natives-windows-i586.jar" />
    <nativelib href = "jogl-all-natives-windows-i586.jar" />
  </resources>
  <resources os="Windows" arch="amd64">
    <nativelib href = "gluegen-rt-natives-windows-amd64.jar" />
    <nativelib href = "jogl-all-natives-windows-amd64.jar" />
  </resources>
  <resources os="Windows" arch="x86_64">
    <nativelib href = "gluegen-rt-natives-windows-amd64.jar" />
    <nativelib href = "jogl-all-natives-windows-amd64.jar" />
  </resources>
  <resources os="Linux" arch="i386">
    <nativelib href = "gluegen-rt-natives-linux-i586.jar" />
    <nativelib href = "jogl-all-natives-linux-i586.jar" />
  </resources>
  <resources os="Linux" arch="x86">
    <nativelib href = "gluegen-rt-natives-linux-i586.jar" />
    <nativelib href = "jogl-all-natives-linux-i586.jar" />
  </resources>
  <resources os="Linux" arch="amd64">
    <nativelib href = "gluegen-rt-natives-linux-amd64.jar" />
    <nativelib href = "jogl-all-natives-linux-amd64.jar" />
  </resources>
  <resources os="Linux" arch="x86_64">
    <nativelib href = "gluegen-rt-natives-linux-amd64.jar" />
    <nativelib href = "jogl-all-natives-linux-amd64.jar" />
  </resources>
  <resources os="Mac OS X" arch="i386">
    <nativelib href = "gluegen-rt-natives-macosx-universal.jar" />
    <nativelib href = "jogl-all-natives-macosx-universal.jar" />
  </resources>
  <resources os="Mac OS X" arch="x86_64">
    <nativelib href = "gluegen-rt-natives-macosx-universal.jar" />
    <nativelib href = "jogl-all-natives-macosx-universal.jar" />
  </resources>

  <component-desc />
</jnlp>

[edit:] It seems that I found what's causing the problem (but stil no solution). If I start the applet with a 32-bit version of any given browser the browser starts the 32-bit jre which cannot cope with the jvm-settings inside the jnlp-files.
Thats is really odd because calling the 32-bit jvm on a 32-bit machine works just fine.
If I start the applet with a 64-bit browser (like the IE 64-bit version or the Nightly Firefox 64 build) the "correct" jvm is called and it runs a okay.
So I guess the real question is how to start the 64-bit jvm from a 32-bit browser (is this even possible?).
However I wrote a small test program to reproduce the error. The program stores a large image in an array. With the an 32-bit browser you should be able to load 2-3 images until you get an OutOfMemoryException. If you want to test the program you have to create a jar and sign it afterwards and name it SConfigTest.jar.
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;

public class AppletTest extends JApplet {

    private static final long serialVersionUID = 1L;

    public AppletTest() {

    }

    public void init() {

        /*
         * settings if using a proxy server
         */
        /*
        Properties p = System.getProperties();
        p.put("http.proxyHost", "proxy.address.com");
        p.put("http.proxyPort", "8080");
        System.setProperties(p);
        //*/
        System.out.println("Applet initialized");
    }
    public void start() {

        System.out.println("Applet starting");

        BufferedImage[] imgArray = new BufferedImage[20];

        /*
         * load 20 copies of the image into the memory
         */
        for(int i = 0; i < imgArray.length; i++) {

            try {

                URL imageUrl = new URL("http://www.raize.ch/Reisen/" +
                                       "velo-eurasien/karten-rollover/" +
                                       "western-tibet-highway_" +
                                       "satellitenbild_grossplus.jpg");

                InputStream in = imageUrl.openStream();
                imgArray[i] = ImageIO.read(in);
                in.close();
                System.out.println("Image no. " + (i + 1) + " loaded!");
            }
            catch (IOException e) {

                e.printStackTrace();
            }
        }

        System.out.println("All images loaded");

        /*
         * display the image inside the browser window
         */
        this.setSize(imgArray[0].getWidth(), imgArray[0].getHeight());
        this.getContentPane().add(new JLabel(new ImageIcon(imgArray[0])));
    }

    public void stop() {

        System.out.println("Applet stopping");
    }

    public void destroy() {

        System.out.println("Applet destroyed");
    }
}

A: Stick with initial-heap-size="256M" max-heap-size="1600M" if only for the fact that spelling mistakes will show up more easily.

somehow after a few tries were I circled through the four different solutions and clearing the applet cache it worked (but only on the 32 bit WinXP machine).

It is not the applet cache that is important here, but the cached JNLP file.  Go to the Java Control Panel, find the app. and uninstall it between runs.


text:
Q: How do I install Ubuntu Server using Daemon Tools instead of a disc? How do I install Ubuntu Server using Daemon Tools instead of a disc?
Just trying to see if it can be done, and if so how can I do that? I'm looking to Dual Boot it with Windows 8 as well.
Thank you.

A: Given that Daemon Tools is Windows software and ubuntu server replaces it, no: you cannot install Ubuntu server using daemon tools instead of a disc.


text:
Q: I have some configuration with complex fields, the task is to find the section in the configuration that has the field that was clicked on The configuration looks like this:

As we can see, we have some configuration with sections, and these sections have some fields, the list of which I render using the autocomplete functionality in the application search input. I also render sections that I can toggle on click and render the corresponding fields in every section. The goal is that when I click on a field from the search input dropdown list, the section switches to the one in which the clicked field is located.
const SearchForm = ({ handleUpdateSearch, configure, tabValue, setTabValue }: { handleUpdateSearch: any, configure: Config, tabValue: number, setTabValue: Function }) => {

    const handleUpdate = (e: React.ChangeEvent<HTMLInputElement>) => {
        handleUpdateSearch(e.target.value)
    }

    const changeSection = (_id: any) => {
        // change tabValue depending on the clicked field
    }

    const arr = configure.sections.map((s: any) => {
        return s.fields.map((f: any) => {
            return f.name;
        });
    })

    const merge = [].concat.apply([], arr); // search input dropdown list

    return (
        <Box sx={Header}>
            <Autocomplete
                freeSolo
                disableClearable
                size='small'
                sx={{ width: 250 }}
                options={merge}
                renderOption={(props, option) => (
                    <li {...props}>
                        <ListItem>
                            {option}
                        </ListItem>
                    </li>
                )}
                renderInput={(params) => (
                    <Search onChange={handleUpdate}>
                        {/* <SearchIconWrapper>
                            <SearchIcon />
                        </SearchIconWrapper> */}
                        <StyledInputBase
                            placeholder="Search…"
                            {...params}
                            InputProps={{
                                'aria-label': 'search',
                                ...params.InputProps,
                                type: 'search',
                            }}
                        />
                    </Search>
                )}
            />
            <Typography variant="h5" color='common.white'>
                Configuration Manager
            </Typography>
        </Box>
    )
}

export default SearchForm;

Specifically, the tabValue variable is responsible for the section number, and the setTabValue function is responsible for changing this variable (the number of each section is a state).Also, if there are any tips or recommendations on rendering fields in autocomplete, I would be grateful.


text:
Q: Resize Element with box handles in corners in Jcrop , after selecting cropping area , a div appears with box handles in corners.

Is there any jQuery plugin that can build this type of box handles ?

A: You can use jQuery UI's resizable as noted above. I even setup a fiddle for ya!
http://jsfiddle.net/digitalaxis/j2JU6/
jQUERY
$('#element').resizable({
    handles: {
    'ne': '#negrip',
    'se': '#segrip',
    'sw': '#swgrip',
    'nw': '#nwgrip'
    }
});

HTML

CSS
#elementResizable {
    border: 1px solid #000000;
    width: 300px;
    height: 40px;
    overflow: hidden;
}
#nwgrip, #negrip, #swgrip, #segrip, #ngrip, #egrip, #sgrip, #wgrip {
    width: 10px;
    height: 10px;
    background-color: #ffffff;
    border: 1px solid #000000;
}
#segrip {
    right: -5px;
    bottom: -5px;
}

A: You can use the jQuery UI Resizable plugin:
http://jqueryui.com/demos/resizable/
Use the "handles" parameter to make your element resizable through it's entire border.


text:
Q: dialog box displays only the last item in the array list I am trying to display data from a an array list but after the marker onclick
it only displays the last element in the array list in the material dialog box
 DriverLocationDataManager gets all the data snapshots of the geopoints of the drivers in the database
after adding in all the driver data, i use the addMarker function which gets the geopoints and set the markers on the map.
//Init data manager

    drivers = new ArrayList<>(0);

    dataManager = new DriverLocationDataManager(this) {
        @Override
        public void onDataLoaded(List<Driver> data) {
            if (data.isEmpty()) {
                Snackbar.make(container, "Sorry!. UG Shuttle service is currently unavailable",
                        Snackbar.LENGTH_INDEFINITE).show();
            } else {

                drivers.addAll(data);

                List<Marker> markers = addMarkers(data);
                for (int i = 0; i < markers.size(); i++){
                    markers.get(i);
                    Driver driver = drivers.get(i);
                    map.setOnMarkerClickListener(marker -> {
                        // Get custom view
                        View v = getLayoutInflater().inflate(R.layout.driver_popup, null, false);

                        //Assign props
                        TextView username = v.findViewById(R.id.driver_username);
                        CircularImageView profile = v.findViewById(R.id.driver_profile);
                        ImageView status = v.findViewById(R.id.driver_status);
                        TextView shuttle = v.findViewById(R.id.driver_bus_number);
                        ViewGroup viewGroup = v.findViewById(R.id.group);

                        //Init props
                        Glide.with(getApplicationContext())
                                .load(driver.getProfile())
                                .apply(RequestOptions.circleCropTransform())
                                .apply(RequestOptions.placeholderOf(R.drawable.avatar_placeholder))
                                .apply(RequestOptions.errorOf(R.drawable.avatar_placeholder))
                                .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
                                .transition(withCrossFade())
                                .into(profile);

                        username.setText(driver.getDriver());   //Driver's username
                        shuttle.setText(driver.getCarNumber()); //Driver's car number

                        //Attach to dialog
                        Builder materialDialog = new Builder(HomeActivity.this)
                                .customView(v, true)
                                .negativeText("Dismiss")
                                .onPositive((dialog, which) -> {
                                    dialog.dismiss();
                                    enableTracking(marker);
                                })
                                .onNegative((dialog, which) -> dialog.dismiss());

                        if (driver.isStatus()) {
                            status.setImageResource(android.R.color.holo_green_light);  //Online

                            //Enable tracking when driver is online
                            materialDialog.positiveText("Track")
                                    .onPositive((dialog, which) -> {
                                        dialog.dismiss();
                                        enableTracking(marker);
                                    });
                        } else {
                            //Tracking is disabled
                            status.setImageResource(android.R.color.holo_red_light);    //Offline
                        }

                        materialDialog.build().show();
                        return true;
                    });

                }
            }
        }
    };

A: I invite you to read the official developer guide here. It explains how to properly use Dialogs, how to display a list in it, and even how to implement a custom view if you need one to display your list.


text:
Q: What is the "and" and "or" Operator in Kotlin? We all know that in Java, we use the && operator for "and" and || operator or "or". But when it comes to Kotlin, this doesn't work. When I was trying out a simple program, I noticed that the && operator in Kotlin was behaving like the || operator in Java using IntelliJ, I have no idea why.
while(day!=1 && month != 1 && year!= 0) {
    ...
    ...
}

When I debugged the program, I saw that when day = 1, month = 8, year = 1947, it jumped out of the loop.
I modified the code and debugged again, this time it jumped out when day = 31, month = 1, year = 1947.
So what exactly is the "and" and "or" operator in Kotlin?

A: To not jump out of the loop for day = 1, month = 8, year = 1947, the condition would have to be, for example:
while(day==1 && month != 1 && year!= 0) {
    ...
    ...
}

Your initial condition says = If "day" isn't 1 and "month" isn't 1 and "year" isn't 0, only then continue. So it works as intended since parameter "day" is actually 1, and breaks out of the loop. You should read up on negation and logic gates, it will help you understand programming better, since logic gates have been exactly the same for around 100 years.

A: There are two logical operators in Kotlin:

 || :true if either of the Boolean expression is true

and

 &&: true if all Boolean expressions are true

Note that, or and and are functions that support infix notations
.
Logical operators are used in control flow such as if expression, when expression, and loops.
For more information here


text:
Q: Show database details for item selected in spinner I am using a SimpleCursorAdapter to populate a Spinner with the name column from a database.
Adapter:
spinnerAdapter = new SimpleCursorAdapter(
        this,
        android.R.layout.simple_spinner_item,
        null,
        new String[] {SupplierEntry.COLUMN_SUPPLIER_NAME},
        new int[] {android.R.id.text1},
        0);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
mSuppliersSpinner.setAdapter(spinnerAdapter);

getLoaderManager().initLoader(SUPPLIERS_LOADER, null, this);

Cursor Loader:
@Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        // Define a projection that specifies the columns from the table we care about.
        String[] projection = {
                SupplierEntry._ID,
                SupplierEntry.COLUMN_SUPPLIER_NAME};

        // This loader will execute the ContentProvider's query method on a background thread
        return new CursorLoader(this,        // Parent activity context
                SupplierEntry.CONTENT_URI,   // Provider content URI to query
                projection,                  // Columns to include in the resulting Cursor
                null,                        // No selection clause
                null,                        // No selection arguments
                null);                       // Default sort order
    }

How could I, upon selecting an item in the spinner (the name column), show all the other details in some textviews ?

A: First, set a listener to the spinner so you get a callback when an item is selected.
mSuppliersSpinner.setOnItemSelectedListener(this);

I supply 'this' as listener because my Fragment / Activity implements the interface, but you can write one between the brackets as well.
You can implement this method:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
    //Start another cursorloader to get the details
}

Based on the id, or the position, you know which entry was selected. At this point you can start another CursorLoader (with a selection so you only get the details of this particular entry). When you get a callback in onLoadFinished, you can show the details in the TextViews.


text:
Q: ALSA, avoiding capture of sound before app starts I'm working on an app that captures audio using the ALSA API.
A tester of the app noticed the following behavior. If a sound is playing
just before the app starts, and then the app is started, that sound
is captured when snd_pcm_readi() is called. Any sound playing within
about a second before starting the app is captured in this way.
Is this behavior expected?
What I want the app to do is capture only the sound that occurs after the
application starts. How can I assure that happens (snd_pcm_drop(), maybe?).


text:
Q: How to make blocking call for Mono?(How to get token from ReactiveSecurityContextHolder in a syncronous way) My Task is - get JWT token.(all details are here How to get jwt token value in spring webflux? (to exchange it with Minio STS token))
But lets discard redundant details. In an nutshell:
I have a source code:
@GetMapping(..)
public void someEndpoint(...) {
    Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
        .map(securityContext -> securityContext.getAuthentication().getPrincipal());
    mono.block(); //<-- I need to get the result of Mono execution HERE at this thread in a blocking manner
     ...
}

And I get the error here:
block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-2

Because it is forbidden to use blocking calls in reactor and bla bla bla although in previous versions of reactor this code was working.
I started to looking for a solution of my issue and created 2 topics:

*

*How to get jwt token value in spring webflux? (to exchange it with Minio STS token)

*How to get raw token from ReactiveSecurityContextHolder?
I've got an advice to make blocking call in a way described here:
So my attempts are:
Attempt 1:
Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
            .map(securityContext -> securityContext.getAuthentication().getPrincipal());
Mono<Object> objectMono = mono.subscribeOn(Schedulers.boundedElastic());
Object result = objectMono.block();

Attempt 2:
Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
            .map(securityContext -> securityContext.getAuthentication().getPrincipal());
mono.subscribeOn(Schedulers.boundedElastic());
Object result = mono.block();

In both cases I receive the same error:
block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-2

How can I fix it ?
UPDATE 1:
Also I've found the similar topic with the same question but without any answer How do i extract information from Jwt which is stored in ReactiveSecurityContextHolder. It returns a Mono<String> but I need String
UPDATE 2:
All code snippets provided below lead to the same error (    block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-2
)
A)
Mono.just("qwerty")
.subscribeOn(Schedulers.boundedElastic())
.publishOn(Schedulers.boundedElastic())
.block()

B)
Mono<String> customMono = Mono.just("qwerty");
Mono<String> blockedMono = customMono
        .subscribeOn(Schedulers.boundedElastic())
        .publishOn(Schedulers.boundedElastic());
System.out.println("blockedMono.block(): " + blockedMono.block());

C)
 Mono<String> customMono = Mono.just("qwerty");
 Mono<String> blockedMono =  Mono.just(0)
            .subscribeOn(Schedulers.boundedElastic())
            .publishOn(Schedulers.boundedElastic())
            .then(customMono);

 System.out.println("blockedMono.block(): " + blockedMono.block());

A: subscribeOn only applies to the subscribe event, i.e. when you first add your subscription. Events are still published on the default Scheduler, in this case 'parallel'.
To be able to make blocking calls you need to publishOn a non-blocking Scheduler, so for instance:
Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
            .map(securityContext -> securityContext.getAuthentication().getPrincipal());
Mono<Object> objectMono = mono.subscribeOn(Schedulers.boundedElastic())
                              .publishOn(Schedulers.boundedElastic()); // <- this

Object result = mono.block();

should do the trick.
Edit:
In your case you should not call block directly within the method annotated with @GetMapping.
Consider doing this:
public MinioAsyncClient getOrCreateClientForPrincipal(Object Principal) {
    ...
}

@GetMapping(..)
public Mono<ResponseEntity<Boolean>> someEndpoint(...) {
    Mono<Boolean> mono = ReactiveSecurityContextHolder.getContext()
            .publishOn(Schedulers.boundedElastic()) //<-- this allows .block() somewhere downstream
            .subscribeOn(Schedulers.boundedElastic())
            .map(securityContext -> securityContext.getAuthentication().getPrincipal())
            .map(this::getOrCreateClientForPrincipal)
            .flatMap(asyncClient ->
                {
                    BucketExistsArgs args = ...;
                    try {
                        CompletableFuture<Boolean> existsQuery = asyncClient.bucketExists(args);
                        return Mono.fromFuture(existsQuery)
                             //allow Future to be cancelled if this Mono is cancelled
                             .doOnCancel(() -> existsQuery.cancel(true))
                             //unwrap CompletionException from the Future to its cause
                             .onErrorMap(CompletionException.class, e -> e.getCause())
                        ;
                        } catch(InsufficientDataException
                                | InternalException
                                | InvalidKeyException
                                | IOException
                                | NoSuchAlgorithmException
                                | XmlParserException e) {
                            //We need to catch these only because they're declared by MinioAsyncClient.
                            //they aren't actually thrown
                            return Mono.error(e);
                    }
                }
            )
            //error handling, adapt as necessary
            .onErrorReturn(InsufficientDataException.class, ...)
            .onErrorReturn(InvalidKeyException.class, ...)
            .onErrorReturn(IOException.class, ...)
            .onErrorReturn(NoSuchAlgorithmException.class, ...)
            .onErrorReturn(XmlParserException.class, ...)
        ;

    return mono.map(ResponseEntity::ok);

}

Notes:
The method is declared as returning Mono, since you are in a reactive context anyway. This makes it easier to return appropriately after processing, instead of using void and pretending to have a 'normal' context.
if getOrCreateClientForPrincipal takes 'longer', you could consider making it return Mono<MinioAsyncclient> and calling it with .flatMap.
Should you follow the suggestion in the other question of caching the client for each principal in order to avoid creation on each call, you can do it in this method. You will need to figure a way of cleaning up that cache, but that's beyond the scope of this answer.
Error handling:
MinioAsyncClient declares a bunch of Exceptions that it won't actually throw. These Exceptions can certainly be thrown within the Future and would be wrapped in a CompletionException, which the above code unwraps back to its source. It then provides for returning a default Boolean value for each exception, but here you can use the various .onError... methods to handle, propagate, etc.
You may even want to move them out one more level and handle on the outermost mono to map directly to an appropriate response code.
Note how there is no call to block() - it shouldn't really be needed, so in fact this may very well work without the calls to publishOn or subscribeOn...


text:
Q: Convert Unity Settings from binary to text Looks like in 2017.2 version Unity changed their Settings format from binary to text. At least, projects, created with Unity 2017.2.0f3, create PlayerSettings, QualitySettings etc. in text format.
Text compared to binary increases commits quality (you can now see a normal diff).
But project, created in Unity 5.6, opened in 2017.2, still shows Settings files in binary.
Is it a fast way to convert settings files to text?

A: I know that you used to be able to force text (things might have changed in 2017), which was especially useful for git merge conflicts. According to this blog, you can enable this by:

Edit > Project Settings > Editor menu and then under Asset
  Serialization Mode choose Force Text

This should make assets text only; however, I'm not sure this handles the specific setting files you were looking to convert.
The official unity documentation that covers this is here.