Sanity check on DIY drainage repair

Question: Background: I have zero plumbing experience, hence the sanity check. Everything I describe here is brand new to me.
My house is in a hilly area in Silicon Valley. All of the houses in this neighborhood have drains distributed around the yard, which drain to pipes under the sidewalk just above a storm drain. I only moved in recently; the house is 20 years old. A couple weeks ago we had a historic storm, and water collected deep enough that my house was very close to flooding. The drains in the yard did not really appear to be taking in much water, and the pipe at the street was putting out only a trickle. But I ended up being saved by luck; the drain in the front yard closest to the street was also the lowest, and was operating in reverse, with a torrent of water coming out of that drain and then running across the surface of the front yard toward the street, ironically dumping over the sidewalk directly above the pipe it was supposed to be going through. The next day I poked a stick up that pipe, under the sidewalk, and felt resistance... so I dug there.
Here is the aftermath of what I found:

The white pipe is coming out of the yard. The right black pipe is going under the sidewalk (the left black pipe was unused, which is normal in this neighborhood). They were connected with corrugated pipe and hoseclamps (one end still barely visible in that photo after I destroyed the middle section), and the corrugated pipe and the entire black pipe were filled with a giant rootball that had entered under the hoseclamps:

Reconnecting the pipes without another cheesy corrugated section proved difficult. There was both an elevation and a slope mismatch. The yard side was lower and sloped UP maybe 10deg. The street side was higher and sloped DOWN maybe 10deg. Here is what I ended up with:

I used two Fernco 3" flexible pieces, a simple straight one, and also a cleanout tee. They are connected with a 3" long piece of ABS. The cleanout is a nice bonus, but the real win here is that the length of that piece gave me even more flexibility for the alignment problem.
Here is the main question though. The white pipe is some weird thing which I believe is schedule 30. Incredibly thin-walled (0.070"), so it amazes me it hasn't had roots penetrate it yet. But its OD is 3.25", compared to the Fernco IDs and the black pipe OD (which are all 3.5"). At first I was worried this would be a problem. But:
(1) I ran a simple test to see if the rubber would contract nicely down to that smaller diameter. I overinserted the straight Fernco coupling onto the white pipe (so that I could see the mate more clearly) and cranked down the hose clamp. The result:

While it does look like there are small gaps, this is only because the rubber bows up away from the clamps. I am pretty convinced that at the clamps, there is a very good seal (and flushing 50gal loads down the drain after full assembly seemed to confirm this). The circular shape of the cross-section is distorted a bit which doesn't seem ideal, but I think this may have more to do with the thin wall than with the diameter mismatch.
(2) Ironically, the looseness of the Fernco <-> 3.25" mate was kind of critical in allowing me to actually assemble this entire mess with the huge starting misalignment. I don't think I'd have been able to get it all together if the white pipe had 3.5" OD. Basically I was able to overmate the entire "patch" assembly onto the white pipe with a pretty crooked alignment, which allowed me to get the other end of the tee slid back onto the black pipe and tighten that clamp, after which I tightened the crooked clamp onto the white pipe, which slowly straightened itself out, leading to the desired bend in the flexible coupling.
My major concern is if there is any issue with using the 3.5" ID Fernco coupling with the 3.25" OD thinwall pipe. I want to prevent future root invasions.
Comment: Seems like a reasonable repair.  This is ground water drainage.  In climates that get more rain you typically have a sump that the rainwater or ground water would enter first to help prevent sediment or anything else from entering the city service.  The sump inflow pipes are typically higher than the outflow pipe but really as long as there is general slope it probably doesn't matter too much that you have a belly in your pipe - that portion will likely have water sitting in it during the rainy season but you have a cleanout should root get in again.  Not worth the trouble to dig and slope it.
Comment: @gbronner no other clogs upstream, as I mentioned I flushed 50gal and it flowed smoothly. Also this section is 5ft from the curb exit, I can always snake from there if I need to.
Comment: I don't really see a specific question in here which is required before we try to provide an answer. Based on your description I'm not sure if the changes you made are going to work until you try them. You might want to hook it up and run a garden hose into the lawn drains and see if you get good flow. I would try to correct the negative slope you referred to. It may not be easy but otherwise water will just sit between the lawn drain and the upslope.
Comment: @HoneyDo I updated the end to make my question more clear. The drainage works fine (as I mentioned, I flushed 50 gallons through it). Even though there is a small upslope in this section, it is all far lower than the upstream sections. I just want to make sure the mate between the schedule 30 pipe and the Fernco fitting will not allow future root invasions because of the small diameter mismatch (which appears to disappear when the clamps are tightened and the rubber contracts). My changes did not affect the overall path of the water, only the connections in this small segment.
Comment: I'd try to to snake / roto-rooter the whole thing before you bury it again. You may have gotten dirt and other blockages in the line.
Answer: What you assembled will be a good match for the conditions and allow for a clean out. You are correct the fittings don't fit well on the drain pipe because of its smaller diameter.
Since there were roots in the area one thing I have done is pack rock salt around the patch (yours is well beyond what many contractors would have done) the salt will prevent roots from immediately trying to get back in and is a natural way without harsh chemicals. It won't take a lot of salt a couple of handfuls really helps.
But what you have should work fine.
Comment: Thanks Ed for your input!
Comment: FWIW, and for anybody else reading in the future: I actually spoke to Fernco customer service today, and they said sizing up or down 1/4" on the mate is no issue. Though I have no idea how anybody would upsize. Those fittings would not be easy to stretch!

Sanity check on DIY drainage repair


DataTables global Regex Search in each column

Question: I'd like to implement a feature, where you can start your search string with $ to get a startsWith search in all searchable columns.
This is what I've tried so far:
$('#myinput').on('keyup', (event) => {
    let searchValue = $(event.currentTarget).val();
    if (searchValue.startsWith('$')) {
        searchValue = `^${searchValue.substr(1)}`;
    }
    this.dataTable.search(searchValue, true, false, false).draw();
});

But apparently, this only searches in the first column. If I don't use ^ in my search, it searches all columns. How can I check if any of the columns start with myValue instead of the entire row data?
Can be reproduced on https://datatables.net/examples/api/regex.html.
Enable global Regex and search ^Airi and after that ^Accountant.
You will get results for Airi, but not for Accountant.
How can I make the search for ^Accountant still display the first entry, as the second column starts with Accountant?
Answer: That happens because when global regex is set to true it will treat the whole row as text. Therefore your search should look like:
$('#myinput').on('keyup', (event) => {
    let searchValue = $(event.currentTarget).val();
    if (searchValue.startsWith('$')) {
        searchValue = `\b${searchValue.substr(1)}`;
    }
    this.dataTable.search(searchValue, true, false, false).draw();
});

Regex token \b stands for "boundary". Each start of a word creates a new boundary (here is the Regex spec: https://regex101.com/r/s0MdwW/1). You can also try how it works in the Datatables website by searching "\bTok" which should make "Airi" appear.
Note however that there is a catch: Searching for "Sat" will match "Airi Satou" since there is a boundary between the words. If you want to avoid that particular case then you would simply need to perform a ^ regex search (like your current code) but for each column, and then collect all results. Per column regex search only use the column content for the match:

Update: Ok so the per column search was definitively more complex than expected because simply searching  each column would create an AND search. For example searching for "Airi" would also require that "Airi" is in all other columns.
To solve this particular a custom search function must be built. Here you can find it: https://codepen.io/adelriosantiago/pen/XWKGoLx?editors=1011
This custom function OR searches through the columns using the $.fn.dataTable.ext.search.push function.
Comment: thanks for the answer! Can you summarize how to perform a per column search?
Comment: @TomM I have updated the answer with an example how to do it.
Comment: I tried the column-search too but for me it just straight up cleared the entire table regardless of my search string. Used the custom search filter `$.fn.dataTable.ext.search.push` you suggested too and could solve my problem with that, so I'll accept your answer. Thank you!


My select input calculator is not working, how can I figure out why?

Question: I am working on a calculator that pics values from 4 select dropdowns real time, and goes on to update three divs below based on whatever the selected values are.
However I keep getting NaN for two of the answer divs.
My console.log is clean so I cannot get where this is coming from.

document.querySelector("select").onchange = function() {
  recalculate()
};

function recalculate() {
  var locations = document.getElementById('locations').value;
  var average_price = document.getElementById('average_price').value;
  var donation_rate = document.getElementById('donation_rate').value;
  var customers_number = document.getElementById('customers_number').value;
  var sales_result = document.getElementById('sales_result').innerHTML;
  var customers_result = document.getElementById('customers_result').innerHTML;
  var donations_result = document.getElementById('donations_result').innerHTML;
  var weeksInYear = 52;
  //customers_result = locations * weeksInYear * customers_number;
  //donations_result = donation_rate * customers_number* locations * average_price;
  //sales_result = locations * customers_result * average_price;
  document.getElementById('customers_result').innerHTML = locations * weeksInYear * customers_number;
  document.getElementById('donations_result').innerHTML = donation_rate * customers_number * locations * average_price;
  document.getElementById('sales_result').innerHTML = locations * customers_result * average_price;
};
.ng-scope {
  -webkit-text-size-adjust: 100%;
  -webkit-tap-highlight-color: transparent;
  line-height: 1.42867;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 22px;
  box-sizing: border-box;
}

#restaurant-landing .section-margins {
  margin-top: 12px;
  margin-bottom: 12px;
}

.row {
  width: 90%;
  margin-left: 50px;
  margin-right: 50px;
}

#restaurant-landing {
  font-size: 22px;
}

.row:before,
.row:after {
  content: " ";
  display: table;
}

.row:after {
  clear: both;
}

*:before,
*:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.col-xs-12 {
  float: left;
  width: 100%;
  position: relative;
  min-height: 1px;
}

.calculator-fields {
  font-size: 22px;
  line-height: 39px;
  border-radius: 12px;
  margin-top: 12px;
  margin-bottom: 12px;
  overflow: hidden;
  *zoom: 1;
  background-color: #2a4563;
  padding: 12px 30px;
  display: block;
}

.col-xs-3 {
  padding-left: 15px;
  padding-right: 15px;
}

.field-wrapper {
  margin-left: -15px;
  margin-right: -15px;
  overflow: hidden;
  *zoom: 1;
}

.calc-label {
  float: left;
  width: 58.33333%;
  color: #ffffff;
}

label {
  display: inline-block;
  max-width: 100%;
  margin-bottom: 5px;
  font-weight: bold;
}

.calc-field {
  float: left;
  width: 41.66667%;
}

.col-md-4 {
  width: 33.33333%;
}

.result-box {
  margin-top: 12px;
  font-family: 'Arvo', serif;
  background-color: #54822b;
  padding-top: 16px;
  padding-bottom: 4px;
  text-align: center;
  font-weight: bold;
}

.result-number {
  font-size: 48px;
  line-height: 62px;
  color: white;
}

.result-label {
  font-size: 22px;
  line-height: 28.6px;
  color: black;
  padding-bottom: 4px;
  text-align: center;
  font-weight: bold;
}
<!doctype HTML>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

                # of locations:

                <select name="locations" id="locations">
                  <option label="1" value="1">1</option>
                  <option label="2" value="2">2</option>
                  <option label="3" value="3">3</option>
                  <option label="4" value="4">4</option>
                  <option label="5" value="5" selected="selected">5</option>
                  <option label="6" value="6">6</option>
                  <option label="7" value="7">7</option>
                  <option label="8" value="8">8</option>
                  <option label="9" value="9">9</option>
                  <option label="10" value="10">10</option>
                  <option label="15" value="15">15</option>
                  <option label="20" value="20">20</option>
                  <option label="25" value="25">25</option>
                  <option label="40" value="40">40</option>
                  <option label="50" value="50">50</option>
                  <option label="100" value="100">100</option>
                  <option label="200" value="200">200</option>
                  <option label="300" value="300">300</option>
                  <option label="400" value="400">400</option>
                  <option label="500" value="500">500</option>
                </select>

                avg. ticket price:

                <select name="average_price" id="average_price">
                  <option label="$4" value="4">$4</option>
                  <option label="$5" value="5">$5</option>
                  <option label="$6" value="6">$6</option>
                  <option label="$7" value="7">$7</option>
                  <option label="$8" value="string:$8">$8</option>
                  <option label="$9" value="string:$9">$9</option>
                  <option label="$10" value="string:$10">$10</option>
                  <option label="$11" value="string:$11">$11</option>
                  <option label="$12" value="string:$12" selected="selected">$12</option>
                  <option label="$13" value="string:$13">$13</option>
                  <option label="$14" value="string:$14">$14</option>
                  <option label="$15" value="string:$15">$15</option>
                  <option label="$16" value="string:$16">$16</option>
                  <option label="$17" value="string:$17">$17</option>
                  <option label="$18" value="string:$18">$18</option>
                  <option label="$19" value="string:$19">$19</option>
                  <option label="$20" value="string:$20">$20</option>
                  <option label="$25" value="string:$25">$25</option>
                  <option label="$30" value="string:$30">$30</option>
                  <option label="$35" value="string:$35">$35</option>
                  <option label="$40" value="string:$40">$40</option>
                  <option label="$45" value="string:$45">$45</option>
                  <option label="$50" value="string:$50">$50</option>
                  <option label="$75" value="string:$75">$75</option>
                </select>

                donation:

                <select name="donation_rate" id="donation_rate">
                  <option label="15%" value="0.15">15%</option>
                  <option label="20%" value="0.20">20%</option>
                  <option label="25%" value="0.25">25%</option>
                  <option label="33%" value="0.33">33%</option>
                  <option label="40%" value="0.40">40%</option>
                  <option label="45%" value="0.45">45%</option>
                  <option label="50%" value="0.50">50%</option>
                </select>

                # Customers:

                <select name="customers_number" id="customers_number">
                  <option label="10" value="10">10</option>
                  <option label="20" value="20">20</option>
                  <option label="30" value="30">30</option>
                  <option label="35" value="35">35</option>
                  <option label="40" value="40">40</option>
                  <option label="45" value="45">45</option>
                  <option label="50" value="50">50</option>
                </select>

$11,440

sales

2,860

customers

$1,716

donations

Comment: I'm guessing it's because you are passing a string in the value in several of your options: `string:$8` and so on.
Comment: all the value you get from dom are string, just convert to number
Answer: There is a lot that I do not like about this but this fixes the NaN issue

document.querySelector("select").onchange = function() {
  recalculate()
};

function recalculate() {
  var locations = parseFloat(document.getElementById('locations').value);
  var average_price = parseFloat(document.getElementById('average_price').value);
  var donation_rate = parseFloat(document.getElementById('donation_rate').value);
  var customers_number = parseFloat(document.getElementById('customers_number').value);
  var sales_result = document.getElementById('sales_result');
  var customers_result = document.getElementById('customers_result');
  var donations_result = document.getElementById('donations_result');
  var weeksInYear = 52;

  customers_result.innerHTML = locations * weeksInYear * customers_number;
  donations_result.innerHTML = donation_rate * customers_number * locations * average_price;
  sales_result.innerHTML = locations * customers_result * average_price;
};
.ng-scope {
  -webkit-text-size-adjust: 100%;
  -webkit-tap-highlight-color: transparent;
  line-height: 1.42867;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 22px;
  box-sizing: border-box;
}

#restaurant-landing .section-margins {
  margin-top: 12px;
  margin-bottom: 12px;
}

