text:
Q: JavaScript Array Sorting/Ranking with Equal Ranks After sorting an array of objects based on of their property values ("rating" in this case), how do you associate ranks for each object if there are ties between some of these values? Here's an example:
//Should be tied for 1st Rank
var obj1 = {
  name: "Person1",
  rating: 99
}

//Should be 3rd Rank
var obj2 = {
  name: "Person2",
  rating: 50
}

//Should be 2nd Rank
var obj3 = {
  name: "Person3",
  rating: 98
}

//Should be 4th Rank
var obj4 = {
  name: "Person4",
  rating: 0
}

//Should be tied for 1st Rank
var obj5 = {
  name: "Person5",
  rating: 99
}

Here's as far as I got:
var clients = [obj1, obj2, obj3, obj4, obj5];
var sorted = [];

for (var i = 0; i < clients.length; i++) {
  sorted.push(clients[i]);
}

sorted.sort(function(a, b) {
  return b.rating-a.rating;
});

Ultimately, I'd like to be able to get the rank using the object name, like this:
alert(sorted.indexOf(obj5) + 1);

A: Created a solution that worked, albeit ugly. Thanks jamie for some framework used in this:
for (var i = 0; i < clients.length; i++) {
  sorted.push(clients[i]);
}

sorted.sort(function(a, b) {
  return b.rating-a.rating;
});

for(var i = 0; i < sorted.length; i++) {
    // original ranking
     sorted[i].rank = i + 1;
}

function sortRanking() {
  for (var k = 0; k < sorted.length; k++) {
    for (var h = 1; h < sorted.length + 1; h++) {
      if (sorted[k+h] !== undefined) {
        if (sorted[k+h].tie !== true) {
          if (sorted[k].rating === sorted[h + k].rating) {
            sorted[k].rank = k + 1;
            sorted[h + k].rank = k + 1;
            sorted[k].tie = true;
            sorted[h + k].tie = true;
          }
        }
      }
    }
  }
}

sortRanking();
alert("Rank: " + obj3.rank);

A: Using ES6, here's how you can do it, adding a property rank to every client. Try the code snippet below.

function setRanks(clients) {
    let currentCount = -1, currentRank = 0,
        stack = 1; // consecutive clients with same rating
    for (let i = 0; i < clients.length; i++) {
        const result = clients[i];
        if (currentCount !== result['rating']) {
            currentRank += stack;
            stack = 1;
        } else {
            stack++;
        }
        result['rank'] = currentRank;
        currentCount = result['rating'];
    }
}

// get the rank using the object name
function getRank(clientName) {
  return clients.find(c => c.name === clientName)['rank'];
}

//Should be tied for 1st Rank
var obj1 = {
  name: "Person1",
  rating: 99
}

//Should be 3rd Rank
var obj2 = {
  name: "Person2",
  rating: 50
}

//Should be 2nd Rank
var obj3 = {
  name: "Person3",
  rating: 98
}

//Should be 4th Rank
var obj4 = {
  name: "Person4",
  rating: 0
}

//Should be tied for 1st Rank
var obj5 = {
  name: "Person5",
  rating: 99
}

var clients = [obj1, obj2, obj3, obj4, obj5];

clients.sort((c, other) => other.rating - c.rating);
setRanks(clients);
console.log(clients);

console.log(getRank('Person5'));

A: 2nd attempt: although not quite there - i argue separating the ranking in to a different property rather than rely on the indexOf  to find ranking is the way to go. You then have something clearer to manipulate when there is a tie. Still working it. Will be watching for best solution
for(var i = 0; i < sorted.length; i++) {
    // original ranking
     sorted[i].rank = i + 1;

}
function sortRanking() {
  for(i=0; i< sorted.length; i++) {
    var current = sorted[i];
    var next = sorted[i + 1];

    if(next === undefined || next.rating !== current.rating) {
      console.log("we are done");
      return "done";
    }

    if(next.rating === current.rating) {

      for(var j = next + 1; j < sorted.length; j++) {
            sorted[j].rank = sorted[j-1].rank;
    }

    next.rank = current.rank;

}

}
}
sortRanking();
console.log(sorted);

1st attempt - After playing around with for a bit. Here is a solution adding from your original logic:
var clients = [o1, o2, o3, o4];
var sorted = [];

for (var i = 0; i < clients.length; i++)
sorted.push(clients[i]);

sorted.sort(function (a, b) {

return clients.rating - clients.rating;
});

function checkForTieAndRating(x) {

// x parameter for object of interest
// need to get the one in front to determine if it is tied
// get index of obj of interest
var indexOfInterest = clients.indexOf(x);
var indexOfBefore = indexOfCurrent -1;

// if obj of interest is ranked #1 then return
if(indexOfBefore < 0) {
return indexOfInterest + 1;
} else {
// get the actual object before this one so you can check rating. put in variable so you can compare.
var objBefore = clients[indexOfBefore];
var ratingOfObjBefore = objBefore.rating;
if(ratingOfObjBefore === x.rating)
  return "Tied for" + indexOfInterest;
 }

}

// check ranking and if tie
checkForTieAndRating(obj2);

// other issue going this route - would be to then 1) alter the objects ranking following the objs that are tied - to

//Possible alternative solution: After working and about to submit it - I think it would be better to add a ranking property after the sort and manipulate the rankings from there if there are any tied.

A: If you want several records on the same place, you should probably use an additional immediate array, effectively grouping the elements.
I will use lodash for convinience, you should get the idea.
_.chain(clients).groupBy('rating').pairs().sortBy(0).reverse().pluck(1).value();

You loose your ability to use indexOf at this point, so you need to write your own getRank.
Again, with the help of lodash
// returns zero when no rank is found
var getRank = function(sortedArray, object) {
    return 1 + _.findIndex(sortedArray, function(list) {
        return _.contains(list, object);
    });
};

Full working fiddle: http://jsfiddle.net/4WJN3/1/

A: I needed a similar piece of code for an operations scheduling script I was writing. I used objects and their properties/keys, which can have any value and can be accessed whenever needed. Also, as far as I read in some articles, the search of properties in objects can be faster than search in arrays.
The script below has three simple steps:

*