.row {
  width: 90%;
  margin-left: 50px;
  margin-right: 50px;
}

#restaurant-landing {
  font-size: 22px;
}

.row:before,
.row:after {
  content: " ";
  display: table;
}

.row:after {
  clear: both;
}

*:before,
*:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.col-xs-12 {
  float: left;
  width: 100%;
  position: relative;
  min-height: 1px;
}

.calculator-fields {
  font-size: 22px;
  line-height: 39px;
  border-radius: 12px;
  margin-top: 12px;
  margin-bottom: 12px;
  overflow: hidden;
  *zoom: 1;
  background-color: #2a4563;
  padding: 12px 30px;
  display: block;
}

.col-xs-3 {
  padding-left: 15px;
  padding-right: 15px;
}

.field-wrapper {
  margin-left: -15px;
  margin-right: -15px;
  overflow: hidden;
  *zoom: 1;
}

.calc-label {
  float: left;
  width: 58.33333%;
  color: #ffffff;
}

label {
  display: inline-block;
  max-width: 100%;
  margin-bottom: 5px;
  font-weight: bold;
}

.calc-field {
  float: left;
  width: 41.66667%;
}

.col-md-4 {
  width: 33.33333%;
}

.result-box {
  margin-top: 12px;
  font-family: 'Arvo', serif;
  background-color: #54822b;
  padding-top: 16px;
  padding-bottom: 4px;
  text-align: center;
  font-weight: bold;
}

.result-number {
  font-size: 48px;
  line-height: 62px;
  color: white;
}