*sort the values (ascending or descending doesn't matter for the rest of the script)

*find the ranks and number of occurrences for each value

*replace the given values with ranks using the data from step 2
Note! The below script will not output duplicate ranks, but instead increments ranks for duplicate values/elements.
function rankArrayElements( toBeRanked ) {

// STEP 1
var toBeRankedSorted = toBeRanked.slice().sort( function( a,b ) { return b-a; } ); // sort descending
//var toBeRankedSorted = toBeRanked.slice().sort( function( a,b ) { return a-b; } ); // sort ascending

var ranks = {}; // each value from the input array will become a key here and have a rank assigned
var ranksCount = {}; // each value from the input array will become a key here and will count number of same elements

// STEP 2
for (var i = 0; i < toBeRankedSorted.length; i++) { // here we populate ranks and ranksCount
    var currentValue = toBeRankedSorted[ i ].toString();

    if ( toBeRankedSorted[ i ] != toBeRankedSorted[ i-1 ] ) ranks[ currentValue ] = i; // if the current value is the same as the previous one, then do not overwrite the rank that was originally assigned (in this way each unique value will have the lowest rank)
    if ( ranksCount[ currentValue ] == undefined ) ranksCount[ currentValue ] = 1; // if this is the first time we iterate this value, then set count to 1
    else ranksCount[ currentValue ]++; // else increment by one
}

var ranked = [];

// STEP 3
for (var i = toBeRanked.length - 1; i >= 0; i--) { // we need to iterate backwards because ranksCount starts with maximum values and decreases
    var currentValue = toBeRanked[i].toString();

    ranksCount[ currentValue ]--;
    if ( ranksCount[ currentValue ] < 0 ) { // a check just in case but in theory it should never fail
        console.error( "Negative rank count has been found which means something went wrong :(" );
        return false;
    }
    ranked[ i ] = ranks[ currentValue ]; // start with the lowest rank for that value...
    ranked[ i ] += ranksCount[ currentValue ]; // ...and then add the remaining number of duplicate values
}

return ranked;}

I also needed to do something else for my script.
The above output has the following meaning:

*

*index - the ID of the element in the input array

*value - the rank of the element from the input array
And I needed to basically 'swap the index with the value', so that I have a list of element IDs, arranged in the order of their ranks:
function convertRanksToListOfElementIDs( ranked ) {  // elements with lower ranks will be first in the list

var list = [];

for (var rank = 0; rank < ranked.length; rank++) { // for each rank...
    var rankFound = false;
    for (var elementID = 0; elementID < ranked.length; elementID++) { // ...iterate the array...
        if ( ranked[ elementID ] == rank ) { // ...and find the rank
            if ( rankFound ) console.error( "Duplicate ranks found, rank = " + rank + ", elementID = " + elementID );
            list[ rank ] = elementID;
            rankFound = true;
        }
    }
    if ( !rankFound ) console.error( "No rank found in ranked, rank = " + rank );
}

return list;}

And some examples:
ToBeRanked:
[36, 33, 6, 26, 6, 9, 27, 26, 19, 9]
[12, 12, 19, 22, 13, 13, 7, 6, 13, 5]
[30, 23, 10, 26, 18, 17, 20, 23, 18, 10]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
[7, 7, 7, 7, 7, 2, 2, 2, 2, 2]
[2, 2, 2, 2, 2, 7, 7, 7, 7, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
rankArrayElements( ToBeRanked ):
[0, 1, 8, 3, 9, 6, 2, 4, 5, 7]
[5, 6, 1, 0, 2, 3, 7, 8, 4, 9]
[0, 2, 8, 1, 5, 7, 4, 3, 6, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
convertRanksToListOfElementIDs( rankArrayElements( ToBeRanked ) ):
[0, 1, 6, 3, 7, 8, 5, 9, 2, 4]
[3, 2, 4, 5, 8, 0, 1, 6, 7, 9]
[0, 3, 1, 7, 6, 4, 8, 5, 2, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

A: function rank(arr) {
    var ret = [];
    var s = [];
    var i = 0;
    var _key_;
    for (_key_ in arr) {
        var v;
        v = arr[_key_];
        if (!s[v]) {
            s[v] = ++i;
        }
        ret.push( {
            'Mark': v,
            'Rank': s[v]
        });
    }
    return ret;
}
var marks = [
    65,
    41,
    38,
    38,
    37,
    37,
    92,
    84,
    84,
    84,
    83
];
marks.sort(function(a, b) {
  return b-a;
});
var rank = rank(marks);
 console.log(rank);

A: Concise, efficient, flexible.
Items with same score have same ranks, yet the next different score get a rank shifted by n (based on index). Input must be a array sorted by values of the sourceColumn. Two versions of the code, pick the one you like :

*

*for(){ } loop

*array.map()

var studentsSortedByGrades = [
  { name: "A", grade: 5 },
  { name: "B", grade: 3 },
  { name: "C", grade: 3 },
  { name: "D", grade: 2 },
];

var addRankFORLOOP = function(sortedArr,sourceColumn,newColumn){
  for(var i = 0; i<sortedArr.length; i++){ //
    sortedArr[i][newColumn] =
      i===0 || sortedArr[i][sourceColumn] !== sortedArr[i-1][sourceColumn]  ? i+1 // anytime new grade appears, rank=i
        : sortedArr[i-1][newColumn] // elseIf: equal grade, then equal rank
  }
  return sortedArr;
};

/*//OR
var addRankMAP = function(sortedArr,sourceColumn,newColumn){
  return sortedArr.map((item,i) => {
    item[newColumn] = i===0 || sortedArr[i][sourceColumn] !== sortedArr[i-1][sourceColumn]  ? i+1 // anytime new grade appears, rank=i
        : sortedArr[i-1][newColumn] // elseIf: equal grade, then equal rank
    return item; })
}; /**/
var withRanks = addRankFORLOOP(studentsSortedByGrades,'grade','rank');
console.log(withRanks) // ranks: 1,2,2,4


text:
Q: Проблема с отладкой: No local changes, not deploying APK Could not identify launch Студия видит внешнее устройство, даже она смогла загрузить туда приложение сама,
но отладчик выдает такую ошибку:

No local changes, not deploying APK Could not identify launch
  activity: Default Activity not found Error while Launching activity

A: У вас не указан Intent Filter
 <intent-filter>
            <category android:name="android.intent.category.LAUNCHER"/>
            <action android:name="android.intent.action.MAIN"/>
        </intent-filter>

Примерно так, в манифесте к активити

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eliminar estilo css desde vuejs? Al cargar la pagina se me ve el div con una altura muy larga por unos segundos, por lo que decidi darle una altura estatica y al cargar los elementos esta altura (height) eliminarse en el css, pero no logro hacerlo o no se como definir desde vuejs el valor de la variable para que esta se aplique en el css, aqui el codigo:

                    <button type="button" @click="anchura"> anchura</button>
                    Select room:
                    <select v-model="room" @change="selectRoom"><option value="22">22</option><option value="34">34</option><option value="139">139</option><option value="158">158</option></select>
                    <button>Back</button>

There's no previous product made in this room.

js:
computed: {
    computed: function() {
        return this.width;
    },
    computed_show_current_products: function() {
        return this.visibility;
    }
},
methods: {

    selectRoom: function() {
        axios.post("index.php?url=get_busyroom", {'room':this.room}).then((response)=>{ //GOES TO GET_BUSYROOM LINE 32 IN WEB.PHP
            if (response.data.length > 0) {
                this.anchura = "null";
                this.visibility = "visible";
                this.message = "Room busy! Finish it first."
                this.hide = false;
                this.currentproduct = response.data;
                this.showcurrentProduct = true;
                this.showpreviousProduct = false;
                this.packagenewProduct = false;
            }else {
                this.showlastProduct(this.room);
            }

css:
#start_packing {
    width: 400px;
    background:rgba(0, 149, 144, 0.8);
    padding: 20px;
    margin: auto;
    margin-top: 80px;
    border-radius: 4px;
    color: white;
    height: 70px;
}

A: Entiendo que ya pasaron varios meses de la pregunta, pero podrías jugar un poco con el ciclo de carga de vue y variables de visualización. Puedes crear un variable "loaded" que por default esté en false
data(){
  return {
    loaded: false

En tu función donde mandas llamar axios, cambiarla a true cuando ya tengas los datos
axios.post("index.php?url=get_busyroom", {'room':this.room}).then((response)=>{ //GOES TO GET_BUSYROOM LINE 32 IN WEB.PHP
            if (response.data.length > 0) {
                this.anchura = "null";
                this.visibility = "visible";
                this.message = "Room busy! Finish it first."
                this.hide = false;
                this.currentproduct = response.data;
                this.showcurrentProduct = true;
                this.showpreviousProduct = false;
                this.packagenewProduct = false;
                this.loaded = true
            }else {
                this.showlastProduct(this.room);
            }

Y en la vista solo mostrar el div si loaded es true


text:
Q: Room is not frozen yet? The main chatroom for EOS.IO got deleted automatically (Which itself is not suppose to happen because it's a mainroon that suppose to have an auto freeze/deletion protection.), so I created a new room that is  here with the same name and description as the original main room for a replacement I creating a replacement instead of contacting a mod to undelete the original one was just me experimenting, just in case you ask why?
After some days of not having any messages the room is still not frozen yet, now yes Stack Exchange is posting messages there, but that doesn't count as said by an official person I even saw rooms get frozen even with Stack Exchange posting in them. The last message from a normal user was 35 days ago.
Why is this room I created not frozen yet? Have I managed to fool the system to think that my replacement main room is the real main room?
Also check this out it has no  active feeds and it's not a main room.

A: TL;DR: No bug here, just sequence of rare corner cases, as far as I can tell.

The freeze/delete protection takes place only when there is one single room for a site.
As can be seen in the list of rooms including frozen/deleted, when the main room was deleted in July 28 (2018), this room (10k only) existed and was unfrozen and active, thus became the "main" room.
Now why that other room got deleted in August 23? Because this room existed and was active.
Now... what that other room did not get the auto protection? Because it's a "one on one" room, which has different logic behind the scenes, making it "secondary" to the ordinary chat rooms.


text:
Q: Distinct integer solutions to the equation $(x^2+y^2+z^2)/(x+y+z)=2n$ I've been set this problem by my teacher, and had no idea where to start. I have a Diophantine equation:
$$
\frac{x^2+y^2+z^2}{x+y+z}=2n
$$
$x, y, z$ and $n$ must be distinct positive integers. I've found solutions where there is an equality for any of $x, y$ and $z$ but I haven't been able to for distinct positive integers, and would appreciate help.

A: This one is quite difficult; at least, difficult to find all primitive integer solutions and prove that we have all. Taking $a=x-n,b=y-n,c=z-n,$ we are led to
$$ a^2 + b^2 + c^2 = 3n^2. $$
In order to get $\gcd(a,b,c,n)=1,$  it is necessary that all be odd.
I think I will leave in the zeros in the formulas for $a,b,c.$ They serve as spacers.
$$ n = p^2 + q^2 + r^2 + s^2 $$
$$ a = p^2 + q^2 - r^2 - s^2 + 0 \, p  q - 2  p  r + 2  q  r + 2  p  s + 2  q  s + 0  \,  r  s $$
$$ b = p^2 - q^2 + r^2 - s^2 + 2  p  q - 0  \,  p  r + 2  q  r - 2  p  s + 0  \,  q  s + 2  r  s$$
$$ c = p^2 - q^2 - r^2 + s^2 - 2  p  q + 2  p  r + 0  \,  q  r + 0  \,  p  s + 2  q  s + 2  r  s$$
In the table below, for each line just take the eight solutions $x=n \pm a, y=n \pm b,z=n \pm c.$ Some of those will have $x,y,z$ positive.
=========================
    n       x    y    z                                         p    q    r    s
    1 ;     2    2    2 x^2+y^2+z^2: 12 x+y+z: 6 * 2n: 12 ;     1    0    0    0
    3 ;     8    4    4 x^2+y^2+z^2: 96 x+y+z: 16 * 2n: 96 ;     0    1   -1   -1
    5 ;    12   10    6 x^2+y^2+z^2: 280 x+y+z: 28 * 2n: 280 ;     0    1    0   -2
    7 ;    18   12    8 x^2+y^2+z^2: 532 x+y+z: 38 * 2n: 532 ;     1    2    1    1
    9 ;    20   20   10 x^2+y^2+z^2: 900 x+y+z: 50 * 2n: 900 ;     0    2    2    1
    9 ;    22   16   14 x^2+y^2+z^2: 936 x+y+z: 52 * 2n: 936 ;     0    2   -1   -2
   11 ;    24   24   16 x^2+y^2+z^2: 1408 x+y+z: 64 * 2n: 1408 ;     0    1    1   -3
   11 ;    28   18   16 x^2+y^2+z^2: 1364 x+y+z: 62 * 2n: 1364 ;     3    1    0    1
   11 ;    30   12   12 x^2+y^2+z^2: 1188 x+y+z: 54 * 2n: 1188 ;     3    0   -1    1
   13 ;    30   26   20 x^2+y^2+z^2: 1976 x+y+z: 76 * 2n: 1976 ;     0    2    0   -3
   13 ;    32   24   18 x^2+y^2+z^2: 1924 x+y+z: 74 * 2n: 1924 ;     2   -2   -2   -1
   15 ;    34   32   20 x^2+y^2+z^2: 2580 x+y+z: 86 * 2n: 2580 ;     3    2    1    1
   15 ;    38   26   20 x^2+y^2+z^2: 2520 x+y+z: 84 * 2n: 2520 ;     1   -1    3   -2
   15 ;    40   22   16 x^2+y^2+z^2: 2340 x+y+z: 78 * 2n: 2340 ;     1   -3   -2   -1
   17 ;    40   30   30 x^2+y^2+z^2: 3400 x+y+z: 100 * 2n: 3400 ;     0    3   -2   -2
   17 ;    40   34   24 x^2+y^2+z^2: 3332 x+y+z: 98 * 2n: 3332 ;     4    0   -1    0
   17 ;    42   28   28 x^2+y^2+z^2: 3332 x+y+z: 98 * 2n: 3332 ;     0    3    2    2
   17 ;    46   22   18 x^2+y^2+z^2: 2924 x+y+z: 86 * 2n: 2924 ;     3   -2   -2    0
   19 ;    42   42   24 x^2+y^2+z^2: 4104 x+y+z: 108 * 2n: 4104 ;     1   -3    3    0
   19 ;    44   36   32 x^2+y^2+z^2: 4256 x+y+z: 112 * 2n: 4256 ;     0    3   -1   -3
   19 ;    48   30   30 x^2+y^2+z^2: 4104 x+y+z: 108 * 2n: 4104 ;     1    0    3   -3
   19 ;    50   30   20 x^2+y^2+z^2: 3800 x+y+z: 100 * 2n: 3800 ;     1    1    1   -4
   21 ;    46   44   34 x^2+y^2+z^2: 5208 x+y+z: 124 * 2n: 5208 ;     0    2    1   -4
   21 ;    50   40   32 x^2+y^2+z^2: 5124 x+y+z: 122 * 2n: 5124 ;     2    3    2    2
   21 ;    52   40   22 x^2+y^2+z^2: 4788 x+y+z: 114 * 2n: 4788 ;     4    2    0    1
   23 ;    52   48   34 x^2+y^2+z^2: 6164 x+y+z: 134 * 2n: 6164 ;     1   -3   -3   -2
   23 ;    54   48   24 x^2+y^2+z^2: 5796 x+y+z: 126 * 2n: 5796 ;     3   -2   -3   -1
   23 ;    58   42   24 x^2+y^2+z^2: 5704 x+y+z: 124 * 2n: 5704 ;     1   -3    3    2
   23 ;    60   36   30 x^2+y^2+z^2: 5796 x+y+z: 126 * 2n: 5796 ;     3    3    1    2
   25 ;    56   50   42 x^2+y^2+z^2: 7400 x+y+z: 148 * 2n: 7400 ;     0    3    0   -4
   25 ;    60   44   42 x^2+y^2+z^2: 7300 x+y+z: 146 * 2n: 7300 ;     4   -2   -2   -1
   25 ;    60   48   36 x^2+y^2+z^2: 7200 x+y+z: 144 * 2n: 7200 ;     1   -2    4   -2
   25 ;    66   38   30 x^2+y^2+z^2: 6700 x+y+z: 134 * 2n: 6700 ;     1    4    2    2
   25 ;    68   30   26 x^2+y^2+z^2: 6200 x+y+z: 124 * 2n: 6200 ;     2   -1    4   -2
    n      x    y    z                                                p    q    r    s

==========================

A: There are infinitely many non-trivial solutions $x=y=z$ with $x$ even and $n=\frac{x}{2}$:
$$
\frac{x^2+y^2+z^2}{x+y+z}=\frac{3x^2}{3x}=x=2n.
$$
So they cannot be unique.
Edit: The title now says distinct integer solutions (in the body it is still says unique integer solutions. In this case consider, for example,
$$
(x,y,z,n)=(18,12,8,7).
$$
This solves your equation in distinct integers.

A: Above equation shown below:
\begin{equation}
(x^2+y^2+z^2)/(x+y+z)=2n  \tag{A}
\end{equation}
Equation $(A)$ has parametric solution:
$x=b(a+b)$
$y=a(7a+b)$
$z=2ab$
$n=(1/2)*(7a^2-2ab+b^2)$
For $(a,b)=(1,17)$ we get:
$(x,y,z,n)= (306,24,34,131)$


text:
Q: how to resize navbar differently on different screens when scrolling I want to resize my navbar differently on different window sizes, but when I use the following code to do so, when I scroll back up on a mobile device, the size of the navbar becomes what it is supposed to be on the desktop version on scrolling back up (second elseif statement). How do I make the conditioning so that when I scroll back up, the navbar resizes according to the 4th case , which is for mobiles.
function scrollFunction() {
      if (
        window.innerWidth>815 &&
        document.body.scrollTop > 80 ||
        document.documentElement.scrollTop > 80
      ) {
        document.getElementById("navbar").style.padding = "30px 50px";
        document.getElementById("logo").style.fontSize = "32px";
      } else if (
        window.innerWidth>815 &&
        document.body.scrollTop < 80 ||
        document.documentElement.scrollTop < 80 )
         {
        document.getElementById("navbar").style.padding = "60px 50px";
        document.getElementById("logo").style.fontSize = "38px";
      }
      else if(
        widnow.innerWidth<815 &&
        document.body.scrollTop > 80 ||
        document.documentElement.scrollTop > 80
      ){
        document.getElementById("navbar").style.padding = "30px 40px";
        document.getElementById("logo").style.fontSize = "32px";
      }
      else if (
        window.innerWidth<815 &&
        document.body.scrollTop < 80 ||
        document.documentElement.scrollTop < 80
      ){
        document.getElementById("navbar").style.padding = "30px 40px";
        document.getElementById("logo").style.fontSize = "32px";
      }
    }

A: && has precedence over ||. So I think given your set of conditions, the last two conditions are less likely to get invoked.
Try
if (
        window.innerWidth>815 &&
        (document.body.scrollTop > 80 ||
        document.documentElement.scrollTop > 80)
      ) {

instead
if (
        window.innerWidth>815 &&
        document.body.scrollTop > 80 ||
        document.documentElement.scrollTop > 80
      ) {

on all your if and else if conditions.
Also, for tasks like this, I would urge you to look into media queries.


text:
Q: What is correct : $n^{\mathcal{O}(1)} = \mathcal{O}(n^{logn})$ or $n^{\mathcal{O}(1)} = \mathcal{o}(n^{logn})$ I cannot really understand what is right: $$n^{\mathcal{O}(1)} = \mathcal{O}(n^{logn})$$ or $$n^{\mathcal{O}(1)} = \mathcal{o}(n^{logn})$$
I know that Little-oh notation means

For every choice of a constant k > 0, you can find a constant a such that the inequality f(x) < k g(x) holds for all x > a.

and Big-Oh

For at least one choice of a constant k > 0, you can find a constant a such that the inequality f(x) < k g(x) holds for all x > a.

But, it is not clear for me haiving
 $n^{\mathcal{O}(1)}$ and $(n^{logn})$ because whether  $n^{\mathcal{O}(1)} < n^{logn}$ or $n^{\mathcal{O}(1)} > n^{logn}$ only matters on $n$ itself and the actual exponent of $n$.
Like $2^{1000} > 2^{log2}$ but as n grows $n^{logn}$ will become larger. Etc. So it may be that
$$n^{\mathcal{O}(1)} < n^{logn}$$
or
$$n^{\mathcal{O}(1)} > n^{logn}$$
or
$$n^{\mathcal{O}(1)} = n^{logn}$$
But $n^{logn}$ grows asymptotically faster.
So, are we dealing with big or little oh?

A: $n^{(O(1))}$ is actually both $O(n^{log(n)})$ and $o(n^{log(n)})$. Note that $o(n^{log(n)})$ is the stronger upper bound. In other words, $f(x) = o(n^{log(n)}) \implies f(x) = O(n^{log(n)})$.
Note that any function in $O(1)$ must be a constant. Denote that constant by $c$. We want to show that for any choice of $k > 0$, we can find a constant $a$ such that $n^c < k*n^{log(n)}$ for all $n > a$. Note that there exists a constant $e$ such that $n^e > 1/k$ for all k as long as $n>1$, since k is a constant. Consider selecting an $a$ such that $log(a) > c + e$. Then whenever $n > a$, $k*n^{log(n)} > k*n^{c+e} > n^c$. Thus, $n^{O(1)} = o(n^{log(n)})$, and it follows that $n^{O(1)} = O(n^{log(n)})$.
When proving these things, it is important to realize that you are trying to compare functions when the inputs get arbitrarily large. Sure, $2^{1000} > 2^{log(2)}$, but this does not say much about the relative growth rates of the function in general. The definitions of big-O and little-O seek to reach this sort of generalization when it comes to function growth comparisons.


text:
Q: error compiling opencv example I am trying to compile an example that is provided for one of the opencv_contrib modules (text detection module). The link is below:
https://github.com/Balaje/opencv-1/blob/master/samples/cpp/textdetection.cpp
I keep getting errors like:  error: 'ERStat' was not declared in this scope
I have already compiled and installed opencv_contrib modules and I see text.hpp in /usr/local/include/opencv2. I included text.hpp as well, but I got the same errors. Does anybody know how I can fix the problem?
I compile the file with the following command:
g++ pkg-config --cflags opencv -o textdetection textdetecti
on.cpp pkg-config --libs opencv

A: Try replacing all ERStat in the code with cv::text::ERStat. It should solve the problem.


text:
Q: Edit and update same textbox I have a database Table where I can edit a value. I want to update the same, below is the code that I have tried.
The table code is as below

        DBID
        Query Raised
        Time Raised
        Query Answered
        Time Answered

<%
try {
    ps = con.prepareStatement("Select DBID, Query_Raised, TR, Query_Answered, TA from Scope1 where TR!='null'");

    rs = ps.executeQuery();

    while(rs.next()) {
%>

        <%=rs.getString("DBID")%>
        <input type="Text" value="<%=rs.getString("Query_Raised")%>" name="Updat">
        <%=rs.getString("TR")%>
        <%=rs.getString("Query_Answered")%>
        <%=rs.getString("TA")%>
        <input type="Submit" value="Update">

<%
    } // while loop ends here

    rs.close();
    con.close();
} catch(Exception e) {
    out.println(e);
}
%>

and the update query that is used is:
String a = request.getParameter("Updat");

ps = con.prepareStatement("Update Scope1 Set Query_Raised = '" + a + "'");

int i = ps.executeUpdate();

if(i == 1) {
    out.print("Done");
} else{
    out.print("Erro");
}

I wanted to know the where condition that I should use to update the data in same page.
Thanks

A: I understand the first code part in the question is a JSP say update.jsp and the second part  it seems is your servlet, say UpdateServlet.
So in your update.jsp on every row you have an <input type="text"> and submit button, but the <form> I think is only one which must be outside the
, so here goes my solution (choose any one):

*

*Use multiple <form> tags for each row, like
<form action="whatever_action_you_have_which_calls_the_servlet"
      name="form<%=rs.getString("DBID")%>"
      id="formID<%=rs.getString("DBID")%>">
   // Including name and id so that the different forms remain unique

        <%=rs.getString("DBID")%>
        <input type="Text" value="<%=rs.getString("Query_Raised")%>" name="Updat">
        <%=rs.getString("TR")%>
        <%=rs.getString("Query_Answered")%>
        <%=rs.getString("TA")%>
        <input type="Submit" value="Update">

</form>

So when you click on submit it would submit the <form> for which the submit button was clicked and would submit only the input which was edited and voila! your servlet code also works fine.

*You can have both the blocks of code in the same JSP, then use the <form> code snippet as described in point#1 and the second code snippet would be:
String a = request.getParameter("Updat");

if ( (a is not empty) or (a is not null)  ) {
    ps = con.prepareStatement("Update Scope1 Set Query_Raised = '" + a + "'");

    int i = ps.executeUpdate();

    if(i == 1) {
        out.print("Done");
    } else{
        out.print("Error");
    }
}

...

<form action="whatever_action_you_have_which_will_call_this_JSP" ...>

 ... your code as in point#1

</form>

*Use ajax and other javascript DOM manipulative methods to accomplish this as said by Endy.
For this you will need to have JSP (to display) & Servlet (to update the code).
This might be a little more effort but you will learn Ajax and will be a little more close to real world.
By far jQuery ajax is the simplest to use.
Note:
Just for the record, I know you might be practicing but if you are planning to use it in a real project then please read ahead.
It is a bad-practice to use scriptlets in JSP (unless really required and that too if it is for view-level logic and not business or data-level logic) and even worse is to use JDBC code inside a JSP. So it would be really great if you could follow f_puras's advice.
If you are wondering why I should listen to your unsolicited advice then here is some food for thought:

*

*How to avoid scriptlets in JSP

*Scriptless JSPs

*Why JSP = JDBC is bad
Hope this helps.

A: You can either use AJAX to post the data to a page that handles the updating, then return the result as a callback, see http://api.jquery.com/jQuery.post/.
Other solution is to forward user back to the page with the form after you have processed the submission.
Third solution is to submit the data to the same page and parse/update it there.


text:
Q: Select all orders which have the same order items I need to fetch all orders which have the same cart (same list of order items and quantity).
Here are my tables:
orders (I think columns are not important, the primary key is id)
| id |
| -- |
| 1  |
| 2  |
| 3  |
| ... |

order_items

id
order_id
product_id
quantity

1
100
1
20.00

2
100
2
22.00

3
107
1
20.00

4
110
1
20.00

5
110
2
22.00

...
...
...
...

My goal is to use SQL to get orders 100 and 110 in this case. (They need to have the same rows containing the same product_id and quantity so order items number can vary, this is just an example). As you can see order 107 have the same order item but it's missing product id 2 with the quantity of 22.00 so it doesn't need to be included.
It's important to mention that this table will be large and probably it will contain 1M+ rows, maybe even more.
The ultimate goal is to have those groups of orders, for example, [100-110] but in reality, it would be like [100-110-...-n, x-y-z-...-n, ...]. The number of the same orders is not limited, that's why I used n in the example. My example only contains 2 orders that are the same.
The only thing I have achieved so far is to get the first group of orders with the query I've found on Stackoverflow:
SELECT DISTINCT O2.id
FROM orders O1
         INNER JOIN order_items I1 ON O1.id = I1.order_id
         INNER JOIN order_items I2 ON I1.product_id = I2.product_id AND I1.quantity = I2.quantity
         INNER JOIN orders O2 ON O2.id = I2.order_id
WHERE O1.id =
      (SELECT id FROM orders ORDER BY created_at LIMIT 1)
  AND (SELECT COUNT(*) FROM order_items WHERE order_id = O1.id)
    = (SELECT COUNT(*) FROM order_items WHERE order_id = O2.id)
ORDER BY O2.id;

I tried to change it in order to return all orders but with no luck.

A: WITH
cte AS (
    SELECT order_id,
           GROUP_CONCAT(product_id, quantity ORDER BY product_id, quantity) order_content
    FROM order_items
    GROUP BY 1
)
SELECT t1.order_id, t2.order_id
FROM cte t1
JOIN cte t2 USING (order_content)
WHERE t1.order_id < t2.order_id;

https://dbfiddle.uk/-mMek3QT

A: I believe all you need to do is use a window function to COUNT() how many products there are in every order, then join it to itself by product_id, quantity, and that product_count. That'll get you potential matches (which would include subset matches like two different orders with the same counts but each have one different product). Then with a window function again count how many rows actually matched between two orders and if the count of the matched rows is the same as the count of products in those orders then you know it's an exact match.
Something like this may work:
WITH order_items_counted AS
(
    SELECT
        id,
        order_id,
        product_id,
        quantity,
        COUNT(product_id) OVER (PARTITION BY order_id) AS product_count -- Counts how many products are in each order
    FROM order_items
),
potential_matches AS
(
    SELECT DISTINCT
        O1.order_id,
        O1.product_count,
        COUNT(O1.id) OVER (PARTITION BY O1.order_id, O2.order_id) AS matched_row_count -- Counts how many order_line rows matched
    FROM order_items_counted AS O1
    INNER JOIN order_items_counted AS O2
        ON O1.order_id <> O2.order_id -- Different Orders
        AND O1.product_count = O2.product_count -- With the same # of Products
        AND O1.product_id = O2.product_id -- Which are the same Products
        AND O1.quantity = O2.quantity -- With the same Quantities
)

-- Finally get the exact matches by filtering out any partial matches (the matched row count <> the product count)
SELECT DISTINCT
    order_id
FROM potential_matches AS exact_matches
WHERE product_count = matched_row_count

I don't have a way to test it at the moment, so please let me know if you have any issues and I'll address them accordingly.


text:
Q: How Many Three-Digits Even Numbers Can Be Formed From 2,4,5 Question:
I was wondering how many $3$-Digits Even Numbers can be formed from $2,4,5$ ?
My Approach:
If we take even number $2$ at extreme right _ _ $2$ then 2 permutations can formed from remaining numbers i.e ($4,5$), similarly if we take $4$ at extreme right _ _ $4$ then again 2 permutations will be formed. So,
$2!+2!=6$
Is my answer correct? because according to my teacher it should be 18.
Conclusion:
Help will be highly appreciated and i want the clear method to solve questions of this kind in which any number digits either even or odd can be formed using any given numbers.
P.S.(Sorry for Bad English)
Thanks,

A: let's the number is $\,\overline{abc} \,$ with $ a,b,c \in \{ 2,4,5\} $ and $c\in \{2,4\}$ ( because $\,c\,$ is the even number).We have
a has three choices, b has three choices and c has two choices. Therefore, we have $3*3*2=18 $ numbers satisfies the problem.


text:
Q: C++ error: expected unqualified-id before 'else' #include <fortran.h>

real function f() code
    return 0.0;
endfunction

program(main)
    if 3 == 3 then
        print(*) "Your PC is fine.";
    elseif 3 == 4 then
        print(*) "Your PC is broken.";
    else
        print(*) "Your PC is trash.";
    endif

    write(*, "(I)") 5);
end

I get the error expected unqualified-id before 'else' in line number 10. I don't know why.
And in line number 16, the program should write '5' on the screen, but I get a runtime error.
Also, C++ is a case sensitive language, is there a way not to make C++ case sensitive?
FORTRAN.H is:
#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#define IF if(
#define THEN ){
#define ELSEIF } else if(
#define ELSE }else{
#define ENDIF }
#define if IF
#define then THEN
#define elseif ELSEIF
#define else ELSE
#define endif ENDIF
#define PROGRAM(x) main(){
#define program PROGRAM
#define END }
#define end END
#define STOP exit(0);
#define stop STOP
#define call
#define subroutine
#define recursive
#define function
#define FOR for(
#define for FOR
#define LOOP ){
#define loop LOOP
#define ENDFOR }
#define endfor ENDFOR
#define WHILE while(
#define DO ){
#define ENDDO }
#define enddo ENDDO
#define PRINT(t) std::cout<<
#define _ <<
#define READ std::cin>>
#define $ >>
#define Read READ
#define read READ
#define Print PRINT
#define print PRINT
#define selectcase(x) switch(x){
#define endselectcase }
#define endfunction }
#define code {
typedef char character;
typedef int integer;
typedef double doubleprecision;
typedef float real;

char* function __FORTRAN_WRITE_ARGS(const char* f) code
    integer i;
    std::__cxx11::string arg = "";

    if f[0] != '(' || f[strlen(f)-1] != ')' then
        return "";
    endif

    for i = 0; i < strlen(f); i++ loop
        selectcase(f[i])
            case ' ':
                continue;
                break;
            case '(':
                continue;
                break;
            case ')':
                continue;
                break;
            case ',':
                continue;
                break;
            case 'I':
                if f[i+1] >= 48 && f[i+1] <= 57 then
                    arg += "%";
                    arg += f[i+1];
                    arg += "d";
                else
                    arg += "%d";
                endif

                break;
            default:
                continue;
        endselectcase
    endfor
    char retval[arg.length()] = "";
    strcat(retval, arg.c_str());
    return retval;
endfunction
#define write(t, f) printf(__FORTRAN_WRITE_ARGS(f),
#define endwrite )
#define WRITE write
#define precision

Is there any way to fix this issue or this error?

A: While I like the idea of the project, the implementation is currently flawed and I am unsure you will ever be able to get a 100% conversion. fortran.h uses some old, deprecated practices and contains two actual compile errors.
The main issue (why you asked the question) is plain to see when you run the code through the pre-processor.
int main(){
    if( 3 == 3 ){
        std::cout<< "Your PC is fine.";
    } }else{ if(( 3 == 4 ){  // *** The issue you're having ***
        std::cout<< "Your PC is broken.";
    }else{
        std::cout<< "Your PC is trash.";
    }

    printf(__FORTRAN_WRITE_ARGS("(I)"), 5);
}

The ELSEIF (I eliminated most lowercase variations) gets substituted, but not the way you want. ELSEIF makes its substitution, but then you had done #define else ELSE and #define if IF. That obviously clashes with real C++ and you were making double substitutions which were creating broken code.
Below is my modified fortran.h and main.cpp. It will be worth running a diff on my fortran.h to see exactly what changes I made. It now compiles, but it's still broken. It prints garbage after saying that my computer is fine. I poked around on your WRITE function, but in order to preserve your syntax (which might be incorrect, I don't know Fortran but the '()' don't match up), I couldn't come up with anything reasonable. It will likely need nested macro calling. One to generate the string, and another to actually substitute the string into the printf statement. In figuring this out, the pre-processor only flag, -E, will be your friend to see if the substitutions you are attempting are working.
fortran.h
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>

#define IF if(
#define THEN ){
#define ELSEIF } else if(
#define ELSE }else{
#define ENDIF }
#define PROGRAM(x) int main(){
#define program PROGRAM
#define END }
#define end END
#define STOP exit(0);
#define stop STOP
#define call
#define subroutine
#define recursive
#define function
#define FOR for(
#define LOOP ){
#define ENDFOR }
#define WHILE while(
#define DO ){
#define ENDDO }
#define PRINT(t) std::cout<<
#define _ <<
#define READ std::cin>>
#define $ >>
#define selectcase(x) switch(x){
#define endselectcase }
#define endfunction }
#define CODE {
typedef char character;
typedef int integer;
typedef double doubleprecision;
typedef float real;

char* function __FORTRAN_WRITE_ARGS(const char* f) CODE
    integer i;
    std::string arg = "";  // Removed __cx11, not needed

    IF f[0] != '(' || f[strlen(f)-1] != ')' THEN
        return "";
    ENDIF

    FOR i = 0; i < strlen(f); i++ LOOP
        selectcase(f[i])
            case ' ':
            case '(':
            case ')':
            case ',':
                continue;
                break;
            case 'I':
                IF f[i+1] >= 48 && f[i+1] <= 57 THEN
                    arg += "%";
                    arg += f[i+1];
                    arg += "d";
                ELSE
                    arg += "%d";
                ENDIF

                break;
            default:
                continue;
        endselectcase
    ENDFOR
    char retval[arg.length() + 1];  // Removed pointless initialization, fixed size
    for (auto& I : retail) i = '\0';  // null character initialization
    strncpy(retval, arg.c_str(), arg.length());
    return retval;
endfunction
#define write(t, f) printf(__FORTRAN_WRITE_ARGS(f),
#define endwrite )
#define WRITE write
#define precision

main
#include "fortran.h"  // Not a system include for me, so changed to " "

real function f() CODE
    return 0.0;
endfunction

program(main)
    IF 3 == 3 THEN
        PRINT(*) "Your PC is fine.";
    ELSEIF 3 == 4 THEN
        PRINT(*) "Your PC is broken.";
    ELSE
        PRINT(*) "Your PC is trash.";
    ENDIF

    write(*, "(I)") 5);
END

If the end-goal is to legitimately write C++ code using fortran syntax for something other than novelty, I'd say abandon that idea quickly and just learn C++.


text:
Q: Arrow keys in perl debugger works in one PuTTy session but not on another I have one saved session in PuTTy (connecting to a RHEL box) where perl -d and the arrow keys works very nice.
I have the same PuTTy version, and using session1, I cloned to connect to a different but similar RHEL box and the arrows does not work?
According to This question, session1 should have also not been working as I do not have Term::ReadLine::Gnu on that first box

A: You don't necessarily need Term::ReadLine::Gnu, other modules may fill the same need. I use Term::ReadLine::Perl. You may have that module (or another equivalent) installed on the first box but not on the second.
The linked answer claims that Term::ReadLine::Perl does not have arrow-key support, which may have been true at one time, but arrow keys work fine for me.


text:
Q: textbox having value via javascript, but asp:requiredfieldvalidator fires even the textbox has the value i have a textbox in asp.net with required field validator, which is filled using the javascript function(). But the case is that when the validation fires on the textbox it gives error message if it is empty thats okey, but when i fill textbox via javascript it still shows the error message of validation

A: I think you have to provide your code in you comment.
but i have understand little bit of your question.
try this and comment your require field validator on your textbox.
and use this javascript function in your code and let me know it working correctly or not.
<asp:TextBox runat="server" ID="txtBxID" onblur="return validateTextBox()"></asp:TextBox>
<script type="type/javascript>

function validateTextBox(){
   if ($("#txtBxID").val() == "") {
      $("#txtBxID").css("border", "1px solid red");
      return false;
   } else {
      $("#txtBxID").css("border", "");
   }
}
</script>


text:
Q: Squid in dual stack ipv4 / ipv6 reaching out for services only served on ipv4 interface I am running a dual stack network and am running a server there (Squid, Apache, DHCP, Mail,...). The network is working properly. However not all services running on that server provide a listener on ipv6. Prominent example: miniDLNA.
Now as I have Squid running, all internal connections are also served via squid. Calling the miniDLNA WebPage is not possible that way. I was not able to configure Squid to fall back to ipv4 to reach a service not provided on ipv6 interface. It might not be possible. I use "proxy.pac" to solve this now by checking for that specific ports and return "DIRECT" in that case like that:
  if (
    dnsDomainIs(host, ".MYINTERNALDOMAIN.int") &&
    (shExpMatch(url, "*:8200/*") || // service 1
     shExpMatch(url, "*:4080/*"))   // service 2
   )
{
    return "DIRECT";
}

But I am asking myself, if there might be a kind of acl magic I could use that would manage squid to do that internally? And a good question would also be to check, if proxy.pac could be optimized. I for instance tried dnsResolve to be sure about the internal net - and that is a very slow approach.
Thanks for any ideas on that. Google was not helpfull in that case.


text:
Q: Why can't a load bypass a value written by another thread on the same core from a write buffer? If a CPU core uses a write buffer, then the load can bypass the most recent store to the referenced location from the write buffer, without waiting until it will appear in the cache. But, as it's written in A Primer on Memory Consistency and Coherence, if the CPU honors TSO memory model, then

... multithreading introduces a subtle write buffer issue for TSO. TSO
  write buffers are logically private to each thread context (virtual
  core). Thus, on a multithreaded core, one thread context should never
  bypass from the write buffer of another thread context. This logical
  separation can be implemented with per-thread-context write buffers
  or, more commonly, by using a shared write buffer with entries tagged
  by thread-context identifiers that permit bypassing only when tags
  match.

I can't grasp the necessity of this limitation. Could you please give me an example when allowing some thread to bypass a write buffer entry written by another thread on the same core leads to the violation of the TSO memory model?

A: The classic example of how TSO differs from sequential consistency (SC) is:
(This is example 2.4 here - http://www.cs.cmu.edu/~410-f10/doc/Intel_Reordering_318147.pdf)
  thread 0     |     thread 1
---------------------------------
write 1-->[x]  |   write 1-->[y]
a = read [x]   |   b = read  [y]
c = read [y]   |   d = read  [x]

Both addresses store 0 initially. The question is: would c=d=0 be a valid outcome? We know a and b must forward the stores before them since they match the addresses of the local stores, and will probably be forwarded from the local threads store buffer. However, c and d may not be forwarded across context, so they may still show the old value.
The interesting gotcha here is that since each thread observes both stores, and forwards the local one, and outcome of a=1,c=0 would mean that t0 saw the store to [x] occurring first. An outcome of b=1,d=0 would mean that t1 saw the store to [y] occurring first. The fact that this is a possible outcome due to store buffer forwarding would break sequential consistency as it requires that all contexts agree on the same global order of stores. Instead, x86 settled for a weaker TSO model that allows this case.
Forwarding stores globally is practically impossible since buffered stores are not necessarily committed, which means they may even be in the wrong path of a branch misprediction. Forwarding locally is fine since a flush would also eliminate all the loads that forwarded from them, but on multiple contexts you don't have that.
I've also seen work that tries to buffer stores globally outside of the core, but this is not very practical due to latency and bandwidth. For further reading, here's a recent paper that may be relevant - http://ieeexplore.ieee.org/abstract/document/7783736/


text:
Q: SOAPUI replaces address with localhost When ever I try to load a new WSDL into a project (existing or new) the address is being replaced with localhost. For example I copy from the web browser
http://192.168.1.1:8080/webservices/service1?wsdl
then I get an error stating
http://localhost:8080/webservices/service1?wsdl error loading ... attempted to read from closed stream.
I have verified the proxy (we don't use them). However, I did have it turned on at on point to 'record' the call using JMeter. But jmeter is no longer running.
If I enter an address to an external webservice it will load fine.
Ideas / suggestions on how to resolve this issue?


text:
Q: customController save 1 object less then it has to My SF page. So the problem is that I got repeat block, that adds rows by a button on the page. So there is no record inside the list but I got 1 repeat block. If I press "add new row" once there would be only 1 record. So when I save changes I always get one less record than I should. I was trying to add something like this :
Estimates__c estimates = (Estimates__c)con.getRecord();

Estimate_lines__c line.Estimate__c = estimates.Id();

to set id of the parent object to add additional record manually. But it doesn't work. Also it doesn't work if I add it in the constructor. So question is how could I make number of block the same as records. So I always have 1 or more repeat blocks on the page.
VF Page
    <apex:pageBlock id="pageBlock" title="Page created by Me" mode="edit">
        <apex:pageBlockButtons id="Section1_buttons_block">
            <apex:commandButton id="Save_data" value="Save" action="{!save}"/>
            <apex:commandButton id="clear" value="clear" onclick="clearValue()"/>
            <apex:commandButton id="clearAllValuesRerender" value="clearFields" action="{!clearAllFields}" immediate="true"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection id="pageBlockSection1" showHeader="true" title="Section1">
            <apex:inputField id="Project_input_field" value="{!Estimates__c.Project__c}"/>
            <apex:inputField id="Customer_input_field" value="{!Estimates__c.Customer__c}"/>
            <apex:inputField id="Contact_input_field" value="{!Estimates__c.Contacts_Person__c}"/>
            <apex:inputField id="Estimate_status_input_field" value="{!Estimates__c.Status__c}"/>
            <apex:inputField id="Note_input_field" value="{!Estimates__c.Notes__c}"/>
            <apex:commandButton id="New_row_add_button" value="Add new row" action="{!addSection}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection id="pageBlockSection2" showHeader="true" title="Section2">
            <apex:inputField id="Quantity_from_estimates_line" value="{!item.Quantity__c}" />
            <apex:inputField id="Unit_price_input_field" value="{!item.Unit_price__c}" />
            <apex:inputField id="Description_input_field" value="{!item.Description__c}"/>
        </apex:pageBlockSection>
            <br>
                <apex:repeat value="{!itemList}" var="v">
                    <apex:pageBlockSection >
                    <apex:inputField id="Quantity_from_estimates_line" value="{!v.Quantity__c}" />
                    <apex:inputField id="Unit_price_input_field" value="{!v.Unit_price__c}" />
                    <apex:inputField id="Description_input_field" value="{!v.Description__c}"/>
                    </apex:pageBlockSection>
                </apex:repeat>
            </br>

    </apex:pageBlock>

My controller.
public with sharing class EstimateController {
    Integer estimateLineItemsCount = 1;
    public Estimates__c estimates {get;set;}
    public List<String>listOfSections {get;set;}
    public List<Estimate_lines__c> itemList {get;set;}
    public Estimate_lines__c item {get;set;}
    public List<Estimate_lines__c> line1 {get;set;}
    private ApexPages.StandardController con;

    public EstimateController(ApexPages.StandardController con) {
        this.con = con;
        estimates = new Estimates__c();
        itemlist = new List<Estimate_lines__c>();
        item = new Estimate_lines__c();
    }

    public void getEstimateId(){
        Estimates__c estimates = (Estimates__c)con.getRecord();
        item.Estimates__c = estimates.Id;
    }
    public PageReference addSection(){
        //item = new Estimate_lines__c();
        addLineItem(item);
        return null;
    }
    public PageReference addLineItem(Estimate_lines__c myLine){
        itemList.add(myLine);
        return null;
    }
    public PageReference save(){
        upsert estimates;
        for(Estimate_lines__c line : itemList){
            Estimates__c estimates = (Estimates__c)con.getRecord();
            line.Estimates__c = estimates.Id;
        addLineItem(line);
        }
        Estimates__c estimates = (Estimates__c)con.getRecord();
        item.Estimates__c = estimates.Id;
        addLineItem(item);
        upsert itemList;
        System.debug(itemList);

        return null;
    }
    public PageReference clearAllFields(){
        Estimates__c estimates = (Estimates__c)con.getRecord();
        estimates.Customer__c = null;
        estimates.Project__c = null;
        estimates.Contacts_Person__c = null;
        estimates.Status__c = null;
        estimates.Notes__c = null;

        item.Quantity__c = null;
        item.Unit_price__c = null;
        item.Description__c = null;

        estimateLineItemsCount = 1;

        return null;

    }
}

A: Your controller has a lot going on in it that doesn't need to be there. I have made an attempt to clean up the controller and the VF page below as well as commenting it to describe what is happening.
To answer the specific problem you asked about, there will be one <apex:pageBlockSection> added by the repeater for each one of the Estimate Line records in the list that it is iterating over.
Page Controller
public with sharing class EstimateController {

    public Estimates__c estimate { get; set; }
    public List<Estimate_lines__c> estimateLines { get; set; }
    private ApexPages.StandardController con;

    public EstimateController(ApexPages.StandardController con) {
        this.con = con;

        // init the record for the page and the list of children
        estimate = (Estimates__c)con.getRecord();
        estimateLines = new List<Estimate_lines__c>();

        // add an empty line to the collection initially
        addNewLineItem();
    }

    // add a new item to the list of estimate lines
    public void addNewLineItem() {
        estimateLines.add(new Estimate_lines__c());
    }

    public PageReference save() {

        // DML for the parent record
        upsert estimate;

        // DML for the children

        for (Estimate_lines__c estimateLine : estimateLines) {
            // set the id of the parent on the child
            estimateLine.Estimates__c = estimate.Id;
        }

        upsert estimateLines;

        return null;
    }

    public PageReference clearAllFields(){

        // reset the parent
        // estimate = (Estimates__c)con.getRecord();
        estimate.Customer__c = null;
        estimate.Project__c = null;
        estimate.Contacts_Person__c = null;
        estimate.Status__c = null;
        estimate.Notes__c = null;

        // clear the list of children and then add a new entry to the list
        /* this code needs to be extended to check for an Id value on
           the Estimate_lines__c records and delete those with Ids from the
           database rather than just clearing the list used by the page */
        estimateLines = new List<Estimate_lines__c>();
        addNewLineItem();

        return null;

    }
}

VF Page
<apex:pageBlock id="pageBlock" title="Page created by Me" mode="edit">
    <apex:pageBlockButtons id="Section1_buttons_block">
        <apex:commandButton value="Save" action="{!save}"/>
        <apex:commandButton value="Clear" action="{!clearAllFields}" immediate="true" />
    </apex:pageBlockButtons>

    <!-- create one pageblocksection for the header -->
    <apex:pageBlockSection id="pageBlockSection1" showHeader="true" title="Estimate Header">
        <apex:inputField id="Project_input_field" value="{!estimate.Project__c}"/>
        <apex:inputField id="Customer_input_field" value="{!estimate.Customer__c}"/>
        <apex:inputField id="Contact_input_field" value="{!estimate.Contacts_Person__c}"/>
        <apex:inputField id="Estimate_status_input_field" value="{!estimate.Status__c}"/>
        <apex:inputField id="Note_input_field" value="{!estimate.Notes__c}"/>
        <apex:commandButton id="New_row_add_button" value="Add new row" action="{!addNewLineItem}"/>
    </apex:pageBlockSection>

    <!-- create one pageblocksection for each estimateLine -->
    <apex:repeat value="{!estimateLines}" var="line">
        <apex:pageBlockSection id="pageBlockSection2" showHeader="true" title="Estimate Line">
            <apex:inputField id="Quantity_from_estimates_line" value="{!line.Quantity__c}" />
            <apex:inputField id="Unit_price_input_field" value="{!line.Unit_price__c}" />
            <apex:inputField id="Description_input_field" value="{!line.Description__c}"/>
        </apex:pageBlockSection>
    </apex:repeat>

</apex:pageBlock>


text:
Q: How can i add textbox inside dropdown list? I want to add textbox inside dropdown list. Is there a way that i can use theadd textbox inside the dropdown ? thank you. I have using bootstrap.

A: Using the markup from the first example provided from Dropdowns - Bootstrap, then you could use the following:

$(document).ready(function(){
  jQuery('', {
    class: 'dropdown-item',
    href: '#',
    text: 'New Item'
  }).appendTo($('.dropdown-menu'));
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>

    Action
    Another action
    Something else here

The important thing to consider is that you should change the appendTo selector to your actual item. With my example, if you had multiple DOM elements that had the .dropdown-menu class, then they'd all get appended the new element.


text:
Q: Variance of the mean of independent (not IID) normal random variables Say you've got $i=1:N$ observations, $X_i$.  Each observation is the mean of a Gaussian with an associated variance $Var(X_i)$. The variances are NOT identical.  The expectation of $X$ should simply be their mean $N^{-1}\displaystyle\sum X$.  The variance of the mean should be
$$
Var\left(N^{-1}\displaystyle\sum X_i\right) = N^{-2}\displaystyle\sum Var(X_i)
$$
Is this correct?  I'm following the basic formula on Wikipedia, but I'm getting implausibly small variances.  Am I missing something?  The above formula is usually used in the context of equal variances, but it doesn't say anything about requiring equal variances.

A: Yes, this is so.   The random variables do not need to be identically distributed.   However the result requires the random variables to be independent.
Let ${\{(X_i, \mu_i, \sigma_i^2)\}}_{i=1}^N$ be a series of mutually independent random variables, their means, and variances.
Let $\bar X:=\tfrac 1 N \sum\limits_{i=1}^N X_i$ be the mean of the series (ie: the sample mean).
Then indeed the expectation of the sample mean is: $\mathsf E(\bar X) = \tfrac 1 N\sum\limits_{i=1}^N \mu_i$
And the variance of the sample mean is:$$\begin{align}
\mathsf{Var}(\bar X) ~=~& \mathsf {Cov}(\tfrac 1 N \sum\limits_{i=1}^N X_i,\tfrac 1 N \sum\limits_{j=1}^N X_j)
\\[1ex] =~&\tfrac 1{N^2} \sum_{i=1}^N\sum_{j=1}^N \mathsf{Cov}(X_i,X_j)
\\[1ex] =~& \tfrac 1{N^2} \sum_{i=1}^N \mathsf{Var}(X_i) & ^\dagger
\\[1ex] =~& \tfrac {1}{N^2} \sum_{i=1}^N \sigma_i^2
\end{align}$$
(† because $\forall i\forall j: \big[i\neq j ~\to~ \mathsf{Cov}(X_i,X_j)=0\big]$ due to independence.)
And indeed, as the count $N$ increases infinitely the variance of the sample mean will decrease vanishingly.   $~\lim\limits_{N\to\infty} \mathsf{Var}(\bar X)=0$

PS: This is not the mean of the sample variance, if that is what is confusing you.


text:
Q: Mercurial: best way to push ignored file Sometimes need arises to update a library or file that has previously been put into .hgignore.
Normally, I would delete its entry from ignore list, commit/push a change and put ignore entry back.
Is this a good practice or there is some better/elegant way to deal with such a situation in Mercurial?

A: From the hgignore man page

The Mercurial system uses a file called .hgignore in the root directory of a repository to control its behavior when it searches for files that it is not currently tracking.

This library is obviously tracked. At some point you did hg add <library>. hgignore is no longer part of the equation for this file. In the future just update your library and commit.
hgignore is used for things like stopping mercurial talking about certain files when you do an hg status or adding them on hg addremove. It doesn't stop mercurial noticing if a tracked file changes.

A: You don't need to remove the entry from .hgignore; you can just hg add the file.
However, when you use a GUI, this GUI might use the .hgignore entries to show you a filtered list of files you can add. In this case, you would either have to add the file maqnually with hg add, or remove the entry temporarily from the .hgignore file.


text:
Q: Update an array using MongoDB I have JSON like :

{ "_id" : "1", "_class" : "com.model.Test",  "itemList" : [
  {       "itemID" : "1",   "itemName" : "Foo",
           "resources" : [ {       "resourceID" : "1",  "resourceName" : "Foo Test1",  }, {       "resourceID" : "2",  "resourceName" : "Foo
  Test2",  }  ] } ] }

I need to be able to update the list of resources.
I have done the following:
    BasicDBObject updateQuery = new BasicDBObject();
    updateQuery.put("id", "1");

    BasicDBObject updateCommand = new BasicDBObject();

    List<Resource> resources = populateResources();//Fetch a new list of Resources
    updateCommand.put("$push", new BasicDBObject("resources", resources));

    MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
    DBCollection db = mongoOperations.getCollection("myCollection");
    db.save(updateCommand);

I get the follwoing error:

java.lang.IllegalArgumentException: fields stored in the db can't
  start with '$' (Bad Key: '$push')

When I used :
db.update( updateQuery, updateCommand, true, true );

I got the following exception:

java.lang.IllegalArgumentException: can't serialize class
  com.model.Test

I've tried :
db.updateMulti(updateQuery, updateCommand);
I didn't get neither any exceptions nor any updates takes place into the documents.
So what am I missing here !!

A: The save() method is failing because it is attempting to insert the following document into the collection: {"$push":{"resources":[a list of resources]}}, and "$push" is not a valid key name.
From your question, it appears as though you are attempting to add another resource document to the list of embedded documents, "resources", inside of the embedded document matching {"itemID" : "1"}, inside of "itemList".  Is this correct?
Dealing with layers of embedded documents is tricky, but it can be done:
Here is how the following document may be inserted into the "resources" list using the JS shell:
> var docToInsert = { "resourceID" : "3", "resourceName" : "Foo Test3"}
> db.myCollection.update({_id:"1", "itemList.itemID":"1"}, {"$push":{"itemList.$.resources":docToInsert}})
> db.myCollection.find().pretty()
{
    "_class" : "com.model.Test",
    "_id" : "1",
    "itemList" : [
        {
            "itemID" : "1",
            "itemName" : "Foo",
            "resources" : [
                {
                    "resourceID" : "1",
                    "resourceName" : "Foo Test1"
                },
                {
                    "resourceID" : "2",
                    "resourceName" : "Foo Test2"
                },
                {
                    "resourceID" : "3",
                    "resourceName" : "Foo Test3"
                }
            ]
        }
    ]
}
>

The documentation on using the "$" positional operator to update embedded documents may be found in the "Updating" documentation:
http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator
The documentation on the "$push" modifier is also on the "Updating" page:
http://www.mongodb.org/display/DOCS/Updating#Updating-%24push
From the posted code, it appears as though "resources" is a list.  It is possible that the method you need to use is $pushAll, used for adding multiple values to a list:
http://www.mongodb.org/display/DOCS/Updating#Updating-%24pushAll
Using the Java driver, the above insert may be done like so:
Mongo m = new Mongo("localhost", 27017);
DB db = m.getDB("test");
DBCollection myColl = db.getCollection("myCollection");

BasicDBObject docToInsert = new BasicDBObject("resourceID", "3");
docToInsert.put("resourceName", "Foo Test3");

BasicDBObject updateQuery = new BasicDBObject("_id", "1");
updateQuery.put("itemList.itemID", "1");

BasicDBObject updateCommand = new BasicDBObject("$push", new BasicDBObject("itemList.$.resources", docToInsert));

myColl.update(updateQuery, updateCommand);
System.out.println(myColl.findOne().toString());

The above outputs the following:
{ "_class" : "com.model.Test" , "_id" : "1" , "itemList" : [ { "itemID" : "1" , "itemName" : "Foo" , "resources" : [ { "resourceID" : "1" , "resourceName" : "Foo Test1"} , { "resourceID" : "2" , "resourceName" : "Foo Test2"} , { "resourceID" : "3" , "resourceName" : "Foo Test3"}]}]}

Hopefully, the above will improve your understanding of how updating an embedded document works with Mongo using the Java driver.  I notice that this question is also related to Spring ("mongoOperations" is a class from the Spring package), which I am unfortunately not familiar with.  If you are still having issues with your update, perhaps another member of the Community who is more familiar with Spring will be able to assist.


text:
Q: How do we know the representation for $n_2 \lt n_1$ has less bases? Given that we know the following is true:
$n = \sum_{j=0}^{s} c_j 3^j, c_s \ne 0, c_j \in \{-1,0,1\}$
We are to determine the least number of weights to weigh any integral number of pounds up to 80 pounds if one is allowed to put weights in both pans of a balance.
The answer is clearly 5 weights (1 lb, 3 lb, 9 lb, 27 lb, 81 lb), since we can represent $80 < 81 = 3^4$
But my question is as follows, and is vital to the proof (I assume? Is it?).  Regardless, I'd like to know:  How do we know that some number less than $80$, such as $79$ doesn't require more than $5$ weights to be represented?
How can we prove that every number less than 80 requires either 5 weights or less to be represented, essentially?
I would normally use proof by induction, but as you can see, my above statement isn't valid for all integers, only integers below 82.


text:
Q: onTouch exception when scrolling multiple WebViews I have an app that uses multiple WebViews next to each other to display content. When vertically scrolling on one, and I scroll another before the first stops completely I get an exception with the below stack trace. The first line in the stack is the most puzzling to me. I do not know what a VelocityTracker is, or what any of the other variables refer to.
11-30 10:47:04.740: E/webview(2199): Got null mVelocityTracker when mPreventDefault = 0 mDeferTouchProcess = false mTouchMode = 3
11-30 10:50:23.771: D/AndroidRuntime(2199): Shutting down VM
11-30 10:50:23.771: W/dalvikvm(2199): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-30 10:50:23.795: E/AndroidRuntime(2199): FATAL EXCEPTION: main
11-30 10:50:23.795: E/AndroidRuntime(2199): java.lang.NullPointerException
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.webkit.WebView.onTouchEvent(WebView.java:5283)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.View.dispatchTouchEvent(View.java:3885)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1702)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1125)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at android.app.Activity.dispatchTouchEvent(Activity.java:2132)
11-30 10:50:23.795: E/AndroidRuntime(2199):     at
...

I am using a sub-classed WebView, but I do not override the onTouchEvent() method.
Interestingly I am only finding this error on the OS v2.3 device I am using as well as any OS v2.x emulator. Anytime I test on a 4.x device everything is fine and all WebViews are able to handle touching and scrolling simultaneously.
What is going on? Is this a known bug in Android? I could not find any record of a similar circumstance. Any suggestions for a workaround? I could just prevent other WebViews from being touched so long as one of them is scrolling, but that seems ridiculous.

A: I found out how I was causing the problem, but not what the problem truly was.
I stumbled on this link which described a problem when a WebView does not pass along all onTouch events. I had an onTouchListener set to my WebViews which handled the first onTouch event by returning true but then passed along subsequent events by returning false.
Apparently some versions of the OS get messed up when they aren't able to process all onTouch events.


text:
Q: Need help understanding capturing from Wireshark? I am having issues with my FTP servers.
Connecting, sending and receiving fail sometimes, and it is not consistent.
I manage to capture and filter by IP the packets, I just need pointers on what can I do from there as I don't fully understand the capturing.
Here is a screenshot

Here are the log from the server when failing
Error:  Connection closed by server
Error:  Connection timed out
Error:  Could not connect to server
Status: Delaying connection for 5 seconds due to previously failed connection attempt...
Status: Connecting to xxx.xxx.xxx.xxx:21...
Status: Connection established, waiting for welcome message...
Error:  Connection timed out
Error:  Could not connect to server
Status: Delaying connection for 5 seconds due to previously failed connection attempt...
Status: Connecting to xxx.xxx.xxx.xxx:21...
Status: Connection established, waiting for welcome message...
Error:  Connection timed out
Error:  Could not connect to server

A: To properly understand what is happening, take a look at the TCP 3 Way Handshake. In a nutshell, it goes a little something like this:
Client 1 >>>>>>SYN>>>>> Client 2
Client 2 >>SYN ACK>>>>> Client 1
Client 1 >>>>>ACK>>>>>> Client 2

The session is now established, where Client 1 is the machine/node that initiates the connection. Once established, the proper termination of a connection is a similar exchange of
Client 1 >>>>>>FIN>>>>> Client 2
Client 2 >>FIN ACK>>>>> Client 1
Client 1 >>>>>ACK>>>>>> Client 2

Although that doesn't always happen. I also see that the connection was RST, you can probably guess what that means. Not sure why you're connection is being randomly reset, but it looks like it's the client that's resonding with a RST,ACK but your screenshot doesn't show a RST sent by the server. You should do this, and then update your question:

*

*Disconnect from the server

*Clear all wireshark logs

*Filter based on server IP

*Start capture

*Try to connect

*Stop capture after connection fails

*Display only a single TCP Stream
Add the new pic. If it's easier, I believe the PCAP file is text based, meaning you can open it up in your favorite text editor, do a find/replace on your IP addresses, save it back and either upload it here, or link to pastebin or something.


text:
Q: What are the effects of formatting on SQL statements in PHP applications? I have this bit of PHP code that accesses a database using XAMPP/mysql. I'm setting the query string, both look exactly the same to me besides spacing/tabs but one works and the other doesn't.
This doesn't work:
$sql = "UPDATE employees
    SET
    first_name = '$_GET[firstname]',
    last_name = '$_GET[lastname]',
    hire_date = '$_GET[hiredate]',
    salary = '$_GET[salary]',
    department_id = '$_GET[department]',
    WHERE
    employee_id = '$_GET[id]'";

This works:
$sql = "UPDATE employees
        SET
        first_name      =    '$_GET[firstname]',
        last_name       =   '$_GET[lastname]',
        hire_date       =   '$_GET[hiredate]',
        salary          =   '$_GET[salary]',
        department_id   =   '$_GET[department]'
        WHERE
        employee_id     =   '$_GET[id]'";

When I use the broken statement I get:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE employee_id = '104'' at line 8

Can anyone explain why?

A: You have an extra comma in your first example. Basically you made a typo.
$sql = "UPDATE employees
SET
first_name = '$_GET[firstname]',
last_name = '$_GET[lastname]',
hire_date = '$_GET[hiredate]',
salary = '$_GET[salary]',
department_id = '$_GET[department]', // <--- HERE
WHERE
employee_id = '$_GET[id]'";


text:
Q: How start and stop MySQL and apache web server via PowerShell? I have installed MySQL 8 and Apache 2.4 web server individually and I would like to have a PowerShell function to turn them off and on as if I was using Xampp.
The problem is if do Start-Service Apache2.4, in PowerShell, I get this error
Start-Service : Service 'Apache2.4 (Apache2.4)' cannot be started due to the following error: Cannot open Apache2.4
service on computer '.'.
At line:1 char:1
+ Start-Service Apache2.4
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
   ServiceCommandException
    + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand

It's the same problem with MySQL, so for now I'm forced to control them via Windows services application.
Is there a way to control them via a PowerShell function or alias?


text:
Q: Some java method are null safe, some are not, how do I know? Some java method is null safe, but some are not. How to distinguish them?

A: I assume you mean in terms of the parameters? The documentation should state whether or not the arguments can be null, and when they can be null, what semantic meaning is inferred from nullity.
Unfortunately not all documentation is clear like this - and likewise it may not specify whether the return value might be null or not... in which case all you can do is experiment or look at the source code where possible :(

A: In general, I would suggest that you assume that you cannot pass null as a parameter unless the documentation clearly states that you can and what the corresponding behaviour is.
A problem with taking the default assumption that a parameter might be "null-safe" is that, even if that turns out to be true, it's not always clear without documentation what the corresponding behaviour actually is. "Not throwing an exception" doesn't actually indicate what alternative behaviour/default parameter/assumptions are then going to occur instead.
If you're designing an API, then where is's practical, I would suggest not actually encouraging null to be passed as a parameter to exposed methods/constructors, but rather have separate method signatures that include or not the various optional parameters. And in any case, you may then need to document in some way what actual behaviour is being taken to make up for the missing parameter.

A: If you're lucky, the parameter will be documented or annotated, or both. Unfortunately, most Java APIs lack both.
Some static analysis tools can use annotations to check whether you're passing a null value inappropriately. For example, the FindBugs tool includes support for these annotations:

*

*@NonNull - The value must not be null

*@CheckForNull - The value may contain null.

*@Nullable - Whether the value may contain null or not depends on context.

A: Read the javadocs of the methods you are trying to call.  If the javadocs don't specify this, then trial and error in a unit test is probably your best bet.


text:
Q: I am having trouble with if statements and possibly a def function So when running the code, it works as intended except for the fact that when looped a second time, the if statement doesn't work. May I ask for some help please.
cart=[]
price_total=[]
stuff={"potato": 50, "apple": 35, "orange": 40, "banana": 25, "popcorn": 120, "water": 20, "cola":
40}
y=1

def main():
  print("Thanks for using checkout")
  print("(1) make a transaction")
  customer_input=int(input("What would you like to do:"))

main()
if customer_input==1:
  print("potato=50")
  print("apple=35")
  print("orange=40")
  print("banana=25")
  print("popcorn=120")
  print("water=20")
  print("cola=40")
  global order_input
  order_input=input("What would you like to order:")
  cart.append(order_input)
  lol()

A: There are a couple of ways to implement what you want to do.

*

*Using Functions, which is the approach you seem to be trying to implement

*Using classes, which would be a more Object oriented approach

The Functional Approach
In the functional approach all operations are managed by individual functions, and many of the essential variables are passed to these functions.  Here are the implemented functions:
# The Functional Approach
def getInput(prompt, respType= None):
    """Simple Function To Gather input and verify it's type,
       Returns the User input converted to the requested type
       if it is consistent with the type specifier"""
    while True:
        resp = input(prompt)
        if respType == str or respType == None:
            break
        else:
            try:
                resp = respType(resp)
                break
            except ValueError:
                print('Invalid input, please try again')
    return resp

def list_stock(inv):
    """Returns a printable list of all items currently in inventory """
    kylist = sorted(list(inv.keys()))
    s = "The Items currently in stock include:\n"
    for i in range(len(kylist)):
            s += f'{i+1:4}\t{kylist[i]:10} {inv[kylist[i]]} each\n'
    return s

def add_to_cart(item, qty, cart):
    """Adds Item to cart and returns updated cart"""
    cdi = cart.pop(item, 0)
    cdi += qty
    cart[item] = cdi
    return cart

def contents(cart, inv):
    """Returns printable list of cart contents"""
    ckys = cart.keys()
    s = "The Items currently in your cart include:\n"
    s += 'Item\tQty\tCost\n'
    for ky in ckys:
        qty = cart[ky]
        cost= qty* inv[ky]
        s += f'{ky}\t{qty}\t{cost}\n'
    return s

def total_bill(cart, inv):
    """Returns the Total Cost of items in Cart"""
    total = 0
    for itm, qty in cart.items():
        total += qty*inv[itm]
    return total

def load_cart(cart, inv):
    stock = sorted(list(inv.keys()))
    print(list_stock(inv))
    while True:
        itm = stock[getInput('Please enter an item number to add to your cart', int)-1]
        qty = getInput(f'please enter the number of {itm} you want added to your cart', int)
        add_to_cart(itm, qty, cart)
        if  getInput("Do you have more to add? (y/n)").lower() != 'y':
                break

The main function which then controls process flow and manages calling necessary functions includes:
# The Main Method for Functional Appraoch
stuff={"potato": 50, "apple": 35, "orange": 40, "banana": 25, "popcorn": 120, "water": 20, "cola":
40}
cart = dict()
print("Thanks for using checkout")
while True:
    if getInput('Would you like to load a cart? (Y/N)').lower()[0]  == 'y':
        load_cart(cart, stuff)
        print(contents(cart, stuff))
        print (f'Your total bill = {total_bill(cart, stuff)}' )
    else:
        print('Have a nice day!')
        break

A typical execution of this main routine would look like:
Thanks for using checkout
Would you like to load a cart? (Y/N) y
The Items currently in stock include:
   1    apple      35 each
   2    banana     25 each
   3    cola       40 each
   4    orange     40 each
   5    popcorn    120 each
   6    potato     50 each
   7    water      20 each

Please enter an item number to add to your cart 3
please enter the number of cola you want added to your cart 2
Do you have more to add? (y/n) n
The Items currently in your cart include:
Item    Qty Cost
cola    2   80

Your total bill = 80
Would you like to load a cart? (Y/N) n
Have a nice day!

A more Object Oriented Approach
In the OO approach, many of the basic operations are implemented as methods within a Cart Class.  Using the Cart Class groups methods together and keeps them associated with the cart.  The following gives an implementation using the Cart Class.
class Cart:
    def __init__(self, inventory):
        self._cart = dict()
        self._inv = inventory

    def in_inventory(self, item):
        return item in self._inv.keys()

    @property
    def stock(self):
        return sorted(list(self._inv.keys()))

    def price(self, itm):
        return self._inv[itm]

    @property
    def inventory(self):
        kylist = self.stock
        s = "The Items currently in stock include:\n"
        for i in range(len(kylist)):
                s += f'{i+1:4}\t{kylist[i]:10} {self._inv[kylist[i]]} each\n'
        return s

    def add_to_cart(self, item, qty= 1):
        cdi = self._cart.pop(item, 0)
        cdi += qty
        self._cart[item] = cdi

    @property
    def contents(self):
        ckys = self._cart.keys()
        s = "The Items currently in your cart include:\n"
        s += 'Item\tQty\tCost\n'
        for ky in ckys:
            qty = self._cart[ky]
            cost= qty* self._inv[ky]
            s += f'{ky}\t{qty}\t{cost}\n'
        return s

    @property
    def bill(self):
        total = 0
        for itm, qty in self._cart.items():
            total += qty*self.price(itm)
        return total

Using the Cart Class for most of the needed methods, leaves only 1 separate function
def load_cart(cart):
    stock = cart.stock
    print(cart.inventory)
    while True:
        itm = stock[getInput('Please enter an item number to add to your cart', int)-1]
        qty = getInput(f'please enter the number of {itm} you want added to your cart', int)
        cart.add_to_cart(itm, qty)
        if  getInput("Do you have more to add? (y/n)").lower() != 'y':
                break

The main function which manages the entire application would then look like:
# The main routine to execute the Object Oriented Appraoch
stuff={"potato": 50, "apple": 35, "orange": 40, "banana": 25, "popcorn": 120, "water": 20, "cola":
40}
cart = Cart(stuff)
print("Thanks for using checkout")
while True:
    if getInput('Would you like to load a cart? (Y/N)').lower()[0]  == 'y':
        load_cart(cart)
        print(cart.contents)
        print (f'Your total bill = {cart.bill}' )
    else:
        print('Have a nice day!')
        break

Executing this Main method would produce results like:
Thanks for using checkout
Would you like to load a cart? (Y/N) y
The Items currently in stock include:
   1    apple      35 each
   2    banana     25 each
   3    cola       40 each
   4    orange     40 each
   5    popcorn    120 each
   6    potato     50 each
   7    water      20 each

Please enter an item number to add to your cart 4
please enter the number of orange you want added to your cart 3
Do you have more to add? (y/n) n
The Items currently in your cart include:
Item    Qty Cost
orange  3   120

Your total bill = 120
Would you like to load a cart? (Y/N) n
Have a nice day!

A: Put all of your code under def main() and use main() just call the the function.  You can then use while loops to keep asking for user input and provide a way for user to exit by entering -1 or something similar:
cart=[]
price_total=0
stuff={"potato": 50, "apple": 35, "orange": 40, "banana": 25, "popcorn": 120, "water": 20, "cola":40}
y=1

def main():
    global price_total
    print("Thanks for using checkout")
    print("(1) make a transaction. (-1) to exit.")
    customer_input = int(input("What would you like to do: "))
    while customer_input == 1:
      print("potato=50")
      print("apple=35")
      print("orange=40")
      print("banana=25")
      print("popcorn=120")
      print("water=20")
      print("cola=40")
      global order_input
      order_input = input("What would you like to order? (-1) to finish: ")
      if order_input == "-1":
          print(f'You bought {cart} for total price of {price_total}.')
          break
      cart.append(order_input)
      price_total += stuff[order_input]

main()


text:
Q: Date Picker Layout View I have to implement the date picker in my layout.
I have to show the date picker with plus minus symbol.
but after implementing date picker in my xml , I got the date picker having previous an next date above and below.
Please  let me know that how to implement this?

A: Actually, you are testing in latest android version i.e. above API Level 11, so if you need to show the old widgets or UI elements then please add:
android:theme="@android:style/Theme.Black.NoTitleBar"

in your current <activity> in AndroidManifest file.


text:
Q: How to conditionally click a checkbox in telerik grid based on another column in the grid Currently I am using Telerik MVC and Ajax javascript trying to click a checkbox after checking if the comment column has a length greater then 3. Currently it is doing what I want it to do but the first time you try it in the gird it doesnt work but all the following times it does.
basically  if you had a grid set up like below, you could start at the top row and only the following rows will read the code and actually check the checkbox
comment,      time,    date,      checkbox

aaaa,         10:00,   14-2022,   []
aaaaaaaaaa,   10:00,   14-2022,   [x]
aaaaa,        10:00,   14-2022,   [x]
aaaa,         10:00,   14-2022,   [x]

$(document).on("keyup", "#eTmfCompletenessComment", function () {
            function dirtyField(data, fieldName) {
                if (data.dirty && data.dirtyFields[fieldName]) {
                    return ""
                }
                else {
                    return "";
                }
            }

             var commentcheck = $(this).val()
             console.log('$(this).val() =', $(this).val())

                var grid = $('#Grid').data("kendoGrid");
                var items = grid.items();
                if (commentcheck.length > 3) {
                    //var gc = $(this).parents(".k-")
                    $(this).parents(".k-master-row").find('input[type="checkbox"]').prop("checked", true);
                   items.each(function () {
                        var dataItem = $(this).parents(".k-grid-cell").find('input[type="hidden"]');
                       set.dataItem.dirty = true;
                       dataItem.set(true);
                       dataItem.dirtyField.set(true, eTmfCompletenessActive)

                    })

                }
            })


text:
Q: Generate Javadoc for OSGi bundle I'm newbie in OSGi world but I was able to do some Camel and OSGi bundles to do some tasks in a middleware. Everything I made since was a proof of concept, but now I want to refactor some part of my code and I start writing a OSGi bundle who will contain common functionalities shared among other OSGi bundles.
To make it clean, I decide to write comments and use javadoc to get sleek documentation, but I'm stuck with this error:
Error resolving version for plugin
'org.apache.maven.plugins:maven-javadoc-plugin' from the repositories

I was able to run javadoc for another Camel component;
We have a local repository with the dependency maven-javadoc-plugin in;
I add the dependency maven-javadoc-plugin to my project;
I'm running out of ideas why it doesn't work.
Maybe I'm wrong and I using OSGi bundle in a wrong way...
UPDATE
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org</groupId>
<artifactId>test</artifactId>
<version>0.0.1</version>
<packaging>bundle</packaging>

<name>uces OSGi Bundle</name>

<dependencies>
    <dependency>
        <groupId>org.osgi</groupId>
        <artifactId>org.osgi.core</artifactId>
        <version>4.3.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.thoughtworks.xstream</groupId>
        <artifactId>xstream</artifactId>
        <version>1.4.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.10.3</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>2.3.7</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-Activator>org.test.Activator</Bundle-Activator>
                    <Export-Package>org.test</Export-Package>
                </instructions>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>build-for-felix</id>
        <dependencies>
            <dependency>
                <groupId>org.apache.felix</groupId>
                <artifactId>org.apache.felix.main</artifactId>
                <version>4.0.3</version>
                <scope>provided</scope>
            </dependency>
            <!-- To include a shell:
            <dependency>
                <groupId>org.apache.felix</groupId>
                <artifactId>org.apache.felix.gogo.shell</artifactId>
                <version>0.10.0</version>
            </dependency>
            -->
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-antrun-plugin</artifactId>
                    <version>1.7</version>
                    <executions>
                        <execution>
                            <id>compile</id>
                            <phase>package</phase>
                            <goals>
                                <goal>run</goal>
                            </goals>
                            <configuration>
                                <target>
                                    <pathconvert property="plugins.jars" pathsep="${path.separator}">
                                        <path refid="maven.runtime.classpath"/>
                                        <map from="${project.build.directory}${file.separator}classes" to=""/>
                                    </pathconvert>
                                    <pathconvert pathsep=" " property="bundles">
                                        <path path="${plugins.jars}"/>
                                        <mapper>
                                            <chainedmapper>
                                                <flattenmapper/>
                                                <globmapper from="*" to="file:modules/*" casesensitive="no"/>
                                            </chainedmapper>
                                        </mapper>
                                    </pathconvert>
                                    <propertyfile file="${project.build.directory}/config.properties">
                                        <entry key="felix.auto.start" value="${bundles} file:modules/${project.build.finalName}.jar"/>
                                        <entry key="org.osgi.framework.bootdelegation" value="*"/>
                                    </propertyfile>
                                    <copy file="${maven.dependency.org.apache.felix.org.apache.felix.main.jar.path}" tofile="${project.build.directory}/felix.jar"/>
                                </target>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.3</version>
                    <executions>
                        <execution>
                            <id>create-executable-jar</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                            <configuration>
                                <descriptors>
                                    <descriptor>${basedir}/src/main/assembly/felix.xml</descriptor>
                                </descriptors>
                                <finalName>${project.build.finalName}</finalName>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <id>run-on-felix</id>
        <dependencies>
            <dependency>
                <groupId>org.apache.felix</groupId>
                <artifactId>org.apache.felix.main</artifactId>
                <version>4.0.3</version>
                <scope>provided</scope>
            </dependency>
            <!-- org.apache.felix:org.apache.felix.gogo.shell:0.6.1 useless from Maven since stdin is swallowed -->
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-antrun-plugin</artifactId>
                    <version>1.7</version>
                    <configuration>
                        <target>
                            <property name="vm.args" value=""/>
                            <pathconvert property="plugins.jars" pathsep="${path.separator}">
                                <path refid="maven.runtime.classpath"/>
                                <map from="${project.build.directory}${file.separator}classes" to=""/>
                            </pathconvert>
                            <makeurl property="urls" separator=" ">
                                <path path="${plugins.jars}"/>
                                <path location="${project.build.directory}/${project.build.finalName}.jar"/>
                            </makeurl>
                            <propertyfile file="${project.build.directory}/run.properties">
                                <entry key="felix.auto.start" value="${urls}"/>
                                <entry key="felix.auto.deploy.action" value="uninstall,install,update,start"/>
                                <entry key="org.osgi.framework.storage" value="${project.build.directory}${file.separator}felix-cache"/>
                                <entry key="org.osgi.framework.bootdelegation" value="*"/>
                            </propertyfile>
                            <makeurl property="run.properties.url" file="${project.build.directory}/run.properties"/>
                            <java fork="true" jar="${maven.dependency.org.apache.felix.org.apache.felix.main.jar.path}">
                                <sysproperty key="felix.config.properties" value="${run.properties.url}"/>
                                <jvmarg line="${vm.args}"/>
                            </java>
                        </target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

A: Ok, i finally found my response after digging more deeply in javadoc page (Javadoc documentation) and add these lines into the build section:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.10.3</version>
</plugin>


text:
Q: How to disable generate css code after use tab - sublime and emmet Since few years i use SB + emmet.
Almost everyday i'm using auto generate tags, when i type "script" and click tab emment generate beauty "" tag.
From few days after generate tag after put TAB on my closet automaticly emmet put "script {
}"
It's sooooooo fcking anoying. For example when i have want to expand img tag and after it i want paste url to image.
I want to remove functionality generating nametag + brackets after put tab.
For explain i made video with my problem (sorry for voice from conference ) - https://www.youtube.com/watch?v=jYw6uLS19WM Can You help me?

A: I can confirm this:
For me removing the package "emmet scss style reflector" (or slightly different name) did the job


text:
Q: Storing my Survey maker data into salesforce I have a survey maker tool (proprofs.com/survey). I want that when any respondent respond the survey then the response will save on salesforce. I have already created connected app and connected my platform to salesforce using the REST API. Now I am confused what to do next.

A: there are lots of step needed.

*

*you need to decide in which object you will store data.

*Create a Restful class which can do job of storing your data to sf. when ever a call will be made (survey final click)

*you can call http request to your Restful class and save your data to choice of your object.

there are link which can help you in creating Restful apex class.
https://developer.salesforce.com/page/Creating_REST_APIs_using_Apex_REST