.result-label {
  font-size: 22px;
  line-height: 28.6px;
  color: black;
  padding-bottom: 4px;
  text-align: center;
  font-weight: bold;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

                # of locations:

                <select name="locations" id="locations">
                  <option label="1" value="1">1</option>
                  <option label="2" value="2">2</option>
                  <option label="3" value="3">3</option>
                  <option label="4" value="4">4</option>
                  <option label="5" value="5" selected="selected">5</option>
                  <option label="6" value="6">6</option>
                  <option label="7" value="7">7</option>
                  <option label="8" value="8">8</option>
                  <option label="9" value="9">9</option>
                  <option label="10" value="10">10</option>
                  <option label="15" value="15">15</option>
                  <option label="20" value="20">20</option>
                  <option label="25" value="25">25</option>
                  <option label="40" value="40">40</option>
                  <option label="50" value="50">50</option>
                  <option label="100" value="100">100</option>
                  <option label="200" value="200">200</option>
                  <option label="300" value="300">300</option>
                  <option label="400" value="400">400</option>
                  <option label="500" value="500">500</option>
                </select>

                avg. ticket price:

                <select name="average_price" id="average_price">
                  <option label="$4" value="4">$4</option>
                  <option label="$5" value="5">$5</option>
                  <option label="$6" value="6">$6</option>
                  <option label="$7" value="7">$7</option>
                  <option label="$8" value="8">$8</option>
                  <option label="$9" value="9">$9</option>
                  <option label="$10" value="10">$10</option>
                  <option label="$11" value="11">$11</option>
                  <option label="$12" value="12" selected="selected">$12</option>
                  <option label="$13" value="13">$13</option>
                  <option label="$14" value="14">$14</option>
                  <option label="$15" value="15">$15</option>
                  <option label="$16" value="16">$16</option>
                  <option label="$17" value="17">$17</option>
                  <option label="$18" value="18">$18</option>
                  <option label="$19" value="19">$19</option>
                  <option label="$20" value="20">$20</option>
                  <option label="$25" value="25">$25</option>
                  <option label="$30" value="30">$30</option>
                  <option label="$35" value="35">$35</option>
                  <option label="$40" value="40">$40</option>
                  <option label="$45" value="45">$45</option>
                  <option label="$50" value="50">$50</option>
                  <option label="$75" value="75">$75</option>
                </select>

                donation:

                <select name="donation_rate" id="donation_rate">
                  <option label="15%" value="0.15">15%</option>
                  <option label="20%" value="0.20">20%</option>
                  <option label="25%" value="0.25">25%</option>
                  <option label="33%" value="0.33">33%</option>
                  <option label="40%" value="0.40">40%</option>
                  <option label="45%" value="0.45">45%</option>
                  <option label="50%" value="0.50">50%</option>
                </select>

                # Customers:

                <select name="customers_number" id="customers_number">
                  <option label="10" value="10">10</option>
                  <option label="20" value="20">20</option>
                  <option label="30" value="30">30</option>
                  <option label="35" value="35">35</option>
                  <option label="40" value="40">40</option>
                  <option label="45" value="45">45</option>
                  <option label="50" value="50">50</option>
                </select>

$11,440

sales

2,860

customers

$1,716

donations


Composition of a Realtion with identity is the relation itself

Question: I am completely lost as to how to prove the following, although it appears straightforward. I know how this holds for functions, but how do I prove it specifically for relations? I need to provide a general proof, without taking any specific examples.
This is the question:
Let S be any set, and R be a binary relation on S such that R ⊆ S x S.
Prove that R;I = I;R = R, given that I = {(a,a) | a ∈ S}
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: xI;Ry iff
exists a with (xIa and aRy) iff
exists a with (x = a and aRy) iff
xRy


WPF: Storyboard set property overrides code behind?

Question: I'm working on a wpf c# app and I have a question.
I have a storyboard which at the end sets the property of a grid to Visibility.Visible.
Now on my code behind when I try to set the visibility to hidden again after the storyboard has run, the visibility won't change!
Is the storyboard still running somehow or is a storyboard set property a fixed property after running the storyboard?
Answer: I believe you need to set FillBehavior property:
<code> <Storyboard FillBehavior="Stop">
</code>
Answer: The storyboard is still running. I ran into the same thing myself, where I wanted to run a storyboard when a button was clicked but also to have it re-run from the original state. Setting FillBehavior property to Stop works in this case. However, if you want to keep the end state of the animation until the user clicks the button again, you can't use it. All I did was to stop the storyboard, then set the Visible properties and that solved my problem.  Until I actually called Stop() the values were always overridden. This would also explain why when I set properties that the storyboard wasn't modifying (such as color, etc) I had no problem.


Practise Calc Question

Question: How is the radius $10$ in the circle equation: $x^2+y^2+6x-4y+3=0$?
My work:
Standard Form for circle: $(x-a)^2+(y-b)^2=r^2$
$X:$
$X^2+6x+[?]=-3+[?]$
$(x+3)^2=
X^2+6x+9=-3+9
X^2+6x+9=6$
$Y:$
$Y^2-4y+[?]=-3+[?]  $
$(y-2)^2=
y^2-4y+4=-3+4
y^2-4y+4=-1$
The standard form of the Circle is:
$(x+3)^2+(y-2)^2=r^2$
My question is: How do you find the radius of the circle?
Comment: I think you'll find that the radius of your circle is actually $\sqrt{10}$.
Answer: You have the good idea :
$$x^2+6x=(x+3)^2-3^2\\
y^2 -4y =(y-2)^2-2^2
$$
so
$$x^2+y^2+6x-4y+3=(x+3)^2-3^2+(y-2)^2-2^2 +3$$
From that, I let you find $r$.
Answer: You're given $$x^2+6x + y^2 - 4y = -3$$
Complete the square in $x$ to get
$$(x^2+6x+9) + y^2-4y = -3 + 9$$
Now complete the square in $y$ to get
$$(x^2 + 6x + 9) + (y^2 - 4y + 4) = -3 + 9 + 4$$
And with a little arithmetic, we conclude:
$$(x+3)^2 + (y-2)^2 = 10 = r^2$$
and this immediately gives you the radius.
One way to do this is to get all the $x^2$, $x$, $y^2$, and $y$ terms on one side and then to get the number on the other side.  You then complete the square exactly as you did (at each step making sure that whatever you add to one side, you add the same thing to the other side in order to preserve equality).
Comment: This yielding radius $\sqrt{10}$
Comment: Correct.  I wasn't specifying that, because OP wrote in the question that the LHS is equal to $r^2$.
Answer: We start with\begin{align}x^2+y^2+6x-4y+3&=0 \\
x^2+6x+y^2-4y&=-3 \\x^2+6x+9+y^2-4y+4&=-3+9+4\\(x+3)^2+(y-2)^2&=10 \end{align}
which is of the standard form $(x-h)^2+(y-k)^2=r^2$, where $r$ is the radius and $(h,k)$ is the center of the circle.
Notice that $r^2=10$. Taking square root on both sides, we get $r = \pm \sqrt{10}$. But the radius is an absolute value, so we can omit the negative solution. So we get $\boxed{r=\sqrt{10}}$.

Practise Calc Question


Is the monthly supply drop picked up automatically after a while?

Question: Every month you receive a supply drop, which can be collected over 3 days at a certain spot on the Geoscape.
I ignored that pick up partially and after a while I've received a message saying that all resources have been gathered and new items are available at Resistance HQ. I didn't look at my supplies or the date, when it happened so I neither know whether I got the supplies nor when they expired.
So my question is: Is the monthly supply drop picked up automatically after a while or does it expire and the supplies are lost? How long does it take to expire?
Comment: Pretty sure it expires, can't 100% confirm that right now
Answer: The supplies expire after a certain amount of time, just like any other rumor.
The difference being, whenever the Supply Drop disappears (usually because you have picked up the supplies), you get the popup about new items being available at resistance HQ.
In my experience, you don't need to actually pick up the supplies for new items to be available at resistance HQ.
Comment: I'm not so sure, I recently saw a video, where the player let a partially collected supply drop expire and the remainder was added to his total. Any other opinions here? I currently don't have the time to try it out myself.
Comment: @Dulkan Link to the video?
Comment: https://youtu.be/snQik1P9cDM?t=34m48s You can clearly see the supply drop is at 1.5 days remaining, he starts making contact, but the supply drop ticks down as well and provides resources.
Comment: @Dulkan: Curious, can't explain it.


Google Maps avoiding tolls, highways or ferries in turn by turn navigation intent

Question: I am using Google Maps turn by turn navigation in my app to navigate from the current location to a given address. It works fine, my only problem is that I cannot set up avoid tolls/highways/ferries options via intent.
I followed google descriptions here: https://developers.google.com/maps/documentation/android-api/intents#launch_turn-by-turn_navigation
My code is the following with avoid tolls parameter:
<code>String navigation = "google.navigation:q=" + latLng.latitude + "," + latLng.longitude + "&avoid=t";
Uri uri = Uri.parse(navigation);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
</code>
Navigation starts fine, but it doesn't take notice of the avoid tolls parameter, it opens the driving route through roads, where tolls must be paid.
I also tried &dirflg=t and &avoid=tolls parameters, but no result.
Does anybody have some solution for this?
Thank you!
Comment: UPDATE: It works on API 21, but still NOT works on API 17 device.
But I cannot find any descrition about the minimum system requirement of this option. Does anybody have some idea how could I find this out?
Comment: Maybe the problem is in how you set your code, try to follow the exact code on the given [documentation](https://developers.google.com/maps/documentation/android-api/intents#launch_turn-by-turn_navigation). Provide some address and copy the same format of the code. Now, check if the avoid parameter is working. Check also this [ticket](http://stackoverflow.com/questions/36905919/android-use-google-api-for-real-time-directions-or-communicate-with-google-map) about the turn by turn navigation service.
Comment: Thank you for your help, but unfortunately this didn't solve my problem. I added now the destination address in the same format as it is written in the documentation, but it also returned with a route on highways.
Anyway, I tried my original code also on an API 19 device, and it works, so I can solve it by raising the minimum API to 19 from 17 (it is not a big problem, I think) Thanks again!
Answer: I think it's a bug in some of the android implementations on some devices.
I have the same problem. The same code runs fine on an A3 (2016), but not on an Xcover 3. Both on Lollipop (API 22) but on slightly different versions (newer on the A3). Maybe an update will help.


Can drills (and other FTB tools) be enchanted in survival mode?

Question: First of all i am aware of this question:
Is it possible to enchant IndustrialCraft items?

The answer from Euphoric states it can be done using books. This is
  confirmed by the FTB-wiki: This item cannot be enchanted
  traditionally, however can be enchanted using books.
However in the comments of that particular answer SevenSidedDie notes
  that this only works on creative mode where every item can be
  enchanted. Just tested: does not work in Survival mode. (It does work
  in Creative mode, but that's to be expected since you can put any
  enchant on any item while in Creative mode.)

I cannot find a clear internet source for this, some say it cannot be done while some say you can. So can drills and other FTB tools be enchanted by books or other means? And if not, are there mods that allow this?
Comment: Hey man, YOu can offer a bounty on the other question to get new information and such but this will likely get closed as a duplicate since all this is asking is for the other answer to be validated/brought up to date.
Comment: Then we will never know since i do not think a bounty will help the question i quoted as it stands now. I tried commenting on the answer but that did not yield information at all. I might cheat on another world to see if i can enchant drills somehow.
Answer: Yes many power tools and special armor can be enchanted. This may not be working as intended, so keep in mind future patches and updates may remove your enchantments. Use an anvil and an enchanted book of your requested effect, and voila!, your new drill or chainsaw now has Fortune I! Keep in mind that if you enchant an item that runs on an internal battery, and you allow that battery to run dry, the enchantment will be lost.
I personally do this to my Advanced Diamond Drill every game.
Comment: Keep in mind that the anvil will incur additional level cost. A drill or chainsaw can be enchanted with the same enchantments that work on pick/shovel and axe respectively. A Power Tool can also be enchanted.
Answer: They are not meant to be enchanted and in survival it is definitely not possible. I am not aware of any mod that would allow you to enchant them, however you could ask someone who developes mods to make such a mod. However, a lot of vanilla enchants wouldn't make sense on an electric tool anyway.
Comment: Well i just created a new survival world and cheated myself some items and experience. I was able to enchant my drill with "efficiency I". This is clearly an unknown topic. I will answer my question and post screenshots when i did a bit more research.


SSRS No Query Designer is Available

Question: I just created a data source  and now I'm adding a data set. I'm using a dataset that is embedded in my report and then I go click on Query Designer... and it tells me No cube can be found. I click okay and then it tells me No Query Designer is Available. Every time I click on Query Designer... again, it just goes straight to the No Query Designer is Available window.
I looked around for some answers, and some people said that the cube's visibility might be set to false in its properties. However, I checked and it was true. I don't know what to do anymore.
Is there any way I can get this MDX Query Designer window to open? Did I do something wrong?
Answer: I don't know if you managed to fix this problem, but when it happened for me it turned out to be a permissions issue with my data source.
I'll put this as an answer here just in case it helps anyone else out - I found the cube visibility answers quite misleading (although obviously it has helped some people).
Answer: I was able to fix this same problem.
I had an embedded datasource defined that connected to my cube. I temporarily created another dataset, selected to embed this dataset in my report, selected the embedded datasource and then attempted to use the Query Designer. It worked for this new dataset. So I then cancelled the creation of the new dataset, went back to the old non-working dataset and was able now open the Query Designer window

SSRS No Query Designer is Available


How to perform multiple tricks whilst airborne

Question: I am able to perform tricks whilst preparing my ollie on the ground, but I don't seem to be able to perform any subsequent tricks whilst in the air.
What button combinations should I use to perform multiple tricks whilst in the air, or do you just complete one trick and then focus on getting your landing right?
Answer: Having played this much more now it seems that you cannot perform any additional tricks whilst airborne.
You prepare your kick trick whilst travelling along the ground or a rail then execute it. Once it has been executed, the trick is complete and it's time to focus on your landing.
In order to keep performing tricks, you'll want to land in a manual. L-Stick (left or right) + X as close to the ground as you can manage.


Connection refused when Host OS(Ubuntu) telnet the Guest OS(Windows XP) of the Virtualbox

Question: I can't telnet the Guest OS(Windows xp) in my ubuntu machine but I can successfully ping its IP address.
In the network settings of guest os, I enabled two adapters. Here are the  the settings of the two adapters.
For the first adapter:
Attached to: NAT
Adapter: Intel PRO/1000 MT Server(82545SEM)
Promiscuous Mode: Deny
Cable Connect: enabled

For the second adapter:
Attached to: Host-only Adapter
Name: vboxnet0
Adapter: Intel PRO/1000 MT Desktop(82545SEM)
Promiscuous Mode: Deny
Cable Connect: enabled

I added port 1234 in the Exceptions of Windows Firewall Settings in guest OS just for testing. I can ping the IP Address and ssh the Host OS.
This is the result when I executed the telnet command.
user@micmic:~$ telnet 192.168.56.101 1234
Trying 192.168.56.101...
telnet: Unable to connect to remote host: Connection refused

Answer: Make sure you installed the following packages:
sudo apt-get install ssh
sudo apt-get install telnetd-ssl
sudo apt-get install openssh-server


Java - WebSocket sending Hex 0x0A

Question: I have been working on Android(Java) App, to create a websocket server,
all went good, and the connection is accepted.
The problem is sending a message to client (Browser webSocket)
    OutputStream writer = client.getOutputStream();
    // FIN OPCODE 1000 0001
    writer.write(0x81);

    // message length
    writer.write(0x5);

    writer.write('H');
    writer.write('e');
    writer.write('l');
    writer.write('l');
    writer.write('o');
    writer.flush();

I got an Error : failed: Invalid frame header
i installed webshark to see the problem:

On the Right you will see the data
- 0x0A  -> the problem.

0x81  -> FIN & OPCODE (10000001)
0x05  -> length of the message
0x48 0x65 0x6c 0x6c -> Hell

====== MORE CODE =======
How i read the client request (headers) ?
private String readClientInputStream() {
    String str = null;
    try {
        InputStream in = client.getInputStream();
        byte[] buffer = new byte[1024];
        int countBytesRead = in.read(buffer);
        if (countBytesRead > 0) {
            str = new String(buffer, 0, countBytesRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return str;
}

Using str to get Sec-WebSocket-Key and sending response (handshake):
public void sendWebSocketHandShake(String str) {
    String[] result = str.split("Sec-WebSocket-Key: ", -1)[1].split("\\n");
    String key = makeKeyAccept(result[0]); // METHOD CODE BELLOW
    StringBuilder handshake_str = new StringBuilder();
    handshake_str.append("HTTP/1.1 101 Switching Protocols\n");
    handshake_str.append("Upgrade: websocket\n");
    handshake_str.append("Connection: Upgrade\n");
    handshake_str.append("Sec-WebSocket-Accept: ").append(key).append("\n");
    handshake_str.append("\n");
    try {
        OutputStream out = client.getOutputStream();
        byte[] b = handshake_str.toString().getBytes(StandardCharsets.UTF_8);
        out.write(b, 0, b.length);
        out.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

How i make Sec-WebSocket-Accept key ?
   public String makeKeyAccept(String key) {
        String _acceptKey = key.trim() + WEBSOCKET_KEY_MAGIC;
        MessageDigest digest = null;
        String base64 = null;
        try {
            digest = MessageDigest.getInstance("SHA-1");
            digest.update(_acceptKey.getBytes(StandardCharsets.UTF_8));
            byte[] encoded = android.util.Base64.encode(digest.digest(), 0, digest.getDigestLength(), android.util.Base64.DEFAULT);
            base64 = new String(encoded, 0, encoded.length, StandardCharsets.UTF_8);
        } catch (Exception ignore){}

        return base64;
    }

Comment: @MarkRotteveel Thank you for your help .. i fixed it by using trim after base64
Comment: Please provide a [mre].
Comment: do you need more code ? @MarkRotteveel , its a webSocket, handshake is made and working, after that comes the problem when i send a text message to client socket.. i even know the problem `(0x0A)`
Comment: And how do we know the 0x0A (\n or linefeed) is not just a leftover byte from your handshaking process? We need a [mre] to see that.
Comment: @MarkRotteveel i see, i will put more code, Thanks
Comment: @MarkRotteveel Note: end of the response the `\r\n` not working, thats why i'm using only `\n`. Thanks for your time
Answer: Thank you @MarkRotteveel
As he told me the problem could be from the handshake and left over byte..
i fixed it by using trim() after creating the key base64

Java - WebSocket sending Hex 0x0A


Minimize ratio by linear program

Question: This is not a homework problem. It is from a closed MITs 2016 advanced algorithms class.

Here is my proposed solution:
We can run the linear program
$$\begin{array}{ll} \text{maximize} & f^T x\\ \text{subject to} & A x \geq b\\ & f^T x \geq 1\\ & -8 \leq c^T x \leq 8\end{array}$$
If the linear program is infeasible then the problem is infeasible, and if the linear program is unbounded then the solution is $0$. Suppose neither of these is the case. Then $ -8\leq \frac{c^Tx}{f^Tx} \leq 8$, and the idea is to do binary search until the possible interval that $\frac{c^Tx}{f^Tx}$ lies in is of size $\leq \epsilon$.
So for the $i$th iteration of the algorithm suppose $ L \leq \frac{c^Tx}{f^Tx} \leq U$. $\frac{c^Tx}{f^Tx} \leq \frac{L+U}{2}$ if and only if $c^Tx - \frac{(f^Tx)(L+U)}{2} \leq 0$, since $ f^Tx \geq 1$. So if we run the linear program,
$$\begin{array}{ll} \text{minimize} &  c^Tx - \frac{(f^Tx)(L+U)}{2} \\ \text{subject to} & A x \geq b\\ & f^T x \geq 1\\ & -8 \leq c^T x \leq 8\end{array}$$
, and we get a value of $0$ or less, then we have $ L \leq \frac{c^Tx}{f^Tx} \leq \frac{U + L}{2}$, else we have $ \frac{L + U}{2} \leq \frac{c^Tx}{f^Tx} \leq U$.
We then repeat this process until $U-L \leq \epsilon$ and we take $U$ as our answer.
The running time of this algorithm is $k$, where $\frac{16}{2^k} \leq \epsilon$ so $k\leq \log(\frac{16}{\epsilon})$.
Is this a correct solution to the problem?
Edit: There is actually a $O(\frac{1}{\epsilon})$ solution(by someone else); However I'm still not sure if my $O(log(\frac{1}{\epsilon}))$ solution is any good.
Comment: Please understand that I don't know you. I do not recall any other posts of yours around here. Which means I am not familiarised with your way of thinking.  This does not mean that your work is not interesting. It just means that understanding your work in detail requires more than what my time-energy budget allows. When such budget allows, I will try to revisit this question.
Comment: I haven't learned about the epigraph form(from the course) yet, so I don't know what that is. However, does this mean that my solution is not correct? Also when I ran the first linear program to maximize $f^Tx$ it should have told me whether $\frac{c^Tx}{f^Tx}$ is feasible or not. It also seemed like all the linear programs I run in my solution have linear constraints and linear objective functions, so I should be able to input them in the black box mentioned in the question.
Comment: I also just minimize $c^Tx-\frac{(f^Tx)(L+U)}{2}$ in order to see whether or not there exist an x such $\frac{c^Tx}{f^Tx} \leq \frac{L+U}{2}$. I think I can do this because as explained above $f^Tx$ is positive.
Comment: It's ok thankyou anyways. Will you have time so another day? And also is my solution, not clear. Since I haven't been receiving any responses.
Comment: Ok, but I don't understand why instead of doing that we just run the linear program I said above (minimize $c^Tx-\frac{(f^Tx)(L+U)}{2}$) to find an upper bound/ lower bound for $\frac{c^Tx}{f^Tx}$. Since we know in the worst case there will be a feasible solution when $-8 \leq \frac{c^Tx}{f^Tx} \leq 8$.
Comment: Ok, that soundsd fair enough. In the meantime is there anything I can do to get someone else's response?
Comment: You can try to find questions you can answer in order to accumulate some, say, 100 reputation points so that you can start a bounty that motivates others to expend some of their time.
Answer: Hint: Introduce optimization variable $y$, make the objective $y$ and append the constraint $$\frac{c^Tx}{f^Tx} \leq y$$ Note that the denominator is positive. Then, pick, say, $y =2$ and use linear programming to determine whether the constraints define an empty polytope or not. If the polytope is non-empty, then pick, say, $y = 1$ and so on. Once you find an empty polytope, use binary search to adjust $y$ till you find a "decent" approximation for the minimum. My guess is that this is what the authors meant by "within any degree of accuracy".

Minimize ratio by linear program


render a new comment form at the end of post#show

Question: For a basic blog application (Post has_many comments) I want to display a new comment form at the end of post#show. But I'm stuck with the mechanics of building it and rendering the web/templates/comment/form.html.eex in web/templates/user/show.html.eex. The application:
mix phoenix.new my_app
cd my_app
mix ecto.create
mix phoenix.gen.html Post posts content:string
mix phoenix.gen.html Comment comments content:string \
post_id:references:posts
mix ecto.migrate

web/models/post.ex
defmodule MyApp.Post do
  use MyApp.Web, :model

  schema "posts" do
    field :content, :string
    has_many :comments, MyApp.Comment

    timestamps
  end

  @required_fields ~w(content)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

web/models/comment.ex
defmodule MyApp.Comment do
  use MyApp.Web, :model

  schema "comments" do
    field :content, :string
    belongs_to :post, MyApp.Post

    timestamps
  end

  @required_fields ~w(content post_id)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

In the Post controller I have the first problem. This code doesn't work (key :post not found in: %{} error):
web/controllers/post_controller.ex
[...]
def show(conn, %{"id" => id}) do
  post = Repo.get!(Post, id)

  changeset =
    conn.assigns.post
    |> build_assoc(:comments)
    |> Comment.changeset()

  render(conn, "show.html", post: post, changeset: changeset)
end
[...]

The next problem is that I have no idea how to render the form. The following code doesn't work:
web/templates/post/show.html.eex

Show post

    Content:
    <%= @post.content %>

<%= render "comment/form.html", changeset: @changeset,
                        action: comment_path(@conn, :create) %>

How can I fix this?
Answer:
In web/controllers/post_controller.ex, replace conn.assigns.post with just post as that's the actual name of the variable.
To render a template from another view, (you want to render web/templates/comment/form.html.eex from web/templates/post/show.html.eex), you need to pass the view of the target template as the first argument:
render MyApp.CommentView, "form.html", ...

That's because the render in the controller is Phoenix.Controller.render/4 while the one available inside views and templates is Phoenix.View.render/3 and they expect different parameters.


Inequality on the expectations of the inverse of random variables

Question: Given $X$ and $Y$ two positive random variables such that $\mathbb E[X] = \mathbb E[Y]$ and $\mathbb E\left[X^2\right] > \mathbb E\left[Y^2\right]$ is it true that $\mathbb E\left[\frac1X\right] > \mathbb E\left[\frac1Y\right]$?
Comment: Can you atleast add more context to your question?. Where did you encounter it? What are the ideas you have of showing it? Isolated problems like these attract downvotes and closure.
Comment: Presumably you have tried examples, no?  Could you include some of those?
Comment: Note:  it might help to note that, given that the means coincide, the second condition is equivalent to saying that the variance of $X$ is greater.
Comment: I also noticed that E[X^2] > E[Y^2] implies Var[X]>Var[Y] due to Var[X]=E[X^2]+(E[X])^2. For unimodal distributions, there is a clear graphical intuition for the proposition because the increased variance leads the tails of the distribution to spread out further to the left and right of the expected value. Since 1/x is a convex function for x>0, values to the left of the mean are overemphasized when computing E[1/X]. The statement is easy to verify for many simple distributions like uniform distributions w. different supports, but I am unsure how to approach it for more "ugly" distributions.
Comment: Are $X$ and $Y$ independant?
Comment: Thanks for the remark, yes they are independent.
Answer: No.
Let $$X\sim
\begin{cases}
1000, \text{ with probability } 0.5\\
10, \text{ with probability } 0.5
\end{cases}
$$
and $$Y\sim
\begin{cases}
1000, \text{ with probability } 0.49\\
100, \text{ with probability } 0.49-p\\
1, \text{ with probability } p.
\end{cases}
$$
Then for $p=\frac{34}{99}\approx0.343$, we have $$\mathbb{E}[X]=\mathbb{E}[Y],$$ and $$\mathbb{E}\left[X^2\right] = 1000^2(0.5)+10^2(0.5) >1000^2\left(0.49\right)+100^2\left(0.147\right)+1^2\left(0.343\right) = \mathbb{E}\left[Y^2\right],$$
but
$$ \mathbb{E}\left[\frac{1}{X}\right] <\frac{1}{10}< p < \mathbb{E}\left[\frac{1}{Y}\right].$$


Change colour of text of a column based on the value of another column within the same dataframe using pandas stylers

Question: I am trying to change the color of text in a column dependent on the value of another column within a data frame and then host on Streamlit app.
The dataframe contains 5 columns. The column names are as follows:-
df.columns = ['energy_kwh', 'energy_cumsum_kwh', 'threshold', 'energy_consumption', 'Check']

I want the 'check' column to show that within a given row, if the 'threshold' column is greater than the 'energy_consumption' columns then the text in the 'check' column of the given row should be green but if the 'energy_consumption column' is greater than the 'threshold' column within a given row then the text should be red. I have attempted to use the df.style.apply and df.style.applymap method but have been unable to find a solution. Please see below my attempts:-

def highlight(val):
    color = 'red' if val.energy_consumption > val.threshold else 'green'
    return 'color: %s' % color

df_style = df.style.applymap(highlight, subset=['Check'])
st.dataframe(df_style)

def highlight(row):
    if row['energy_consumption'] > row['threshold']:
        return 'color: %s' % 'red'
    elif row['energy_consumption'] < row['threshold']:
        return 'color: %s' % 'green'

df_style = df.style.applymap(highlight, subset=['Check'])

st.dataframe(df_style)

col = df['threshold']

def color_survived(col):
    color = 'red' if df['threshold'] <(df.energy_consumption)
                  else df['threshold'] <(df.energy_consumption) else 'green'
    return 'color: %s' % color

st.table(df.style.applymap(color_survived), subset=['energy_kwh'])

I would like the final dataframe to look like this:-

Would appreciate help on how to approach this problem and also what I am doing wrong.
Answer: applymap evaluates each cell individually but you need to apply the highlighter on the entire table, which can be achieved via apply.
def highlighter(x):
    # initialize default colors
    color_codes = pd.DataFrame('', index=x.index, columns=x.columns)
    # set Check color to red if consumption exceeds threshold green otherwise
    color_codes['Check'] = np.where(x['energy_consumption'] > x['threshold'], 'color:red', 'color:green')
    return color_codes

# apply highlighter to df
df_style = df.style.apply(highlighter, axis=None)


Logic to create array of array in JavaScript

Question: I have a little problem with this logic. I need to create a dynamic Array of Array. But the last object in every Array is not correct. I try some way but still not found expected result.
Here the snippet code :

const data = [{
      "order-nr": 1,
      "article": "Burger"
    }, {
      "order-nr": 1,
      "article": "Soup"
    }, {
      "order-nr": 1,
      "article": "Noodle"
    }, {
      "order-nr": 2,
      "article": "Steak"
    }, {
      "order-nr": 2,
      "article": "Chicken Wings"
    }, {
      "order-nr": 3,
      "article": "Coffee"
    }, {
      "order-nr": 4,
      "article": "Rice"
    }]

    let tempDataArticle = [];
    let dataArticle = [];
    let orderNr = 1;
    let indexOrderNr = 0;

    for (let i = 0; i < data.length; i++) {
      const datarow = data[i];
      dataArticle.push(datarow);

      if (datarow['order-nr'] === orderNr) {
        tempDataArticle[indexOrderNr] = dataArticle;
      } else {
        tempDataArticle[indexOrderNr] = dataArticle;
        orderNr = orderNr + 1;
        dataArticle = [];
        indexOrderNr = indexOrderNr + 1;
      }
    }

    console.log((tempDataArticle));

Output :
  [
    [{
        "article": "Burger",
        "order - nr": 1
    }, {
        "article": "Soup",
        "order - nr": 1
    }, {
        "article": "Noodle",
        "order - nr": 1
    }, {
        "article": "Steak",
        "order - nr": 2
    }],
    [{
        "article": "Chicken Wings",
        "order - nr": 2
    }, {
        "article": "Coffee",
        "order - nr": 3
    }],
    [{
        "article": "Rice",
        "order - nr": 4
    }]
 ]

Here reproduce code.
Expected Result :
[
[{
    "article": "Burger",
    "order - nr": 1
}, {
    "article": "Soup",
    "order - nr": 1
}, {
    "article": "Noodle",
    "order - nr": 1
}],
[{
    "article": "Steak",
    "order - nr": 2
}, {
    "article": "Chicken Wings",
    "order - nr": 2
}],
[{
    "article": "Coffee",
    "order - nr": 3
}],
[{
    "article": "Rice",
    "order - nr": 4
}]
]

My expected result there is 4 Array base on order-nr key. So the total sub Array will depend on order-nr key.
Comment: What is your expected result?
Comment: I'm sorry, please check again my edit
Comment: You said the last object in every array is not correct. What is incorrect about them? The only difference I see is that the expected result contains strings
Comment: Sorry and please check again my edit. Current result (output), I have 3 sub array. And last object of that sub array is not correct. My expected result there are 4 sub array. The sub array must depend on value of `order-nr` key.
Comment: I see. Sorry my bad I didn't see that earlier
Comment: Note that we prefer a technical style of writing here. We gently discourage greetings, hope-you-can-helps, thanks, advance thanks, notes of appreciation, regards, kind regards, signatures, please-can-you-helps, chatty material and abbreviated txtspk, pleading, how long you've been stuck, voting advice, meta commentary, etc. Just explain your problem, and show what you've tried, what you expected, and what actually happened.
Answer:

const data = [{
      "order-nr": 1,
      "article": "Burger"
    }, {
      "order-nr": 1,
      "article": "Soup"
    }, {
      "order-nr": 1,
      "article": "Noodle"
    }, {
      "order-nr": 2,
      "article": "Steak"
    }, {
      "order-nr": 2,
      "article": "Chicken Wings"
    }, {
      "order-nr": 3,
      "article": "Coffee"
    }, {
      "order-nr": 4,
      "article": "Rice"
    }]

let tempDataArticle = [];

for (let i = 0; i < data.length; i++) {
   const order = data[i];

    if(!tempDataArticle[order['order-nr'] - 1])
        tempDataArticle[order['order-nr'] - 1] = [];

    tempDataArticle[order['order-nr'] - 1].push(order)
}

console.log(tempDataArticle);
Comment: Thank you for anwser. Something new for me . I didn't know Javascript can do `tempDataArticle[order['order-nr'] - 1].push(order)` . Usualy I create temporary container to reuse case like this.
Comment: I'm glad I could help!
Answer: Multiples problems here :
indexOrderNr = indexOrderNr + 1; was happening after you detected the item from another order, so the first item of an order would be added to the previous order.
You modified tempDataArticle[indexOrderNr] at every iteration, which is bad since you really don't need to and it makes the program do the same thing multiple times.
Since dataArticle.push(datarow); is done at the start of a new iteration, you add an item to an order without even checking from which order this item is from.
Friendly advice, you can save a lot of time by first working your logic on paper and then start to code.
Here is a working code snippet :

const data = [{
      "order-nr": 1,
      "article": "Burger"
    }, {
      "order-nr": 1,
      "article": "Soup"
    }, {
      "order-nr": 1,
      "article": "Noodle"
    }, {
      "order-nr": 2,
      "article": "Steak"
    }, {
      "order-nr": 2,
      "article": "Chicken Wings"
    }, {
      "order-nr": 3,
      "article": "Coffee"
    }, {
      "order-nr": 4,
      "article": "Rice"
    }]

    let tempDataArticle = [];
    let dataArticle = [];
    let orderNr = 1;
    let indexOrderNr = 0;

    for (let i = 0; i < data.length; i++) {
      var datarow = data[i];

      if (datarow['order-nr'] === orderNr) {
        dataArticle.push(datarow);
      } else {
        tempDataArticle[indexOrderNr] = dataArticle;
        orderNr = orderNr + 1;
        dataArticle = [];
        dataArticle.push(datarow);
        indexOrderNr = indexOrderNr + 1;
      }
    }
    tempDataArticle[indexOrderNr] = dataArticle;

    console.log((tempDataArticle));
Comment: Thank you for the answer. It's work. But i don't understand assigning `tempDataArticle` on line `tempDataArticle[indexOrderNr] = dataArticle;`. Its outside on loop. But `dataArticle` will replace with new `[]` if condition doesn't meet
Comment: At every iteration, the code checks if an article is from `orderNr`.
If Yes, add that article to `dataArticle`.
If No, then we have all the articles of an order so it put them in `tempDataArticle[indexOrderNr]`. It then creates and another empty `dataArticle`, and adds the article from the new order.
However, if this is the last order. The articles from the last order are not yet added since they are added only if it detects an article from a different order. So it needs to add the last order after the for loop is done.
Comment: However, I would recommend Alex Spelt solution, since it's more robust. With his solution, you can have the articles of every order not in order and it will work.
Comment: I see, I didn't see another assignment from tempDataArticle. I only see in outside loop. Thank you for the explanation. I still use this answer because there are another code inside the loop.
Answer: how about this solution:

const data = [{
    "order-nr": 1,
    "article": "Burger"
}, {
    "order-nr": 1,
    "article": "Soup"
}, {
    "order-nr": 1,
    "article": "Noodle"
}, {
    "order-nr": 2,
    "article": "Steak"
}, {
    "order-nr": 2,
    "article": "Chicken Wings"
}, {
    "order-nr": 3,
    "article": "Coffee"
}, {
    "order-nr": 4,
    "article": "Rice"
}]

let newArr = [];

data.forEach(item => {
    if (newArr[item["order-nr"] - 1] === undefined) {
        newArr[item["order-nr"] - 1] = []
    }
    newArr[item["order-nr"] - 1].push(item);
})

console.log(newArr);


How to reuse toggle buttons

Question: I'm trying to find a best way to reuse a toggle button. I want from the toggle button widget to take as low parameters as possible which is List of strings which will build toggle buttons and selected string which will be used to select toggle button. And from onPressed in toggle button I want to return selected string which update selected string in main class. If selected value is null or doesn't match list then select and update selected to first string in toggle list. Here is where I get so far... (Sorry... having really tough time with it)
Here is toggle button widget
class ReuseToggle extends StatelessWidget {
  final List<String> children;
  final String selected;
  final Function onPressed;

  const ReuseToggle({this.selected, this.onPressed, this.children});
  @override
  Widget build(BuildContext context) {
    return ToggleButtons(
      children: children.map((text) => Text(text)).toList(),
      onPressed: (int index) {
        print(index);
      },
/// logic from official documentation
//        for (int buttonIndex = 0;
//            buttonIndex < isSelected.length;
//            buttonIndex++) {
//          if (buttonIndex == index) {
//            isSelected[buttonIndex] = true;
//          } else {
//            isSelected[buttonIndex] = false;
//          }
//        }
//      },
      isSelected: [true, false],
    );
  }
}

and main class
class MaterialScreen extends StatefulWidget {
  @override
  _MaterialScreenState createState() => _MaterialScreenState();
}

List<String> list = ['value1', 'value2'];
String selectedToggle;

class _MaterialScreenState extends State<MaterialScreen> {
  Widget build(BuildContext context) {
    return ReuseToggle(
      children: list,
      selected: selectedToggle,
      onPressed: (value) {
        setState(() {
          selectedToggle = value;
        });
      },
    );
  }
}

Answer: Here is one solution however you will have to initialise your selectedToggle in your main class. This way if the selectedToggle is null your toggle buttons will be unselected and your selectedToggle updates on first onPressed.
class ReuseToggle extends StatelessWidget {
  final List<String> children;
  final String selected;
  final Function onPressed;

  const ReuseToggle({this.selected, this.onPressed, this.children});
  @override
  Widget build(BuildContext context) {
    List<bool> isSelected = [];
    for (int i = 0; i < children.length; i++) {
      if (children[i] == selected) {
        isSelected.add(true);
      } else {
        isSelected.add(false);
      }
    }

    return ToggleButtons(
      children: children.map((text) => Text(text)).toList(),
      onPressed: (int index) {
        for (int buttonIndex = 0;
            buttonIndex < isSelected.length;
            buttonIndex++) {
          if (buttonIndex == index) {
            isSelected[buttonIndex] = true;
          } else {
            isSelected[buttonIndex] = false;
          }
        }
        onPressed(children[index]);
      },
      isSelected: isSelected,
    );
  }
}

Comment: Thanks... Ok.. I will try that and let you know

How to reuse toggle buttons


How to make presentations in using HTML5?

Question: I wanted to know that how can we make a presentations using HTML5. I am talking about the presentations that look like the Powerpoint presentations but are entirely made using HTML5,CSS3 and JavaScript. To point out to some example so that one could understand better just have a look on these pages whose link is mentioned below.

http://slides.html5rocks.com/#landing-slide
http://www.cambridgesemantics.com/2008/09/sparql-by-example/#%281%29

and many other available online. Please provide me with a suggestion of frameworks used or some tutorials that can make my life easier with such presentations.
Comment: Step #1 Find an existing site for such (done) #2 *Learn from said site* (do now! :) #3 Profit! (pending).
Answer: I think you may be after this kind of framework:
http://www.ravelrumba.com/blog/html5-slideshow/
I do also believe this has been asked/answered on here before, but hope it helps!
Comment: Great article. I would get along and respond you back. Thanks
Answer: You may also want to look at Eric Meyer's S5 framework.
Answer: You can hand code HTML5/CSS3 which will take you a while;  You can use Google docs for very simple looking presentations.   If you want to go up a couple notches in design You can use this tool;  they're in Beta but it's pretty flexible and you can even animate your HTML5 objects;   www.ewcPresenter.com


How to view a particular unicode character?

Question: I am currently using Quantal and I am trying to write in Oriya, a South Asian language. The problem is even though changing the keyboard layout to Oriya works in most cases, I am unable to type the Unicode character 0B5F (Oriya Character YYA).
In Fedora, it used to work by using the combo Shift+/.
I've changed one of the lines in the section xkb_symbols "ori" in /usr/share/X11/xkb/symbols/in from
key <AB10> { [  U0b2f, U0040    ] };

to
key <AB10> { [  U0b2f, U0b54    ] };

But when I type in gedit, I get a strange box-like character filled with 0B5F.
How do I fix the keyboard mapping so that I can print the Unicode 0B5F on screen?
Answer: The strange box like character filled with 0B5F indicates that the character being referenced is indeed U+0b5f, but the font doesn't support it.
Try changing the font you're using in gedit to a font that does support Oriya symbols
Menu > Edit > Preferences > TAB(Font & Color) > Editor Font

Comment: Changing to Lohit Oriya font did not help.
Comment: does your square box contain 0b54 or 0b5f? I've managed to get gedit to show the ୟ (U+0b5f) symbol, but the (U+0b54) seems not to map to a symbol in Oriya symbols (and you've mentioned U=0b54 in your question above)
Comment: should the entry in X11/xkb/symbols/in say "key  { [  U0b2f, U0b5f    ] };" instead of "key  { [  U0b2f, U0b54    ] };"
Comment: Man... what a newb mistake!! Of course it was U0b5f. Now I feel silly asking this question!! Thanks for the observation.
Comment: Yup, works like a charm.
Answer: General answer on "how to type a Unicode Character?"
Example, to get this symbol ⌀
Do:

Ctrl+Shift+u you will get ̲u
now you can release your fingers out of the keyboard
and continue by typing your Unicode 2300 , now you have: ̲u̲2̲3̲0̲0
press your spaceBar and you get ⌀

To know the list of Unicode characters, consult this list.

So for your code 0b5f: Ctrl+Shift+u and 0b5f gives ୟ


How can i use jquery validation framework on a select tag

Question: How can i use Jquery validation framework on  a select tab
This is my fiddle
http://jsfiddle.net/2yXsL/377/
I have tried as
<select  id="BsnessType" name="BsnessType" class="span12 valid">
<option value="SELECT">SELECT</option>
<option value="101">Theatre</option>
<option value="102">Restaurant</option>
</select>

$('#mailer').validate({
    focusInvalid: false,
    debug: true,
    rules: {
        name: {
            required: true
        },
        email_address: {
            required: true,
        },
        BsnessType: {
            required: true,
        }

    },
    messages: {
        name: {
            required: 'name required'
        },
        email_address: {
            required: 'email required',
            email: 'email address is not valid'
        },
         BsnessType: {
            required: 'BsnessType is required',

        }

    },
      submitHandler: function(event, validator) {
      if ($("#mailer").valid()) {
        callformsubmit();
        return false;
      }
    }

});

please let me know how to do this ??
Answer: Set empty value for option SELECT. Here is your fiddle updated.. The empty value means that is nothing there and it will trigger required validation.
<option value="">SELECT</option>


coverage.py and setup.py and Django testing

Question: I have a Django project with setup.py which looks like this:
.
├── backend
├── backoffice
├── backoffice_set
├── manage.py
├── MANIFEST.in
├── media
├── README.rst
├── requirements.txt
├── setup.py
└── venv2.7

When I run: python setup.py test everything is O.K.. However, when I run :
/opt/bin/coverage run setup.py test

The tests fail with:
writing dependency_links to cfe_backoffice.egg-info/dependency_links.txt
reading manifest template 'MANIFEST.in'
warning: no files found matching '*' under directory 'backoffice/templates/backoffice/'
writing manifest file 'cfe_backoffice.egg-info/SOURCES.txt'
running build_ext
Traceback (most recent call last):
  File "setup.py", line 21, in <module>
    setup(
  File "/opt/lib/python2.7/distutils/core.py", line 152, in setup
    dist.run_commands()
  File "/opt/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/opt/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "build/bdist.linux-i686/egg/setuptools/command/test.py", line 138, in run
    self.with_project_on_sys_path(self.run_tests)
  File "build/bdist.linux-i686/egg/setuptools/command/test.py", line 118, in with_project_on_sys_path
    func()
  File "build/bdist.linux-i686/egg/setuptools/command/test.py", line 164, in run_tests
    testLoader = cks
  File "/opt/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/opt/lib/python2.7/unittest/main.py", line 149, in parseArgs
    self.createTests()
  File "/opt/lib/python2.7/unittest/main.py", line 158, in createTests
    self.module)
  File "/opt/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/opt/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'runtests'

Has anyone seen this before? Can you suggest a solution?
Answer: Well, after a while I found the solution.
Django was not installed globally, which is what I wanted.
I created my virtual environment with:
 virtualenv --enable-system-packages

So this lead to coverage.py not being installed inside my virtualenv. Hence the solution, which was to force pip to install it with -I, here is the full log of actions:
/opt/bin/virtualenv --system-site-packages venv2.7
. venv2.7/bin/activate
pip install -r requirements.txt
pip install -I coverage
coverage run setup.py test


How do I do an inverted ledge takedown?

Question: To earn one of the medals in Batman: Arkham City's Police Brutality (Extreme) Predator Challenge, I'm supposed to do an inverted ledge takedown. I've tried standing on ledges above enemies, but never get the takedown notification. What am I doing wrong? How do I perform an inverted ledge takedown?
I'm playing as Batman.
Comment: I believe you can only do this while on a balcony or in a doorway.
Comment: @Ullallulloo I'm playing as Batman. I've edited my question to include that detail.
Answer: The Inverted Ledge Takedown requires you to stand on a ledge such as a guardrail. Once you have an enemy approaching below you, and you're given the Takedown prompt, wait a few seconds for the enemy to be facing the opposite direction. (i.e.: If you're facing away from the wall, wait until your target is facing the wall) This YouTube video posted in another answer shows exactly how it's done (It should start just a few seconds before the takedown). Basically, the bat is facing the opposite direction of the target when he performs the takedown.
Here's a picture showing the actual takedown (to avoid link rot):

By default:

PC - Right Click
Xbox 360 - Y
PS3 - Triangle

I played on the Xbox 360, so I'm not 100% on the controls for the PC. If someone makes a correction in the comments, I will edit it into the answer to correct the controls.
Comment: This is an Inverted Takedown. I need to do an Inverted *Ledge* Takedown.
Comment: @splatteredbits Sorry. I was confused. I amended the answer to correct the error.
Answer: This one is a pain in the neck.  I seem to remember doing this on the "Gotham PD" level, which has been frozen over by Mr. Freeze.
The strategy I used was to knock everyone out except for the guy wearing the scrambler backpack (since taking him out last is one of the other challenges).  Then, throw a sonic batarang into one of the two large side rooms that have railings over the doorways.
After he heads into the room, stand on the railing above the open doorway.  When the thug is finished investigating the batarang and heads back out towards the center area, you can do the inverted ledge takedown on him.
This guy doesn't use my strategy (although he manages to do it quite a bit quicker) but you can watch him get the takedown here:
Answer: You can only do an inverted ledge takedown while standing on on a gargoyle statue. When an enemy walks below you, press the counter button (Trinagle on PS, Y on XBox) to do the takedown.
Comment: You're describing an Inverted Takedown. I need to do an Inverted *Ledge* Takedown.
Comment: Fixed (after thinking I was wrong, editing and then editing back...)

How do I do an inverted ledge takedown?


Is it possible to use tailwind css to have a hover effect follow a mouse?

Question: I am currently learning react and tailwind and have started working on a site with only those frameworks. I have a welcome page with an image hidden on screen until hovering over with the mouse. Is it possible to have that opacity fade out on only a radius of the pointer and have that radius follow the pointer?
I have looked into the documentation and have found focus and pointer states but not sure how to implement the idea. I have a basic fade in/out with opacity and hover:opacity classes currently and will keep researching but any help will be greatly appreciated!
Answer: You can definitely add a mouse event listener that will provide pointer location. Based on that information you can adjust the opacity.
<code>const [mousePos, setMousePos] = useState({});
useEffect(() => {
    const handleMouseMove = (event) => {
      setMousePos({ x: event.clientX, y: event.clientY });
    };

    window.addEventListener('mousemove', handleMouseMove);

    return () => {
      window.removeEventListener(
        'mousemove',
        handleMouseMove
      );
    };
  }, []);
</code>
Now, if you want the opacity based off of the object you are tracking (how close the pointer is to that object)
Find mouse position relative to element


Jgroups cluster breaks on restart of individual cluster members

Question: I am  experiencing  issue with  our jgroups  cluster loosing each other when a few cluster members restart.
We have 13 nodes in the cluster and all of them are in the same subnet . When restarting 4 of the nodes the entire cluster breaks down. All of the  of the members stop  recognizing  each other, and the existing members which were not restarted also do not find each other.
We start getting the SUSPECT messages and failed to collect all ACKs
0;33mWARN  [Incoming-1,broadcast,node-12] [GMS] node-12: failed to collect all ACKs (expected=11) for view [node-12|27] after 2000ms, missing 11 ACKs from node-12, node-4, node-6, node-13, node-11, node-2, node-7, node-8, node-9, node-0, node-3
0;33mWARN  [INT-2,broadcast,node-12] [FD] node-12: I was suspected by node-5; ignoring the SUSPECT message and sending back a HEARTBEAT_ACK
PFB the configuration we are using , please let me know if there any issue with the configuration . We are using 3.4.1.Final version of JGroups
<TCP loopback="true"
recv_buf_size="${tcp.recv_buf_size:20M}"
send_buf_size="${tcp.send_buf_size:640K}"
discard_incompatible_packets="true"
max_bundle_size="64K"
max_bundle_timeout="5"
enable_bundling="true"
use_send_queues="true"
sock_conn_timeout="300"
timer_type="new"
timer.min_threads="4"
timer.max_threads="10"
timer.keep_alive_time="3000"
timer.queue_max_size="500"
thread_pool.enabled="true"
thread_pool.min_threads="1"
thread_pool.max_threads="10"
thread_pool.keep_alive_time="5000"
thread_pool.queue_enabled="true"
thread_pool.queue_max_size="100000"
thread_pool.rejection_policy="discard"
oob_thread_pool.enabled="true"
oob_thread_pool.min_threads="1"
oob_thread_pool.max_threads="8"
oob_thread_pool.keep_alive_time="5000"
oob_thread_pool.queue_enabled="false"
oob_thread_pool.queue_max_size="100"
oob_thread_pool.rejection_policy="discard"
bind_addr="${jgroups.bind_addr}"
bind_port="${jgroups.bind_port}" />

<JDBC_PING connection_driver="${database.driver}"
            connection_password="${database.password}"
            connection_username="${database.user}"
            connection_url="${database.url}"
            initialize_sql="${jgroups.schema}"
    datasource_jndi_name="${datasource.jndi.name}"/>

    <MERGE2 min_interval="10000" max_interval="30000" />
    <FD_SOCK />
    <FD timeout="3000" max_tries="3" />
    <VERIFY_SUSPECT timeout="1500" />
    <BARRIER />
    <pbcast.NAKACK use_mcast_xmit="false" exponential_backoff="500" discard_delivered_msgs="true" />
    <UNICAST2 />
    <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000" max_bytes="4M" />
    <pbcast.GMS print_local_addr="true" join_timeout="3000" view_bundling="true" />
    <UFC max_credits="20M" min_threshold="0.4" />
    <MFC max_credits="20M" min_threshold="0.4" /`enter code here`>
    <FRAG2 frag_size="60K" />
    <pbcast.STATE_TRANSFER />

Answer: How do you restart your nodes? By killing them, or by a graceful shutdown (= cluster leave)?
A few comments to your config:

The regular thread pool has only 1 thread running until the queue is full (100'000 elements), so there may be quite a few messages pending in the queue. I suggest disable the queue (thread_pool.queue_enabled="false"), or increase the min number of threads and/or decrease the queue size (say 100)
Try TCPPING instead of JDBC_PING, just to see if this helps
Use MERGE3 instead of MERGE2
Use NAKACK2 instead of NAKACK. In general, I suggest use udp.xml shipped with the version of JGroups you use, and apply my recommendations above. This prevents you from using old protocols.
Use FD_ALL instead of FD
A max credits of 20M is too much for MFC/UFC and effectively defeats the purpose of flow control.

Also run probe.sh (check the JGroups manual for details) to fetch information about the various protocols, e.g. thread pool usage in the transport (TCP), suspicions in FD_ALL etc.
Hope thi helps,
Comment: Good to hear this helped. Your thread pool config is still effectively single threaded though...


Matrix spectral space vs entry space in symmetric matrices

Question: Is is known that the space of symmetric matrices $\mathbb{R}_{sym}^{n \times n}$ has $\binom{n}{2}$  dimensions.
And according to the spectral theorem every symmetric matrix $A \in \mathbb{R}_{sym}^{n \times n}$ has a spectral decomposition in terms of 1-rank matrices.
A = $\sum_{i=1}^n \lambda_i v_i v_i^T $
Hence we conclude the dimension space of the symmetric matrices is $n$.
Where is the fallacy of this reasoning ?
Thanks in advance.
Answer: You have correctly stated that for any symmetric $A$, there exist rank $1$ matrices $v_iv_i^T$ such that
$$
A = \sum \lambda _i v_i v_i^T
$$
However, it is impossible to select a fixed set $\{v_1v_1^T,\dots,v_nv_n^T\}$ such that every $A$, there exists a choice of $\lambda_i$ such that $A$ has the above form.  That is, there is no basis for the set of symmetric matrices that consists of $n$ rank-1 matrices.
Comment: Indeed this impossibility is the reason that my conclusion is incorrect. Thanks.
Answer: The linear subspace of symmetric matrices is actually of dimension $n(n+1)/2$. The linear subspace of diagoanl matrices is of dimension $n$. The similar transformation (spectral decomposition) maps $n(n+1)/2$ space to $n$ space. You have confused 2 different spaces with a single space.
Answer: The dimension space of $n$-symmetric matrices is $\frac{n(n+1)}{2}$. By the spectral theorem every symmetric matrix, with real coefficient, is diagonalizable; in other words every symmetric matrix is similar to a diagonal matrix. But this not means that the dimension of $n$-symmetric matrices in $n$.
The set of diagonal matrices is a vector subspace of symmetric matrices, and is very easy to find a symmetric matrix such that is not diagonal.


XNA remove shader effects

Question: I am new to XNA 4.0 and I'm using a shader for my background texture that creates a glow effects on white objects. When I try to add sprites to the background image it also creates the glow on my sprites, how can I remove my shader on the sprites I add on top of my background?
Answer: Use 2 seperate SpriteBatch.Begin() ... SpriteBatch.End() sections.
In the first use the Effect that wraps your shader and draw your background.
In the second draw anything you want without applying the shader.

XNA remove shader effects


php remove empty paragraphs

Question: I'm trying to remove empty paragraphs from a string.
Yes, I know it sounds pretty easy, but it just won't work. I have tried many solutions that I read here on the forum, but neither of them will work.
I should probably add that I get the strings that I want to convert from an array which is created from a json-file.
Here's my code:
if ($json_file = json_decode(file_get_contents("export.json"), true)) {
    $str = $json_file[12]["the_string"];
}
echo $str;

When I look at the source code of the page I see:

Some text, Some text

Now I want to get rid of only the empty paragraphs.
I have tried this:
echo preg_replace("/
]*>[\s| ]*<\/p>/", '', $str);

...but it doesn't work. Neither does this far more simple solution:
echo str_replace("

","",$str);

Trying both of the solutions above, the output is exactly the original string.
Any help would be highly appreciated, as I have been searching the forum for half a day now...
Thanks in advance!
Edit:
It has to do something with the format of the string that I get from the array. For testing I just copy/pasted the output into the following and here it works absolutely fine!
$str2 = "

Some text, Some text
";

echo preg_replace("/
]*>[\s| ]*<\/p>/", '', $str2);

EDIT2: This is the actual content being accessed in the json file:

\u00a0<\/p>\n
\u00a0<\/p>\n
\u00a0<\/p>\n
This is some text<\/p>

Comment: what do you think `[\s| ]` does?
Comment: Try this regexp `[\n ]*?` there is a space after \n
Comment: it should detect whitespaces or none breaking spaces, shouldn't it?
Comment: `[\n ]*?<\/p>` works as well. As I said, all the regular expressions I tried, should work! I tested them on Rubular.com. Ther must be something else, that is wrong, I don't think it's the regexp
Answer: Well, after a bit of reading about UTF-8, Unicode and lots of other stuff, I found a working solution (actually here on the forum).
echo str_replace("
\xc2\xa0
","",$str);

Nice and easy. But as \x2a\xa0 is just a nbsp; I still don't get why this didn't work:

...

php remove empty paragraphs


c - dynamic memory

Question: Hi everyone out there very first thanks to all of you for providing help.
Now i want to know about double pointer. I'm doing code like this:
int main()
{
    int **a;
    a = (int*)malloc(sizeof(*int)*5);
    for (i=0;i<5;i++)
    {
        a[i] = malloc(sizeof(int)*3);
    }
}

Now i dont know if I'm doing it right. How can I put values in this type of array ? Can anybody explain this concept with example ? Thanks in advance.
Comment: Question 6.16 of the C-FAQ (*How can I dynamically allocate a multidimensional array?*) might be helpful: http://c-faq.com/aryptr/dynmuldimary.html
Comment: The cast is wrong...Should be (int**). It's not even necessary in C.
Comment: Any answer to your liking?    If so, you should accept it.
Answer: Well, you have allocated an array equivalent in size to:
int a[5][3];

So to enter values you just do like this:
a[0][0] = 1234;

Which would put a value into the first column of the first row and
a[4][2] = 9999;

would put another value into the last column of the last row.
Since you are using malloc, you should also loop through a[i] from i = 0 to 4, and free(a[i]); and then free(a); or your program will leak memory.
Answer: All right... what you have here, basically, is a pointer-pointer, namely, the adress of an adress. You can use this kind of variable when dealing with arrays.
The first two lines of your code are equivalent to :
int* a[5]; // Declaration of an array of 5 integer pointers (a[0] till a[4]).

A "pure" C code doesn't use variable for the size of an array, so you use the malloc when you want to edit dynamically the size of the array.
Meaning, if in your code, you are not going to change the size of your arrays, you are using a very complex way to achieve a very simple goal. You could just type :
int a[5][3];

But if you do not know the size of your array, you have to use the mallocs (and then, free). What you are doing, basically, is :

Declaring an array of array;
Allocating the memory for x number of POINTER to integer arrays;
For each of these POINTERS, allocating memory for y integers.

Now that you have done this, you can use your arrays normally. For instance :
a[1][0] = 1;

will mean : in the first array [1], the first row [0] is 1.
The only difference with a standard declaration like the one above, without the mallocs, is that since you allocated memory, you'll have to free it. Which is why you don't want to lose your variable a**. At the end of your function, the pointer-to-pointer variable will be destroyed, but not the memory you allocated.

c - dynamic memory


max() and min() returns np.nan when the np array starts with np.nan

Question: The max() and min() functions are both returning np.nan if I have an array that starts with np.nan
Here is where it works as expected:
>>> column_data = np.array([111, np.nan, 112, np.nan, 115, np.nan, 116, np.nan, 117, np.nan, 118, np.nan, 119])
>>> print(max(column_data))
119.0
>>> print(min(column_data))
111.0

Now I add an np.nan at the beginning of the array, and it screwed up
>>> column_data = np.array([np.nan, 111, np.nan, 112, np.nan, 115, np.nan, 116, np.nan, 117, np.nan, 118, np.nan, 119])
>>> print(max(column_data))
nan
>>> print(min(column_data))
nan

I've tried filtering out the nan elements, but still the same:
>>> print(max(i for i in column_data if i is not np.nan))
nan
>>> print(min(i for i in column_data if i is not np.nan))
nan

What happened here and how do I fix this?
Comment: what did you expect it to do?
Comment: for max() to give me 119 and min() to give me 111, like my first example where it was working fine
Answer: Solution and a bit of explanation:
@user2357112supportsMonica proves a point, "The filter is failing because the objects retrieved from the array to represent the NaN value are different objects from np.nan":
print(np.nanmin(column_data))
print(np.nanmax(column_data))

Output:
111.0
119.0

See inequality comparison of numpy array with nan to a scalar for more info.
Documentation:
As mentioned in the documentation's notes:

NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmax.
Comment: @Dan this is due to the way comparisons to `nan` values are handled. See: https://stackoverflow.com/questions/25345843/inequality-comparison-of-numpy-array-with-nan-to-a-scalar
Comment: The fact that `np.nan != np.nan` has nothing to do with this. Even if things were changed so that `np.nan == np.nan`, the results would be the same. The filter is failing because the objects retrieved from the array to represent the NaN value are different objects from `np.nan`.
Comment: Thank you, this works! Also would you know why it fails to work when the array starts with np.nan but still works well when it does not?
Comment: @Dan Added documentation link
Answer: This is because i is not np.nan is never evaluating to False and thus nothing is every getting filtered out. The correct way to test for nan is using np.isnan(...). This should work correctly:
max(i for i in column_data if not np.isnan(i))

Also, you can use numpy methods for performing filtering, max and min as follows:
column_data[~np.isnan(column_data)].max()

However, if you only wish to calculate max and min for non-nan values and not do anything else with the non-nan values, @U10-Forward's answer is the better approach.


I've added a function to a Scala list, now how do I remove it?

Question: Given the following Scala code:
val buffer = new scala.collection.mutable.ArrayBuffer[Function0[Boolean]]
def foo(): Boolean = { println("foo"); false }
def bar(): Boolean = { println("bar"); true }

buffer += foo
buffer += bar

I've added two functions to my buffer. Now, how do I remove one?
buffer -= foo doesn't work because foo is evaluated to a boolean before any comparisons.
Comment: I hear there's a [`remove`](http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.ArrayBuffer) method
Answer: You misunderstand the reason why your current code is not working. Removing objects in this way relies on the == operator, which for functions is defined using the object identity only. This means that you must ensure that you have a stable value for the function that you are adding if you want to remove it again. You are currently using anonymous function literals ('boxed' from the method references), which cannot be recreated.
In other words, buffer += foo is equivalent to buffer += (foo _), and foo _ will give you a different function object each time. Try this:
buffer += foo
buffer += foo
buffer.map(System.identityHashCode(_))
res4: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(944601779, 1722981029)

Oops, two different objects, we were expecting to have two references to the same one.
Now try
val fooRef:Function0[Boolean] = foo // or val fooRef = foo _
buffer += fooRef
buffer += fooRef
buffer.map(System.identityHashCode(_))
res8: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1732011089, 1732011089)

Ah, that's better! buffer -= fooRef will now work as expected.
Comment: `Function0[Boolean]` looks strange, you could use `() => Boolean` here as type name. `val fooRef: () => Boolean = foo`.
Comment: Sure, I was just going with the same notation used in the question.
Comment: Thanks @rxg, I actually figured it out about an hour after I posted the question. It all made sense once I realized the compiler is creating anonymous classes under the hood.
Answer: You can define foo and bar as function literals:
scala>  val buffer = collection.mutable.ArrayBuffer.empty[Function0[Boolean]]
buffer: scala.collection.mutable.ArrayBuffer[() => Boolean] = ArrayBuffer()

scala>  val foo = () => { println("foo"); false }
foo: () => Boolean = <function0>

scala>  val bar = () => { println("bar"); true }
bar: () => Boolean = <function0>

scala>  buffer += foo
res0: buffer.type = ArrayBuffer(<function0>)

scala>  buffer += bar
res1: buffer.type = ArrayBuffer(<function0>, <function0>)

scala>  buffer -= foo
res2: buffer.type = ArrayBuffer(<function0>)


Is a 240vac (2 pole) outlet a "single phase receptacle"?

Question: I just read about NEC 2017, section 625.54:
"Ground-fault circuit-interrupter protection for personnel.
All single-phase receptacle installed for the connection of electric vehicle charging that are rated 150 volts to ground or less shall have ground-fault circuit-interrupter protection for personnel."
This seem redundant since all EVSE (Electric vehicle supply equipment) have GFCI built into the unit. I was wondering if this refers to the 120v (hot-neutral) type outlet only. I got a regular 40A breaker (2 pole) for my outlet but, if I read this right, I need to upgrade to a 40A GFCI breaker? $100, ouch!
Are 120v (hot-neutral) and 240v (hot-hot) single phase receptacle?
Thanks
Answer: If you hard-wire the EVSE unit, then you're covered because the unit has GFCI built in and you never have an open unprotected receptacle.
Presumably you are talking about a residential application in the U.S., since you seem to be doing it yourself and you are referencing the 2017 N.E.C.
This applies whether your 240V supply is single-phase or 3-phase (in which case it will probably be 208V).
As a curiosity, it might be worth mentioning that if you're dealing with a 3 phase service typical of commercial installations (say you're doing this at a rented commercial office or store space rather than at home), then your service is probably 3-phase with neutral, in which case your outlets will either be 120V, or 208V (there is 120V of potential from any of the phases to the neutral, and 208V from any of the phases to another phase).

In a residential situation, you are served by a single phase (from the 3 phase distribution lines), which is stepped down to 240V in the transformer outside your house. This is split, in the transformer, by a center tap neutral into a pair of 120V legs. This means you get 120V from either pole to the neutral, and 240V from pole to pole. But either way it is still only 1 phase.
Sidebar...
The poles of your residential transformer are 180 degrees out of phase with each other, because the AC sine waves are shifted 180 degrees apart. I believe this is one of the sources of occasional confusion, and this plus the fact that both circuits derive from one phase is one of the reasons that some people refer to the 120V legs as "phase legs", and is also why some people sometimes seem to perceive "phase leg" slightly differently than other people. The bottom line is that this entire setup is a branch circuit off of just one phase of the nearest 3 phase transformer that ties you into the long haul power transmission lines that serve you. Thus, the entire 240V circuit that feeds your house, and both 120V legs of that circuit, are all one phase. And yet the two 120V legs actually are out-of-phase from each other.

Summary
But again; if you are connecting the EVSE (Electric Vehicle Supply Equipment) unit to an approved power source, and you hardwire it in, then you are covered by the GFCI built-in to the unit because you don't have an exposed, unprotected receptacle.
If you run power to a receptacle that you then plug the EVSE into, then you're probably required to use a GFCI breaker because you have created a situation where there may be an open receptacle in an area that requires GFCI protection.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/83529/discussion-between-craig-and-kris).
Answer: In the North American residential universe, all 240V service is not single-phase, it is split-phase.  i would say that is not the same as single-phase.
Regardless, it clearly only applies to receptacles.   Hardwire the unit. Badabing!
Comment: Split *phase.*  Not split *phases.* :)
Answer: Short answer, yes, with only two poles, you can only have one phase.  The 240VAC originates from a single transformer winding source.
Answer: There is a subtle issue at play here, the term "for personnel." Equipment may say that it has "Ground Fault protection", but here in the US, the term "for personnel" requires a SPECIFIC type, referred to as "Class A Ground Fault Protection", also referred to as being a "Ground Fault Circuit Interrupter" (GFCI). Those are SPECIFICALLY DEFINED terms for a device that trips at 5mA of current (no less than 4mA, no more than 6mA). The term "Ground Fault Protection" is more generic. It MIGHT be inclusive of a GFCI, but it could also be what's officially called GFP or GFPE for "Ground Fault Protection (of Equipment) and could trip at 30mA, 100mA or even upward of 25% of the circuit rating! Anything more than 6mA does NOT qualify in this country. 30mA however DOES qualify in other parts of the world, so you must be careful because some overseas suppliers allow you to BELIEVE that it's fine, and you find out it was not when an inspector red-tags your installation.
So if your charger SPECIFICALLY uses the term "GFCI", or "Class A Ground Fault" not just "Ground Fault", then you are good to go, no need to put it ahead of the charger too.
Answer: In both 1 AND 3 phase systems all single pole and double pole breakers are referred to as single phase. The only time it would not be 1 phase is when supplied by a 3 pole breaker.  Also, some folks will confuse the matter even more by calling it  2 phase because a double pole breaker is using 2 of the 3 phases of  a 3 phase system, but it's not proper nomenclature. In actuality, 2 phase is all together a system of its own, distinct from 1 and 3 phase.
In the current 2017 NEC the wording for 625.54 is suffering as it has not taken into account the subtle ambiguity of electrical nomenclature and this is why a revision for the 2020 NEC was adopted and reads currently as  "All receptacles installed for the connection of electric vehicles..."   The wordings for 150V to ground and single phase where removed.
Now, the code section also specifies receptacles.  Thus, a direct wire charger would not apply to the GFCI protection.
Some theory:  A phase is regarded as one complete cycle through the coil.  The coil is the windings of copper around the iron core of the primary and the secondary side of the transformer. For the common U.S. residential "split" single phase, from the start to the end of the secondary coil will be 240 volts. Remember voltage is oscillating back and forth and this can be mathematically represented as a waveform. Thus, a wave has a positive peak and a negative valley.  We center tap the wave ( the calmest part of the wave where the voltage is 0 ) and call this the neutral/grounded conductor.  Now since the wave is a function of time, we use the root mean square to find the average of the peak to peak voltage which is nominal 120 volts.
On a 3 phase WYE system, we still use 1 phase but now we have 3 and they all share one neutral.  The math works out a little differently, ( i.e. 120° between each of the 3 phases instead of 180° split phase difference ) which gives 208V phase to phase and 120V to ground, but pretty much the same principle.