Light is working but switch is not

Question: Total noob here. Replaced a ceiling fan with an LED light. Connected the green to green, white to white and the black to black. The light is turning on but the switch is not working.
Not sure what to do. There is another black and another red wire.
Please help.
Thanks.
Comment: Can you post photos of both the light and the switch boxes?
Comment: `The light is turning on but the switch is not working.` ...... how is the light being turned on?  ...... which switch are you talking about?
Comment: What was the fan connected to before?
Comment: Added the picture. @jim - yes that's what it is. The light is on no matter what position the switch is in.
Comment: Before, there were 2 or more black wires on a wirenut *that the fan wasn't connected to at all*.   Before, was there also a white wire in that bundle?
Comment: Can you post a photo of the switch?
Comment: Can you post a photo that looks into the back of the switch box?
Comment: Is it the case that you did NOT change the wiring at the switch? Or did you change the wiring at the switch when the switch didn't work? If you didn't change the wiring at the switch, then assume that the switch is wired correctly and all you have to do is correctly wire the ceiling box.
Answer: This looks like a very common type of circuit, called a switch loop.
One question: do the unused black and red wires at the light come out of the same cable? If so, the other end of the cable is most probably attached to the switch.
Strictly speaking, you should test this by checking for continuity between the unused black and the unused red, with the switch off and then with the switch on. However checking continuity is something that a total noob may not know how to do, or have the equipment for.
Now, I usually test continuity using line voltage and an ordinary drop light. You can do the equivalent of that here by simply wiring the switch loop into the light circuit and trying it.

Turn off the circuit breaker controlling the light.
At the light fixture, disconnect the black light fixture wire from
the black wire bundle.
At the light fixture, connect the unused black wire to the black wire
bundle.
At the light fixture, using a new wire nut, connect the black light
fixture wire to the unused red wire.
Turn on the circuit breaker.
Turn the switch on and off.

If this doesn't work, that is, if the switch still doesn't control the light, or if the circuit breaker trips, then you have some unusual wiring, and you will have to spend some time analyzing it. If it does work, you're done, and you can put the cover plates back on.
Comment: Thanks Breveleri! That worked. Your help is much appreciated.

Light is working but switch is not


Adding careers section to linguistics

Question: I would really like to see the careers section in Linguistics SE. I know that linguistics is still in Beta and we don't have much users but the site is grwoing so fast and it would be great to have this feature.
Comment: are there career sections on any SE sites, apart from the SO site? I don't know if such a thing is possible.
Comment: I don't think we have enough professional linguists for this to be practical. Are we really growing fast? To me, the site seems to be going along at a consistent but slow pace.
Comment: I just can't see it being a priority for Stack Exchange at any point in the foreseeable future. Which means, it won't just take some time, it will never happen because nobody will be working on it. They are interested in extending Careers to some other sites eventually (as described in the answer to this question: [Extend Careers to other sites (like Ask Ubuntu), not just Stack Overflow](http://meta.stackexchange.com/questions/251063)) but I think they're focusing on tech sector jobs. Still, it can't hurt for you to make this post to gauge how much interest people here have in the idea.
Comment: Well there aren't because most of them are specific sites (I say most because I haven't checked all of them). Server fault, android, etc. aren't career subjects but linguistics is. Also What do you mean by impossible? The admins are not willing to add this feature? Or the premise of having careers section for linguistics is impossible?
Comment: The admins have to roll out this feature. Are you aware of any SE site that has it?
Comment: @prash no other SE site has it.
Comment: @sumelic I agree. But starting and launching the project can take some time and we will reach that point at the time launching it. Right?
Answer: Questions on any SE site should not just be personal opinions, they should be objective truths about the subject matter, where there is a definite right answer. I have a hard time seeing how a career question could meet that desideratum. E.g. any answer to a question like "should I double major in Linguistics and Computer Science to be sure of getting a job" is just going to be made up and will not take into consideration the questioner's abilities, and will not be generalizable to the next person who has the same question. Even actual fact questions like "How many academic jobs where there in 2015 in the area of phonology" will only generate off-topic personal opinions.
Comment: I was not asking about adding career as a question base for linguistics. Careers section is a part of Stackoverflow where people can add their resumes and jobs matching their skills appear. A similar thing for linguistics SE would be like when you are visiting phonetics tags you will see job postings about phonetics.

Adding careers section to linguistics


Checking file handle type in PHP

Question: I'm using fopen to open a feed (.txt file) from a URL but sometimes the feed isn't found. I would like fopen to return FALSE when this happens, so I can handle the error. However, when the feed isn't found on the target URL, I'm being redirected to another page on the site, informing me that the specified file wasn't found. The result being, my $handle refers to the wrong file, and fopen returns TRUE (because it has found -something- albeit the wrong thing), thus sabotaging my attempt at error handling.
How can I verify that fopen has got the right file? Thanks.
<code>if ($handle = fopen($feed, "r")) {
   //fopen returned true, do stuff
} else {
   //fopen returned false, quit
   die("Fail.");
}
</code>
Comment: try using [Curl](http://php.net/curl) instead
Comment: -1 use [search](http://stackoverflow.com/search?q=fopen+file_get)
Comment: It would be better to detect this from your (HTTP?) request, rather than trying to detect an issue way after its occurred.
Comment: I'm not quite sure, but a feed should be some kind of xml, right? So you could check if `isset()` the root-node after passing the string to an xml-reader.
Answer: You can get the http wrapper to ignore redirects as follows:
<code>$opts = array(
    'http' => array('method' => 'GET',
                    'max_redirects' => '0')
);

$context = stream_context_create($opts);
$handle = fopen($feed, 'r', false, $context);
</code>

Checking file handle type in PHP


Tankless water heater - not consistent hot water output

Question: I have a tankless with a descaler on the cold water input.
When I turn on the hot water at the faucet it takes a minute or so to get hot water. Then I'll hear some banging/knocking of the pipes.
However, if I leave the hot water running, it turns to cold water.
What could be happening?
update
It is a Noritz NR981-OD-NG. Natural gas model. We just installed the unit a few weeks ago. I just started to use it this past week.
This is our only hot water heater and is rated for 2 to 3 showers.
The hot water is on full and the cold water is off.
update 12/29/16
Could the flow of water be causing the hot water heater to not activating to heat the water? I can hear the hot water heater 'working' even when cold water is coming out of hot water faucet.  From the specs of the water heater: "Minimum Activation Flow Rate   0.5"  How can I tell/measure what the flow rate is ???
update 1/3/2017
Resolved!
The plumber and I changed out the water limiting spout cover and that did the trick. Our local gas company gave us a water savings kit and we used the water limiting spout (rated for 1.5 gpm) and that seemed to fix the problem.
Comment: What is the make and model of heater? Central or point of use? Electric or gas?  How long has it been in service? Is the hot water flow on full when the water temperature turns cold?
Comment: Hi @JimStewart : I just updated with info you asked...any guesses at what could be causing this?
Comment: Is the digital temperature display reading a value that would correspond to getting hot water, but you are not getting it?
Comment: You could check the flow rate by collecting the output of the shower or a tap in a bucket for a timed period. A flow rate of 0.5 gal/min is very low and it is highly unlikely that you are below that. Who installed the water heater and was it new from the box?
Answer: We have a basic Bosch tankless, NG 117 kBTU/h, with a standing pilot light, no a/c power required, all mechanical controls, discontinued model I think, been in service 12 years. It worked fine until I changed to low flow shower heads (1.4 gpm). I took out the flow restrictors in the shower heads and the water heater worked again. So that is my experience.
Your Noritz NR981-OD-NG is larger and with more features so there are more things that can go wrong. If you remove your shower head and get full flow of hot water, does the water get hot? Or if you turn on all the hot taps in the house, do you get hot or even warm water?
Is the variable burner at fault? Is it stuck on 16 kBTU/h? Is the gas pressure and flow adequate for the heater? Can you tell from the gas meter if the heater is pulling the amount of gas required for maximum 200 kBTU/h heating?
Comment: How do I measure pressure and flow? Would it require disconnecting the gas connection to the heater? Before the install the contractors hooked up a meter to the extended gas line.
Comment: What does your installation guide say about the gas supply requirements? The static pressure can be sufficient, but if the gas line from your meter to your heater is too small in diameter for its length, then the pressure would drop when the burner turns on. The installer should have verified that the gas line was sufficient. Tankless heaters have a high demand for gas.
Comment: Our gas supplier in Dallas sets the meters to give a pressure of 7" of water column (0.25 psi). The specs on my Bosch for NG supply are (before the Aquastar regulator) min 7" WC , max 14" WC. Required at inlet tap with heater operating 5.7" WC and when operating at maximum 4.2" WC. What your the altitude above sea level?
Comment: Looking through my notes it seems that our gas company can supply 7" WC (=0.25 psi), 2 psi or 5 psi from the meter. I am sure we have 7".  The higher pressure supplies are I think for houses with extra regulators maybe one at the service entry to the structure or at the individual appliances. I don't know if it actually occurs in practice, but there is an opportunity for a mismatch.  Do you know what your heater is set up for and what you gas supplier is providing?
Comment: A spec sheet for your Noritz gives gas pressure requirements as 4" WC  to 10.5" WC.


Regular Expression in Javascript for number with decimal

Question: I want a regular expression for a textbox which allows only 3 digits and passes following criterias:

Only digits (234 or 123) or
Only one decimal at the end (55.1)
Should not allow spaces
If decimal is used then there should be a number after/before decimal as well (555. or 12. or .12 should not be allowed)

I have following RE which works partially:
/^\d{0,3}$|^\d{0,2}[\.]\d{1}$/

Any help in modifying this ?
Looks like problem is additional:
I am using the code at keypress. So it validates each pressed value at key press.
  if (window.event)    {
        knum = e.keyCode;
    }
    else if (e.which)    {
        knum = e.which;
    }
    kchar = String.fromCharCode(knum);
    numcheck = /^\d{0,3}$|^\d{0,2}[\.]\d{1}$/;

    alert(numcheck.test(kchar));

It returns false for any decimal key press. Even if I enter 55 and then try a decimal in middle to make it 5.5, ite returns false.
Comment: Just change you {0,2} to {1,2}, but everything else seems fine to me.
What doesn't work ?
Comment: just for clarity: you're checking a string that is, by definition 1 char in length: `String.fromCharCode(knum)`, why are you matching against a pattern that allows for up to 4 characters?
Comment: So that they donot enter unwanted characters into checkbox. So when I had only numbers ( /\d/ ), the code was working fine. I changed it to include decimals and realised that it is not gonna work. That is modified my question and provided code.
Comment: You need to match the kchar against /[0-9.]/ then.  You have to check overall validity after they're done typing with one of the regexes below.  Otherwise, they'll type something like 55. and you'll stop them before they can hit the last digit.
Answer: You need at least 1 digit, but 3 at most: \d{1,3}
OR
There have to be at least 1 but no more than 2 digits before and 1 after the decimal: \d{1,2}[.]\d
So these combined: /(^\d{1,3}$|^\d{1,2}[.]\d$)/
UPDATE:
You are testing the character which was added on the keypress event, not the full value of the input field. This would never have the expected result.
document.getElementById("yourfield").onkeyup = function(e) {

    // the event
    if (!e) e = window.event;

    // determine the target of the keyup event (the input field)
    var targ;
    if (e.target)
       targ = e.target;
    else if (e.srcElement)
       targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
       targ = targ.parentNode;

    // get the value
    kchar = targ.value;
    numcheck = /^\d{0,3}$|^\d{0,2}[\.]\d{1}$/;

    // test
    alert(numcheck.test(kchar));
}

Comment: Somehow, with above code, I am not able to type anything atall after decimal.
Answer: Try /^\d{1,3}|(\d{1,2}\.\d)$/?
Your character class should not escape the period, so it should be [.], though I prefer to write just \. because it's a waste to create a class for one character.  Similarly, \d{1} is redundant when \d means exactly the same thing.   I'm also assuming that you don't want to allow an empty text box, either, so I wrote something that allows 1-3 digits, or 1-2 digits, a period, then one more digit.  If that's wrong, you can change the range on that first \d back to {0,3}, which will allow for a text box containing nothing at all.
Comment: Can I probably compare it in the code at   kchar = String.fromCharCode(knum);  step ??
Comment: I mean instead of taking single character and comparing, if i take already existing text in input box and concatenate with the string entered giving me complete text ? Any similar thing if possible ?
Comment: Compare the individual chars against `/[0-9.]/` if you like, then append them, but then do one last check at the end before submitting or processing the value to see if the overall format is correct using the full regex.  And always remember that they could turn JavaScript off and just put anything in there.
Answer: Use this re:
/^\d{1,3}$|^\d{1,2}[.]\d$/

Comment: That violates their condition #2:  "Only one decimal at the end (55.1)"


How do I make a variable function in a class in python 2.7?

Question: So, I have a class like this:
class Test(object):
    def call(self,instruction,data):
        pass

    def handle_foo(self,data):
        print "Foo: %s" % data

    def handle_bar(self,data):
        print "%s: bar" % data

And code calling it like:
t = Test()
t.call("foo","abc")
t.call("bar","def")

How do I make the call definition call the functions by inserting the variable "instruction" in the function name?
I tried this, but it didn't work
def call(self,instruction,data):
    func = "self.handle_%s" % instruction
    func(data)

Comment: You could just pass the actual function as a parameter, too. Functions are objects.
Answer: That would be using the getattr method
func = getattr(self, 'handle_%s' % instruction)
func(data)

Answer: You can use getattr to get a member of an object with the member's name as a string.
getattr(self, 'handle_' + instruction)(data)

Comment: Works great, thanks! I'll accept once the anti-bot timer is done ticking down.


Incomplete and random numbers of Friends list using asmack

Question: I am getting random numbers of friends from the asmack roster in android.
i am using
<code>        roster = connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();
        return roster.getEntries();
</code>
please help...
Answer: I am using the same method to retrive roster entries and I am getting perfectly. Kindly check with your code once. Comment here if you need any help.
<code>ArrayList<RosterEntry> rosterEntriesc;
    try{
                connection = MyXMPPConnection.getXMPPConnection();
                roster = connection.getRoster();
                rosterEntriesc = new ArrayList<RosterEntry>(roster.getEntries());
       }
catch(Exception e)
{
e.printStackTrace();
}
</code>
Comment: Ya thats what i am saying it is true that this is the method but i am still getting random numbers of roster entries
Comment: what you mean by random numbers of roster entries?
Comment: Some times i get 1 or 2 friends sometimes all and some time none


algebra, equivalence relation regarding associates

Question: If f(x) ~ g(x) if and only if f and g are associates,
prove this is an equivalence relation
have tried to prove this both ways, struggling
Comment: what do you mean associates? should we assume these are elements of a polynomial ring and this means that there is a unit such that ..?
Comment: associates meaning: if f(x),g(x) exist in some F[x], and f(x)=u*g(x). f(x) is an associate of g(x) and u^(-1)*f(x)=g(x). then f(x) and g(x) are associates
Comment: @ElizaK Please [edit] your question to include this important information. We can't read your mind after all :). Thanks in advance.
Comment: So sorry, still new at this. This is all information the professor provided, what other information should i provide?
Answer: Well you need to show 3 things :

Reflexivity : Take $u=1$
Symmetry : If $u$ works in one direction, then $u^{-1}$ works in the other.
Transitivity : If $f(x) = ug(x)$ and $g(x) = vh(x)$, then $f(x) = (uv)h(x)$, and $uv$ is a unit if $u$ and $v$ are.
Comment: makes sense, thank you!


Algorithm to get the maximum size of n squares that fit into a rectangle with a given width and height

Question: I am looking for an algorithm that can return the number of size of n squares that fit into a a rectangle of a given width and height, maximizing the use of space (thus, leaving the least amount of leftover space for squares that do not fit). Neither the rectangle nor the squares can be rotated.
For example, let's say I have a rectangle that is 5 inches by 7 inches, and I need it to fit 35 squares. The algorithm needs to tell me that the 35 squares fit if they are 1 inch wide/tall (as they could be laid out inside the rectangle in a 5 x 7 grid). Another example is if I need to divide a rectangle 35 inches by 1 inch into 35 squares. It should still tell me that the squares will fit if they are 1-inch wide/tall (as they could be laid out in the rectangle in a 35 x 1 grid).
The tricky part is that sometimes there may be leftover space, as the squares cannot be divided into partial squares. Let's say for either of the two examples above I need to lay out 34 squares and not 35 (in which case the answers would still be 1 inch), or maybe 33, or 7 squares. Or, perhaps the rectangle width and height aren't whole numbers. With the number of squares being a variable I need an algorithm that can tell me the size of the squares for a given rectangle width and height.
Thanks for your help!
Comment: See [squares in squares](http://www2.stetson.edu/~efriedma/squinsqu/) and [squares in dominoes](http://www2.stetson.edu/~efriedma/squindom/) from [Erich's Packing Center](http://www2.stetson.edu/~efriedma/packing.html) for some specific cases. Finding these automatically seems like a pretty hard problem.
Comment: Also, as you note in your tags, I see a formula kind of unlikely: this problems are usually solved by algorithms. The trigonometry tag is not relevant, I think.
Comment: @MvG thanks for the links. I just realized that I need to clarify that squares cannot be rotated.
Comment: Starting point: If you take all the squares and  move them to a corner, the leftover space is much easier to calculate.(I am assuming all the squares are of equal size)
Comment: Code on Stack Overflow: [Resizing n of squares to be as big as possible while still fitting into box of X by Y dimensions](http://stackoverflow.com/q/1575589)
Comment: One Should Try To Solve It-> https://math.stackexchange.com/questions/1466926/getting-a-algorithm-for-height-and-pillars-problem
Comment: You can get a specific size for n squares, so they fit perfectly inside a rectangle just using gcd(h,w) as describes in my question https://math.stackexchange.com/questions/3368571/solved-fit-grid-into-a-rectangle-perfectly?noredirect=1#comment7694066_3368571
Answer: Let's analyze a single case:
If we want to cover a $6x5$ rectangle with $7$ squares, we first note that each square at most has an area of $30/7$. We also know that for our filling to be optimal, we need to fill at least an axis.
So now we know that we will fill either the $6$ or the $5$ completely. We will first try with the 5. Since the maximal side of our squares is $\sqrt{30/7}$, we now need the smallest integer more than $5/\sqrt{30/7}$, that is equal to $\lceil5/\sqrt{30/7}\rceil=3$
So we would divide the $5$ in $3$ parts $p_x$, so each side will have $5/3$ . If so, I would cover $(5/3)^2*7=19\frac49$ of the thirty squares. If they don't fit vertically, we try with more parts $p_x$, until the squares fit in the other axis. $$\lfloor6/(5/p_x)\rfloor*\lfloor5/(5/p_x)\rfloor=\lfloor6/(5/p_x)\rfloor*p_x\ge7 \,\,\,\,\,\,\,\,\,\, (5/p_x=\text{the actual size of our squares)}$$
Also, since $p_x$ is integer $\lfloor p_x \rfloor =p_x$
If we do the same with the $6$, we get $\lceil6/\sqrt{30/7}\rceil$ again covering $19\frac49$ of the surface. We then do the same as with the $5$ and save it as $p_y$
Let's now recall the formulas we had.
We had an $x∗y$ rectangle and filled it with $N$ squares. We started with $p_x=⌈x/\sqrt{xy/N}⌉$=$⌈\sqrt{Nx/y}⌉$ or $p_y=⌈y/\sqrt{xy/N}⌉=⌈\sqrt{Ny/x}⌉$ and then we made them fit by shrinking them until they fit in the other axis. But we know we want the area maximised, so $Side=max(x/p_x,y/p_y)$.
A better method:
Once we have the start value $p_x=⌈x/\sqrt{xy/N}⌉=⌈\sqrt{Nx/y}⌉$,if it does not fit in the $y$ axis, we need to make it fit in the $y$ axis. For that, we use that
$$a=x/p_x$$
where $a$ is the value of the actual side of our squares.
Then we know that for our side to fit we need to reduce it:
$$S_x=y/(\lceil y/a \rceil)$$
We do the same with $S_y$ and calculate $max(S_x,S_y)$
The advantage of this is that it needs a constant number of operations, the most expensive one being the square root.
Plain, unoptimized C Code
Some multiplications may be reused but for code readability and practical uses this is enough.
Input: values of $x$,$y$, and $n$. Handcoded.
Output: The optimal side of our squares
<code>#include <math.h>
#include <stdio.h>
#define MAX(x,y)    (x)>(y)?(x):(y)
int main(){
    double x=5, y=6, n=7;//values here
    double px=ceil(sqrt(n*x/y));
    double sx,sy;
    if(floor(px*y/x)*px<n)  //does not fit, y/(x/px)=px*y/x
            sx=y/ceil(px*y/x);
    else
            sx= x/px;
    double py=ceil(sqrt(n*y/x));
    if(floor(py*x/y)*py<n)  //does not fit
            sy=x/ceil(x*py/y);
    else
            sy=y/py;
    printf("%f",MAX(sx,sy));
    return 0;
}
</code>
Comment: @Anton The notation $O(n)$ is the notation of asymptotic complexity. One of it's basic properties is that you just care about the  highest order term and you drop all the constants, for example $O(5x^2+x+1)$=$O(x^2)$. It is a useful way of noting the **time complexity** of your algorithm. In this case, the slowest operation is the square root. Since there are varying implementations, I wrote $O(\text{the time your sqrt function takes})$ because I don't know your code implementation. Assuming you will code this, this makes sense. If you are doing this by hand, this is unimportant :).
Comment: @Anton here is some code http://ideone.com/fwcmoc, outputs the side of the square.
Comment: @chubakueno can you please check the generic formulas after "We started with", there seems to be some inconsistencies with $p_x$ and $p_y$ in the text. Also can you please explain how you went from $x/\sqrt{a}$ to just $\sqrt{b}$?
Comment: Thank you for the detailed answer. I'm going to give it a go tonight/tomorrow morning. Right now I'm having a little trouble wrapping my head around what to do after calculating P(x), when it comes to reducing.
Comment: @Anton I posted now a method to reduce it without any iterations, so it is $O(\text{the time your sqrt function takes})$
Comment: Sorry, I don't understand what you mean. What is O and what time are you referring to for the sqrt function?
Comment: http://en.wikipedia.org/wiki/Big_O_notation
Comment: @TWiStErRob $$\frac{x}{\sqrt{\frac{xy}{n}}}=x\sqrt{\frac{n}{xy}}=\sqrt{\frac{nx}y}$$ Can you please point me to the individual inconsistensies? I have checked again but I don't see anything, but it is possible that I am wrong...
Comment: @TWiStErRob Got it! It was just a typo, thankfully, so it doesn't affect the result. The $y/$ should have gone inside the ceil function, it is corrected now.
Answer: chubakueno's solution doesn't always work. Take for example $x=10$, $y=2$ and $n=8$. His algorithm returns 1 whereas the biggest square size is obtained by fitting one single line of eight squares, and is therefore $10/8=1.25$.
Below is an algorithm that works, written in Javascript. It also has the advantage of computing the minimum number of rows and columns, on top of the square size. Inputs are x, y and n.
<code>// Compute number of rows and columns, and cell size
var ratio = x / y;
var ncols_float = Math.sqrt(n * ratio);
var nrows_float = n / ncols_float;

// Find best option filling the whole height
var nrows1 = Math.ceil(nrows_float);
var ncols1 = Math.ceil(n / nrows1);
while (nrows1 * ratio < ncols1) {
    nrows1++;
    ncols1 = Math.ceil(n / nrows1);
}
var cell_size1 = y / nrows1;

// Find best option filling the whole width
var ncols2 = Math.ceil(ncols_float);
var nrows2 = Math.ceil(n / ncols2);
while (ncols2 < nrows2 * ratio) {
    ncols2++;
    nrows2 = Math.ceil(n / ncols2);
}
var cell_size2 = x / ncols2;

// Find the best values
var nrows, ncols, cell_size;
if (cell_size1 < cell_size2) {
    nrows = nrows2;
    ncols = ncols2;
    cell_size = cell_size2;
} else {
    nrows = nrows1;
    ncols = ncols1;
    cell_size = cell_size1;
}
</code>
Comment: @inyourcorner Sorry for the delay. You could divide `ratio` by your rectangle's aspect ratio `rect_ratio` in the beginning, apply the algorithm, and then your cell size will be `x = rect_ratio * cell_size, y = cell_size`, if I'm not mistaken.
Comment: how could I apply your solution to a similar problem but for a collection of rectangles with fixed aspect ratios of w/h = 3/2 and w/h = 2/3? If you'd like I can create a new question for it. Thanks!
Comment: This makes sense - thanks for confirming, and for the help
Comment: perfect - just what I needed
Answer: Credit for the algorithm is entirely from chubakueno's answer. I'm just posting a C# version of it here in case anyone else needs it.
<code>/// Calculates the optimal side of squares to be fit into a rectangle
/// Inputs: x, y: width and height of the available area.
///         n: number of squares to fit
/// Returns: the optimal side of the fitted squares
double FitSquares(double x, double y, int n)
{
    double sx, sy;

    var px = Math.Ceiling(System.Math.Sqrt(n * x / y));
    if (Math.Floor(px * y / x) * px < n) {
        sx = y / Math.Ceiling(px * y / x);
    } else {
        sx = x / px;
    }

    var py = Math.Ceiling(System.Math.Sqrt(n * y / x));
    if (Math.Floor(py * x / y) * py < n) {
        sy = x / Math.Ceiling(x * py / y);
    } else {
        sy = y / py;
    }

    return Math.Max(sx, sy);
}
</code>
Comment: this does not take into consideration the w & h of the smaller squares?
Comment: No, it assumes we always want to fit squares of fixed sizes.


DC current for reconstructed house with new extension

Question: I am hoping this could be the right forum for this kind of question. I recently bought a house that is going to have major structural changes and an extension that will basically be new-build. I am pretty much a novice to all this.
I am thinking about the electrics, naively, and wondering what kind of cost savings and simplifications could be achieved by trying to run DC around the house.
My thinking is that

I want efficient (LED?) lighting (DC)
If necessary, perhaps I could pipe the light by cheap fiber optic, if that ends up being part of the solution
Most things I use around the house either run off DC or will be rechargeable via USB anyway.
I will still need a few AC sockets for things like the hoover, but not many

I am aware that low voltage DC will suffer voltage drop and power loss, and that fat cabling to compensate would make that more expensive, but what I am thinking is that because this is so early in the construction, are there any opportunities for taking advantage of decorative or structural elements as electrical conductors?

Can I use steel reinforcements, even in steel-concrete, as the DC distribution network?
Other structural and/or decorative elements such as aluminium bars, copper plates and etc., that when arranged could also serve as DC distribution

In short, in our current home it seems absurd at face value that we have all these little USB adapters and chargers lying around, transformers, wall-warts, bricks and etc., when it seems all I really need is a USB socket in a wall.  I am wondering if there is any realistic way of achieving this that makes general sense.
Comment: This has been asked many times before and the basic answer is that it may sound economical but it is not. Unless you'd use **very** thick cables a lot of power will be lost in the DC distribution lines. Thick cables are costly. Mains adapters are relatively cheap and in the end the whole setup will be more efficient using standard mains distribution than it can ever be using low voltage DC distribution. Another reason not do distribute DC is that if it breaks, everything DC is out. With small adapters etc, you just replace the faulty one.
Comment: You can't use DC power to avoid the installation of AC power. It isn't a technical issue; it's a question of what the building code and electrical code used in your area requires.
Comment: Just install these everywhere  https://www.amazon.com/dp/B00J3PMU4C/ref=cm_sw_r_cp_apa_j4wRzbSCV90K1
Comment: @Harper When you do the sums, the OP quite clearly *will* be drawing high currents.  An average room might use 6-8 8W LED downlighters depending on the room size.  Say there are 6 rooms in the house, each with 6 LED downlighters, then you've got 288W.  If you run the supply at 12V (the standard for LV lighting) then you've got 24A of current just on lighting, and we haven't even started on charging laptops and stuff.  Let's just state as a fact that this will be a high current, and move on.  The simple reason is it needs thick cables and higher-powered DC converters, and they both cost money.
Comment: @Jules: I didn't say you couldn't install DC. I'm just saying that the building code will require you to install AC as well. It seemed that the OP was hoping to avoid that.
Comment: @DaveTweed - most building/electrical codes I've looked at either don't regulate or permissively allow *low voltage* DC distribution.  The problem with that is *low voltage* => *high current* => expensive heavy cables and high power losses in those cables.
Comment: @Jules this is the same trap most are falling into.  Where did you get this concept of "high current", OP was rather specific to the contrary.
Comment: @graham depends how well he can source 24V.  I've never had a problem with lighting.  I am also skeptical of 48-64W being a typical room; that maps to 300-400W in incandescent, and I've never heard of anyone using *that much* downlighting.  You're really, really gonna want dimmers on that!!  I would at least go DC in-room... AC-DC converters *on every luminaire*, especially with the dumpster fire that is AC dimming added to the mix, offends ones sense of elegance.
Comment: @DaveTweed certainly true for the mandatory receptacles.  Code doesn't care what your furnace runs on, or your lights.  The only cases where AHJs have been *insistent* on mains hookup involved cases where the homeowner was unable to provision the minimum standard services.
Comment: I've removed the abrasive comment thread. Please keep the discussion civil and focused on improving or clarifying the question.
Comment: DC for hard-wired lighting circuits is certainly doable, but it'll have to be for fixed lighting i.e. not a standard light socket.
Comment: @Harper 8W is typically equivalent to a 40W incandescent, although newer bulbs have better efficiency and can get closer to 60W.  So 240-320W incandescent in a room, which is not too unusual for a decent-sized room.  An adaptor for each fitting is overkill, agreed; but an adaptor per room is normal. That lets you use regular mains cable for the bulk of the distance, and switch to DC cable for short distances.  Also you know *exactly* how many fittings there are, and you can choose the DC cable to match.  Wiring the whole house, you'd have to work on a worst-case basis and overspec the copper.
Answer: It's an idea that initially sounds appealing but just doesn't work out in practice.
Unfortunately for a given acceptable power loss percentage the cable size required is proportional to the inverse square of the voltage. Running any significant power any significant distance at 5V is impractical.
Once you introduce an intermediate voltage (e.g. 48V DC systems) the losses in performing the conversion (which you generally want to be isolated to prevent currents from taking unexpected routes) from your intermediate distribution voltage to the final utilisation voltage tend to eat up any gains.
Using structural metalwork would open up it's own problems, such as poor electrical insulation, risks of shorts (a short on a high current low voltage line can be no laughing matter), galvanic corrosion and great confusion for anyone who works on the property in future.
Answer: I can be very short. The most economic way is to use AC.
You will have to invest time and money for custom DC power distribution solution.
If you look at implementation challenges:
 - DC power supply.
 - DC fuses, you'd want them re-settable.
 - DC sockets, rare.
 - DC appliances.
 - DC cabling.
If you don't want heavy cables, you'd need more voltage. Say 48 Volts, since that is still reasonably low, yet somewhat standard for telecom appliances.
Now, can you get LED's for 48 Volts? Or a phone charger? A PC supply?
You probably can, but you can probably buy years of AC appliances for the money.
Not to mention the time you'd have to invest.
Also, Dave Tweed mentioned in the comments that it might be against building code. Note that there are some DC standards, since there are CEE-form 42 V plugs.
Comment: 48V or 60V is probably practical for lighting, particularly if you're interested in strip lighting (which can generate some very cool effects).  This is often available with voltages in this kind of range (e.g. http://www.heappyled.com/portfolio-item/white-48v-smd-2835-constant-current-led-strip-130led-per-meter/).  Pretty much everything else would require DC-DC converters, which are just as expensive and inefficient as their AC cousins.  Re standards for DC distribution, Power-over-Ethernet is another generally recognised standard that could be helpful.
Comment: @Jules 48-60V is also a little bit bitey, and is the level at which DC starts showing its dark side.  Now you need to start thinking about arc suppression and the rules no longer treat it as "low voltage".  I don't know know how they slipped PoE by the NFPA. The problem with all this voltage conversion is, it's not super practical.  Look harder for ways to git-r-done at malleable voltages.
Answer: Power losses depend very little on the type of current used (AC/DC), and much more on the voltage, which you didn't specify. Running 120V around your house will typically result in ~2% of power loss in the wires. With 40V, you'll lose 9 times as much, or you'll need wires which have 9 times bigger section area. 5V is only viable for very low-power applications.
Using steel structure to run your household current is a bad idea, as galvanic corrosion will eat the steel away very quickly. Running the current though indoors decorative elements is also a bad idea: imagine your DC converter fails in a way that gets high voltage into the output. Or a lightning strike. Would you feel safe in a home where you have to stay away from walls during a thunder storm?
What you can do is buy a big mains to 5V power converter, and put it in a wall with several USB wall outlets. Then you'd get a spot where you can charge your phones without the need for all these wall-warts. Just make sure the power supply is still accessible in case it breaks and you need to replace it.
Comment: It's worse than that, with 40V and the same thickness wires as before you would lose 9 times as much power.
Comment: I uprated all the answers and marked this one as correct as it addresses most clearly the ideas of using structural elements. Also, the idea of power converters and in-wall (or floor or whatever) USB slots seems pretty practical to me! Thanks for the idea.
Comment: @Harper - the first item on OP's list of things he's looking for is LED lighting.  LED lighting for a typical house could easily run into hundreds of watts, which at 12V would mean he needed 5AWG (16mm^2) or similar.  Useful calculator: http://www.solar-wind.co.uk/cable-sizing-DC-cables.html
Comment: *"buy a big mains to 5V power converter, and put it in a wall with several USB wall outlets."* Putting any power supply in a wall, if it's specifically not "in-wall rated", would be a severe code violation that would also invalidate your homeowner's insurance. Instead you can hide the power supply in an "in wall media cabinet" that has a UL rating. Even then I would consider framing and drywalling behind said cabinet (ever see a plastic power supply short, melt and damage things around it?)
Comment: Depends what you're trying to drive @PeterGreen.  Most of the loads OP is thinking about are going to pull 20 watts maybe.  You can handle that effortlessly on 14AWG@12V.   The anti arguments here presume OP is trying to run the whole house.  Aside from ignoring 30 years of experience of actual, successful solar off-gridders, that also ignores OP's own stipulation that he's only trying to power things that are small.
Comment: I still can't help wondering though....if I went the route of hot air vent heating, could I use the aluminium pipes to push DC everywhere?
Comment: @Jules there's your problem, that calculator is so horrible it's *not-even-wrong*.  You are also presuming all of a large home's lighting is on one circuit.  In your current home, are all the lights on one circuit?  Also, do you habitually burn all your lights at once? All due respect I suggest this is confirmation bias on your part, being hasty to accept problematic data whilst making worst case assumptions that you wouldn't make in an AC system.
Comment: @sentinel while your idea has *much more merit* than anyone has given it so far, and *is actually done* in thousands of homes, I would like to pause to separate you from the idea of using building structure as conductors.   Current return (-), possibly, depending on how your AHJ feels about that.  But +, out of the question.   You are half right though, over 6AWG you should absolutely be using aluminum, not that I would expect much over 6AWG unless you subpanel. *hoo boy, if my previous hasn't stirred up the EE hive, my reco for Al is sure gonna.*
Comment: @Harper - not at all.  The house I'm currently building will have a little over 500W of LED lighting in 4 circuits that have maximum usage of between 100 and 200W each.  While I wouldn't *generally* use it all at once (the plan is to use pixel strips to allow positioning of bright versus dark areas, so it's very unlikely we'd use the entire capacity of the LEDs installed... but that doesn't mean you can *assume it won't ever be used*, so you do have to use cables suitable for full rated power). Using more circuits would actually increase the expense because the total length of cable would ...
Comment: @harper a big driver is cost. Where I live I am told that electrical engineers can cost a fortune, though I don't have details. Apparently initial estimates are that the new foundation, extension, roof, groundwork and permits etc., is still going to cost less than the electrics and plumbing, of which plumbing in that shouldn't be anything radical as half the place is built already. I am wondering if it's worth just shoving in big aluminium bars around the place. (to be clear: I have no idea what I am talking about)
Comment: ... also need to increase.  Fortunately, it's a small building so I found a spot where I could install a central transformer and run cables from there without needing any longer than ~2m, but for most projects that wouldn't be possible, and the expense would get prohibitive quickly.
Comment: @Jules hold on. What's the distance of these 100W and 200W runs?  Let's do the calc properly with a non-broken calc.
Comment: @sentinel fat Aluminum busbars aren't entirely wrong, but think more in terms of *subpanels*, places it makes sense to have a distribuiton hub.  But don't think too hard about it, thousands of solar homes work just fine on 12V.
Comment: "or you'll need wires which are 9 times as thick" - not quite. You'll need wires with 9 times the *cross-sectional area*, assuming the same wire material is used. That translates to 3 times the diameter for standard cylindrical conductors. You can derive this mathematically using the [electrical resistivity formula](https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity) and the area of a circle equation (π r ²).
Comment: @ScottPrive Yes, it shouldn't be just any power supply. In-wall 5V supplies are quite common though, most home improvement shops in my town sell those, as well as wall-mountable USB sockets.
Answer: It's a great idea - and you don't have to reinvent the wheel.  It's already done widely, notably in off-grid solar homes, robustly wired RVs, tiny homes, people who want a comfortable home when mains power fails, etc.  You can adapt existing concepts, but you have to know when to let go of them. When someone naysays, they are not letting go of the right concepts.  It happens.
Justification
"Merely to save money" won't work.  Your house still needs mains wiring in the legally required locations (mainly receptacles) because Code requires it, and you can't sell your house without it, which means you can't get or keep a mortgage on it.  This means any DC system must be an "overlay" at least as far as receptacles.  I see nothing in NEC that requires 120V lighting, though.
"Because I'm off-grid" is a superb reason. "Because it's cool" is fine - it's your house.
Because I want more is a fantastic reason.  It's the 21st century for Pete's sake. Houses shouldn't lose power.  All you need to fix that is an overlay system using off-grid solar tech, and prices for those are in free-fall, and you can get in as little as a few hundred dollars if you scale carefully.  Panels, charge controller, batteries, you can have a very nice system.  With a little more work the system can power refrigerator and a well-chosen furnace (or simply a non-electric furnace) and you stand a chance of being able to ride out storms.  You won't be able to wash and dry clothes, but could watch Netflix on your TV.  (notice most routers, Roku and many TVs take 12V input, and the central-office has a submarine-sized battery bank to keep telecom up at all times, and genny backup.)
Distance and Voltage
When dealing in low-voltage, distance is a very serious factor.  This was Edison/GE lost the War of the Currents.  So cottage vs. McRanchion matters.  Corner vs middle of building, matters.  You need to think about this.  It's not a deal-breaker, just needs either smarts... or lots of feeder.   I recommend "smarts".
Voltage is a huge factor, and your choices are 12, 24 or 36 volts.  12V has far-and-away the best selection of gear, with USB fobs for instance sold at literally any gas station.  But it is the most difficult to haul distances, requiring thicker wire.  24V gear exists, but more hunting is required to find it.  In return, you get 4x the transmission efficiency, which is a Big Deal. 36V doubles transmission efficiency again, but gear is scarce, so probably not worth it.  Actually a lot of 12V gear uses switching supplies (e.g. LED drivers) which buck, and so inherently have the ability to work on 12V and 24V (and in some cases, 36).  The question is whether they enable it and had the device listed for it.  This bucking also makes them resilient to voltage drop within reason.
Anything over 36V is out of the question.  It no longer qualifies as "low voltage" and DC can get rather bitey and arcey at those voltages. You don't want to mess with that.
You might as well put a desktop shortcut for a decent voltage drop calculator, because you'll be "living there".  It's hard to find a good one that doesn't lie to you... most of the good ones are optimized for NEC mains installation, and have bugs when dealing with 12V.  This is the best I have found.
Here's a concept to let go: 3% voltage drop.  That's a mains electrical "meme" that guides a lot of really bad design, much to the delight of cable manufacturers.  It is not in Code anywhere. What's in Code is the 310.16 and 240.4D current limits, and one thing I like about Southwire's voltage calc is it takes those into account while letting you choose any % drop. You are going to have voltage drop.  Plan for it.  But it's not the end of the world: likely your supply is 13.8V if a battery is supported, and even at 15% you're still at 11.7V.  And bucking loads just won't care.
The grounding dilemma
Remember electricity wants to get back to source, not ground.  In AC mains, we wire as an isolated system -- ground is excluded from the normal current loop, it only carries ground faults. There is also one neutral-ground bond in one place only which functions as a "fault catcher" and to keep it from floating/rattling at high voltage, which isolated systems are prone to do.  That does not make neutral equate to ground. EE's hate this because they are used to GND/that little symbol being the symbol for the normal current return (what we call neutral).
What about a low-voltage DC system?  Good question.  The whole point of isolating mains is that it's hazardous - that doesn't apply to low voltage DC. Even if you built the DC system isolated, you'd still want to bond negative to the grounding system to keep it from floating/rattling. I can't honestly see a reason not to merge the DC system's grounding system and current return and building frame, provided it's rated for the current.  There's no question on a RV, boat or train; they are vehicles and this is SOP.  However in buildings, your steelwork is not as massive, nor bonded as well (vehicles are welded), and it may be a moot point anyway: you must use proper wiring methods and they don't make 1-wire Romex. You will surely be stuck dragging 2 if not 3 wires along regardless, so using the building for return may be moot.
The ultimate decider here is your AHJ, so have that conversation with him/her first.  If s/he nixes it, run the negative wires. (AHJ = Authority Having Jurisdiction, i.e. your electrical inspector).
Topology
Think about every place you want DC power to go, and how much in watts (or amps if you have decided your voltage).  You may be able to exclude large sections of your house entirely.  Think about where to put distribution.  Generally you want short runs to each load, you don't want to carry 12V long distances on thin wires.  Every segment needs to go into the voltage drop calculator to help you make good wire-sizing decisions.  I imagine most loads will be <4A going <20', so 14AWG wire will yield a <0.42V drop.
Every junction box needs to be accessible. But a distribution point only needs to follow the service panel rules if it has circuit breakers or fuses that you would reset.
Each circuit must be fused based on the thinnest wire in it: 15A for 14AWG and 20A for 12AWG.  You are allowed to use larger wire if you want to.
Anytime a switch is involved, think about relays to reduce the carrying distance of power.  Do the math both ways, but a relay can help, since the power doesn't need to travel the relay loop.
You have to break out the calculator, make the map and do the math.
Example:

This is just a quickie to convey the idea, much more could be done with it. This is with a long, narrow house with all the action on the ends, so 2 separate LV systems. Trying to run a fat trunkline down that long middle didn't make any sense, nor did running 15 "smaller" wires.  There is some fat wire between the distribution points and battery.  A choice was made to move the cable modem and router to the utility room to be near the battery, instead of wasting time trying to haul power to its difficult location in the living room.  Easier to move phone and Internet lines.  Since branches were kept short, #12 and #14 wire could be used, except for the bedroom-living room run for its lighting. There's only 40' of fat feeder and 20' of smaller feeder.
Load factors
One thing said a lot is "look how much power lights need."  6500 lumens was proposed for an "average room".   I was like "you're really gonna want a dimmer on that."  Fortunately DC light dimming is simple and reliable, unlike AC.
And why should all the lights in the house be on at the same time? Maybe the right answer is let them dim... intentionally engineer in some voltage drop, to warn the occupants not to leave lights on unnecessarily.  That makes even more sense in an off-grid/battery scenario.  where such carelessness would burn up battery.  This is the kind of design decision you get to make.
Beyond that it really comes down to a calculus of "how much are you willing to spend on wire for proportional voltage drop".  No problem getting fat wire -  4/0 mobile home feeder at $3.50/ft is more than you'll ever need.
Voltage conversion
Generally you want to do as little voltage multiplying/dividing as you absolutely have to.  Inside a normal house, thicker wire will be cheaper than a choppy, lossy voltage pump.
That's especially true for 120/240 inverters - they are very lossy, especially when they are oversized, and they lose even with no load. A lot of off-grid/solar projects fail because the user fails to account for this enormous vampire load.
I make an exception for supply - solar, wind, generator, microhydro, "use your car battery to recharge your sagging batteries 3 days into the ice storm" etc. You probably can't do much about your power source being quite far from your battery.  This is a great time to pump voltage up as high as you can, pretty much to wire insulation limits. This can be as simple as putting the solar panels in series instead of parallel, or winding the windmill generator differently, or using an inverter to pump your car's alternator up to 120/240V for haulage.
Answer:
Can I use steel reinforcements, even in steel-concrete, as the DC distribution network?
  Other structural and/or decorative elements such as aluminium bars, copper plates and etc., that when arranged could also serve as DC distribution

Decorative elements? Definitely not. That would expose voltage-carrying elements. They must be insulated.
Steel reinforcements would be a nightmare to get right. All the steel inside a slab of concrete is tied together, so it'd all be electrified. And with a large 5V supply driving that grid (say, 100A to get 500 W), anything touching the grid would be welded instantly.
Non-standard electrics also make a house harder to sell. You may know where the grid is buried inside the concrete, but will the next owner?

all I really need is a USB socket in a wall

Well, you can get those. USB-only sockets and combination 120V/USB sockets exist. These have an adapter built in.

Comment: @Dmitry Like father like son! Playing with sparks so early on :-)
Comment: I disagree with your decorative elements carrying voltage comment. There are lamps powered by low-voltage DC powered by exposed bars on the market and quite popular in restaurants etc
Comment: @Sentinel Yeah, those do exist. My kid once managed to short circuit one of these while we were in a car dealership's sales office. Luckily there was a circuit breaker to cut it off, otherwise the short could have blown the DC converter. Another issue with exposed DC bars is that you need a DC converter which guarantees to **never** get AC voltage on the output, even when it's on fire or there's a cockroach inside. This is a safety level required of medical grade SELV equipment, which is not cheap.
Answer: I'm not from your side of the pond but the ground rules are the same.
As you pass current through a cable you lose Volts.  Losing a couple of volts on a 110V circuit is a problem but no where near the problem as a percentage losing a couple of Volts is on a 24V system.  Power is in Watts and at DC that's a simple Volts x Amps.  To get the same power at 24V you need a lot more Amps and the more Amps you have in your circuit the more Volts or pressure you lose in your system.
Apart from building codes and the like there are some very good reasons why we don't power circuits at 24Vdc.
Instrumentation on industry - that's different but only passing a few milliamps.
Answer: In 10 years 5V USB charging is going to be obsolete. It actually already is. Most phones now are capable of fast chargers. Why would I charge my phone for 2.5 hours with a standard usb when fast charger takes 30 mins.  I never understood the big deal of having the adapter plugged into outlet.
Stick with A/C
If you want something to brag about you can run some lights off a solar panel.


Upgrade to Ubuntu 19.04 on HP Elitebook 840 G1 results in blinking cursor after bootloader

Question: I used to dual boot Windows (on dev/sda1) and Ubuntu 18.04, on my HP Elitebook 840 G1 (SSD).
I also have a third partition for most of my files (I believe on dev/sda2 named D:/).
I tried upgrading to 18.10, which worked, after which I wanted to upgrade to 19.04.
GRUB still finds the boot options I want, but when I try to boot into Ubuntu, I get a blinking cursor (after the ubuntu logo). Also going into "advanced options" in GRUB and selection 4.15.0-55-generic gives me the blinking cursor (after the ubuntu logo).
I wanted to know if anyone had managed to solve this? I have tried:

booting from a stick with Ubuntu 19.04 (most of the times it doesn't even boot into the stick, and when it does, I also get a flashing underscores)
boot into recovery mode and change the GPU settings as proposed by heynnema (gdm3 display manager hangs after booting with Ubuntu 18.10)

The fact that even booting from stick gives an error maybe indicates that it indeed is a graphic error?
Comment: How is this question not properly formulated? I believe something must be wrong, as I got a downvote.
Answer: This is not a proper answer, but I didn't get anywhere. What I tried and failed:

reinstall GRUB
reinstall graphics card

I ended up switching back to Ubuntu 18.04 (reinstalled 18.04 from stick onto the partition of the "broken" 19.04). Now I have a GUI. Will wait for 20.04.


Is it possible to use ComputerCraft to show the TPS of a server?

Question: Sometimes a Minecraft server is running a bit slow. How slow? Well, that's what we want to know. With this program, we should be able to see what the currently Ticks Per Second (TPS) is on a nearby monitor. Note that there are usually 20 ticks per second. This would probably be used in an admin room so that operators can see what the current TPS is.
Comment: I imagine it depends on if the Lua is emulated within Minecraft or not.
Answer: As seen in this Reddit post, there is a program called TickProfiler which is commonly used for Lag-busting. Note that this will not work unless you install the profiler on the server.
According to the creator of this program:

I've made a small update now which allows it to be used with ComputerCraft to put up a display showing the locations of laggy blocks, entities and chunks.
It's quite easy to set up, just put this lua file on a computer, and open TickProfiler's config file, then set it up to write with an interval above 0, and the file location as world/computer/COMPUTERID/profile.txt, with COMPUTERID replaced with the ID of the computer you're using to display this information.


What can I do about an old steam baseboard heating valve that wont turn?

Question: It is currently the fall. It is cool outside but is like a sauna inside due to the heaters in my apartment. I have complained about this issue repeatedly to the building super and office. They said they would get the heating guy to come but it has been nearly 2 weeks.
The super came in and said I can turn off the heat via a valve in my bedroom. However, when he tried, he could not turn the valve. I tried with a pair of vice grips, and even though I am fairly strong, I was not able to even budge it.
It looks like it is very old and has been painted over. This is an old building. I tried scraping off the paint and that accomplished nothing. Still wont budge.
My question is - how do I fix this so that it will turn off? It is 4 AM and I am exhausted but can not sleep because, despite having the windows wide open and fans on, I am sweating profusely. Also, right near where the valve is, I can hear water trickling inside the pipes, and it is quite loud.
Here are images of the valve I took:

Click for larger image
Any help would be greatly appreciated.
Comment: have the super replace the valve
Comment: @DionSoft:  Since it's now January, I presume the problem has solved itself or been solved. You might want to post a note here saying whether you found a solution that works for you, and if so what.
Answer: As a temporary solution you could cover the radiator with blankets or clothing to limit the amount of heat dissipation into the room. Don't worry, hot water/steam heating systems do not get hot enough to ignite combustible materials.
If you cannot get the valve repaired or replaced, then you may want to pick up some foam insulation boards and duct tape from a builder's supply store. You can cut the foam with a sharp razor knife to form a 3-sided box that would fit over the radiator. Then just duct tape the edges of the foam box and it should set in place against the wall. Adjust the distance the box is from the wall for regulating the heat in the room.
Comment: As far as the sound of the water: When you stop worrying about it, you really will get used to it. I've got that noise, occasional traffic noise outside, the ticking of a mechanical clock, a "thunk" now and then as my refrigerator ends a cooling cycle, and lots of other noises in the house... and most of the time I really don't notice any of them unless I'm specifically paying attention to them. Once you have the heat issue under control, you'll find you tune out everything else fairly quickly. The sleeping mind learns what noises are and aren't important.


How to turn off Eclipse auto expanded my project folders?

Question: I'm developing in Android (not sure if that matters) on a sustaining project at work.  I have a very large project with too many files in each folder.  Every time I click on an opened file's tab in the source code editor, Eclipse automatically opens the folder where the file is located.  How can I turn this off?
Answer: I'm not sure if this is what you mean, but in the sidebar (package explorer) there is a button at the top that is 2 yellow arrows pointing towards each other. You should click this to stop the editor auto syncing the explorer. It is a persisting button click so you click once to enable the feature and again to disable it.
Comment: It is "Link with Editor" button
Answer: For me worked click on "Focus on active task".


'Continue' and 'Retry' buttons location in action div

Question: Regarding a Web console:
I have a process that stops from time to time when it has warnings and fails.
I'm allowing the user to retry or continue after taking care about the warnings and fails.
Retry - the process will retry the operations on the failed\warning entities
Continue - the process will ignore the failed\warnings entities and continue to the next phase
the 'Retry' and 'Continue' buttons are part of new div displayed\showing up in an end of running step.
What order should the buttons be placed?
"Retry , Continue" or "Continue , Retry"
Answer: This can be compared to the OK-Cancel situation Nielsen/Norman group described in an article: http://www.nngroup.com/articles/ok-cancel-or-cancel-ok/
Spoiler: there is no right or wrong.
There are, however, a few things to keep in mind. First of all, make sure your choice is consistent. So if there are more situations like this, always put the confirmation button (in your case continue). If you're working on a desktop app, the OS can be the guideline for the order the buttons need to be in. If you're working on a web-app, this isn't as straightforward as on desktop and a look at the statistics can help you out. Are most users using a windows machine, then it's wise to put the OK-button first.
You can also use focus-state to guide to the attention of the user to the OK/Continue button. But unfortunately, this is also uncommon on the web. To solve this, you could design an alternate style for the button that stands out a more. Also, try to be descriptive in your labeling, just as you did with continue (instead of OK or confirm)
Answer: It should be in the following sequence:

Retry
Continue

Reason: Retrying ensures that the user tries again to see if the Warning is now resolved and go ahead with a successful compilation. Hence, this is the recommended action to be first.
Continue ignores the warnings and can be used on the second go if the Retry option doesn't work. However, the recommendation will be always to retry.
Also, you could rename Continue to Ignore to make more sense.
Comment: Changing the label to 'ignore' or 'ignore the warning' is a good idea i think. However, I think you put too much emphasis on the order of the buttons. Mac users will expect the reverse order.
(windows: http://img.usabilitypost.com/0808/windows_save.png) (mac: http://www.macsinlaw.com/wp-content/uploads/2011/02/document-save-dialog1.jpg)
Comment: It needs to be in the order I have mentioned. This was not exclusive to Windows but as a good UX principle overall. The screenshot attached is only to give an example to support my point on the order. The order must be Retry and Ignore because Retrying is what needs to be done first, before ignoring. Please consider that the question hasn't mentioned Mac.
Comment: I did consider that and I only used Mac as an example. The question didn't mention Windows either. It mentions a web console, so you don't know what operating system the user is using. It could be anything from Windows to Linux. Maybe even a mobile operating system or the exotic OS2. Could you point to research that back-ups your claim?


How to use systemColor in the opposite way

Question: I want to use systemColor in the opposite way in iOS13 UIColor, for example, systemGray6 is (242,242,247) in LightMode and (28,28,30) in DarkMode, but I want to use (242,242,247) in DarkMode and (28,28,30) in LightMode. What should I do? Apple says:

Don't hard-code system color values in your app. The color values
provided below are intended for reference during your app design
process. The actual color values may fluctuate from release to
release, based on a variety of environmental variables. Always use the
API to apply system colors; for developer guidance, see UIColor.

so how can I use systemColor in the opposite way and avoid hard-code system color values?
Answer: Simple Answer is create new colour set
First go to your project Assets .Add new colour set.
Then change it's appearance  to Any,Dark,Light. set colours what you want in light or dark.
Now you use this colour in anywhere as color
something.color = UIColor(named:"myColor")


Java Debugger says, that i have problem with java version

Question: After build attempt, java debugger extension pack returns:

My Java environment:

My settings:

If i press Proceed, application programm works correctly.
There some few java versions, but i'm already added PATH and JAVA_HOME.

How can i disable that problems from Java Debugger Extension in VSCode?
Comment: The problem may be due to the Java Debugger Extension not supporting this version of Java. Try using it with Java 8. Also, check any settings in VS Code that might be setting Java source and target versions to 1.6 or below (I'm not familiar with VS Code so don't know where to find them).
Comment: Based on some compilation errors (e.g.: `'<>' operator is not allowed for source level below 1.7`), it looks like you have the source level for your build set to an invalid value (perhaps 5 instead of 12?), so review the build settings for your project.
Answer: try to change the extension generated file .settings/org.eclipse.jdt.core.prefs like :
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8


File upload control reactive forms

Question: Issue
I currently have a form that has a bunch of fields, one of them being a file upload field. They all form part of a FormGroup that is declared in my constructor. Now all the text controls I am able to access by using this.control.value except my file control. When I try to access the value of the form control for the file all I get is C:/fakepath/image.png.
Is there a way to access the actual file data so that I can upload it to my API?

Code
My FormControl declarations:
/**
 * Category of the product
 */
public category = new FormControl('', [
  Validators.required
]);

/**
 * Name of the product
 */
public name = new FormControl('', [
  Validators.required,
  Validators.minLength(3)
]);

/**
 * Description of the product
 */
public description = new FormControl('', [
  Validators.required
]);

/**
 * Price of the product
 */
public price = new FormControl('', [
  Validators.required
]);

/**
 * Image of the product
 */
public image = new FormControl('', [
  Validators.required
]);

My constructor for the page/component:
constructor(private api: ApiService,
  private formBuilder: FormBuilder) {

    this.productForm = formBuilder.group({
      category: this.category,
      name: this.name,
      description: this.description,
      price: this.price,
      image: this.image
    });
}

How I am currently trying to access the file
public async createProduct(): Promise<any> {
  console.log(this.image.value);
}

Comment: Angular doesn't support files in its forms. You will have to set it by hand (as far as I know, of course)
Comment: you can serialize `this.productForm` and add it into the FormData as a property and add the image as a seperate property.
Answer: Step 1: HTML Template (file-upload.component.html)
Define simple input tag of type file. Add a function to (change)-event for handling choosing files.

    Choose File
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">

Step 2: Upload Handling in TypeScript (in component file)
Define an default variable for selected file.
fileToUpload: File = null;

Create function which you use in (change)-event of your file input tag:
handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
}

Step 3: File-Upload Service
By uploading a file via POST-method you should use FormData, because so you can add file to http request.
postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    // Append image file to formdata as a seperate property
    formData.append('fileKey', fileToUpload, fileToUpload.name);

    // Append reactive form data too in a seperate property
    formData.append('productForm', JSON.stringify(this.productForm, null, 4));
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

Answer:
Is there a way to access the actual file data so that I can upload it to my API?

You can access it in that way:
// template
<input
 type="file" (change)="onFileChanged($event)"
>

// component
onFileChanged(event) {
  // this.image will be updated each time the file
  // in input will be changed
  this.image = event.target.files[0];
  console.log(this.image);
}

createProduct(): Promise<Product> {
  console.log(this.image);
  const formData = new FormData();
  formData.append(
    'image',
    this.image
  );

  // add other fields to formData:
  formData.append("name", this.productForm.controls['name'].value);

  formData.append("description", this.productForm.controls['description'].value);

  const url = 'urlToApi';

  return this.http.post(url, formData)
    .toPromise()
    .then(response => {
      return response;
    })
    .catch(err => console.log(err));
}

File upload control reactive forms


Deriving Fourier inversion formula from Fourier series

Question:
Let $g\in C_0^{\infty}(\mathbb{R})$ (infinitely differentiable with compact support), and let $$\hat{g}(y)=\int_{-\infty}^\infty g(x)e^{-ixy}dx$$ Assume that $\hat{g}$ is in the Schwartz class. Prove that $$g(x)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\hat{g}(y)e^{ixy}dy$$
We may use the result that if $f\in C^{\infty}(\mathbb{R})$ is a periodic function of period $2L$, then $$\hat{f}(x)=\sum_{n=-\infty}^\infty \left(\dfrac{1}{2L}\int_{-L}^Lf(y)e^{-in\pi y/L}dy\right)e^{i\pi nx/L}$$

I'm trying to follow    Steven Stadnicki's hint. Since $g$ has compact support, let $N$ be such that $g(x)=0$ for all $|x|>N$. Choose $L>N$, and let $f_L(x)=g(x)$ for $|x|\leq N$ and extend $f_L(x)$ periodically with period $2L$ to all of $\mathbb{R}$.
Then we have $$\hat{f_L}(x)=\sum_{n=-\infty}^\infty \left(\dfrac{1}{2L}\int_{-L}^Lf(y)e^{-in\pi y/L}dy\right)e^{i\pi nx/L}$$
If I send $L$ to $\infty$, in some sense I get the function $g$. But I'm still confused how the Fourier coefficients of $f_L$ will translate to the coefficients of $g$.
Comment: You know that $g()$ has compact support, so in particular there's a $N$ such that $g(x) = 0$ for all $|x|\gt N$.  What if you choose $L\gt N$, and set $f(x) = g(x)$ for $0\leq |x| \leq N$, extended periodically to all of $\mathbb{R}$?
Comment: introduce a gaussian term in your proof, and make use of the fact the FT of a gaussian is still a gaussian. @MikaH.
Comment: @StevenStadnicki Then I would get the Fourier coefficients of $f$ in the formula that I mentioned. But how does that imply the coefficients of $g$?
Comment: My thinking was that you ought to be able to (a) show the inner integral 'converging' to the Fourier transform of $g()$, and (b) show the outer sum becoming a Riemann sum for the inverse Fourier transform...
Comment: @StevenStadnicki The inner integral converging as $L\rightarrow\infty$, you mean?
Comment: Mika: precisely.  (You may need to do some rescaling somewhere along the way, of course)
Comment: @StevenStadnicki I'm still confused (please see edit). It would be great if you could provide more detail.
Comment: @freak_warrior I think that would be too complicated to introduce a Gaussian. Is there a simpler way, along the lines of Steven Stadnicki's suggestions?
Comment: Should it really be $\hat{f}$ and $\hat{f_L}$ in the third and fourth displayed equations? I think it should be $f$ and $f_L$.
Answer: My outline of solution:
Replacing $\hat{g}(y)$ by the integral, we will obtain
$$\frac{1}{2\pi}\int_{-\infty}^{\infty}\hat{g}(y)e^{ixy}dy=
\frac{1}{2\pi}\int_{-\infty}^{\infty}\left(\int_{-\infty}^{\infty}g(z)e^{iy(x-z)}dz\right)dy$$
Next we multiply a term $e^{-\frac{\epsilon^2y^2}{4}}$ into the integration, and consider the limit as $\epsilon\to0$,
$$A(t)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\left(\int_{-\infty}^{\infty}g(z)e^{-\frac{\epsilon^2y^2}{4}}e^{iy(x-z)}dz\right)dy$$
After simplifying, we get
$$A(x)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\hat{g}(y)e^{-\frac{\epsilon^2y^2}{4}}e^{ixy}dy$$
Since $|\hat{g}(y)e^{-\frac{\epsilon^2y^2}{4}}e^{ixy}|\leq|\hat{g}(y)|$,
$$\lim_{\epsilon\to0}A(t)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\lim_{\epsilon\to0} \hat{g}(y)e^{-\frac{\epsilon^2y^2}{4}}e^{ixy}dy=\frac{1}{2\pi}\int_{-\infty}^{\infty}\hat{g}(y)e^{ixy}dy$$...
Comment: In case it's not entirely clear to OP: dominated convergence is used here (with logic somewhat backwards from what you might expect).


jquery .not() usage to exclude spedified selector by parent id

Question: A given script selects two elements, but I want to exclude one specific which is defined by  it's parent ID: '#submenu li#livezilla a'
I tried this:
$("#hauptmenu li a, #submenu li a").not("#submenu li#livezilla a").bind("mouseover", function(e) {
    e.stopPropagation();

but something wrong (no knowledge of jquery or JS on my side - - -)
Comment: You have to include the javascript error on your question. Is that the whole line with the error?
Answer: The selectors work just fine. I tested it, and it selects all the links it should:
http://jsfiddle.net/RMdjd/
So, there is either something wrong with your HTML code, or what you are trying to do doesn't work.
It sure does have some effect, but it might actually be the opposite of the intended. The event seem only bubble from the one element that doesn't have the event handler. Pointing on li elements will change their background color, but pointing on the a elements doesn't cause the li element to change background color, except for the one a element that does't have the mouseover event handler:
http://jsfiddle.net/RMdjd/1/
Comment: wow! what a fast and thorough reply, thanks!
The thing is more complicated; I have a script, jquery.menumator.js, which affects another script, LiveZilla Live Chat.
http://wishbone-design.de/flexible-layouts.htm

I just found out - it works if the URL with www is used! The CMS is modX.
so it's not related to this selector!


How can I make Facebook App page visible on mobile?

Question: On my client's Fanpage, a third party app is running for a contest. How can I make this FB contest page available on mobile? I read the answer here:
http://facebook.stackoverflow.com/a/10833366/461119
also
Facebook SDK : Page Tab App returns not found in mobile Facebook App
I do not understand it clearly.
Is the query parameter <code>?ref-ts</code> which we have to add at the end of URL?
What does it mean by "It helps in the browser but not the app itself."?
Will it help to see the App on mobile and click on it to go to the contest page on FB?
Also, I found this answer:

Works as advertised! Thank you. I was getting 404, but simply adding
  ref=ts in my redirect URLs (I force users to use my app as a page tab)
  fixed it! – Guillaume Boudreau

under the first link above but what is forcing users to use app as a page tab?
How can I set App as a page tab?
little bit confused.
I searched the web vigorously but did not get any clear explanation.
Answer: My observations about this issue:

Seems like it's an ANDROID issue, Work OK on iPhone's
Work with the link redirection services like Bit.ly (where the bit.ly link included the ref=ts)

I sent an email to Facebook for ANDROID developers.

Hi,
my iPhone's user colleagues can open links to page tab app with ref=ts
  parameters but on Android we can't ;-(
The only way we've been able to do it is when the link to the app is
  under a bit.ly redirection link
The problem is only when the links are open through the Facebook App.
Thanks
Let us know
Max*
Answer: You can access to your app using the next link https://apps.facebook.com/YOUR-APP-ID
In this way, you can access from a desktop or a mobile with no problem.
Comment: This only works for canvas apps. The issue still persists with page_tab apps.


Empty Destructor Crashing Program: C++

Question: The following program calculates all primes for really large numbers (eg. 600,851,475,143). Everything works right so far except when I put in large numbers the destructor is crashing the application. Can anyone see something wrong with my application?
After rechecking my solution the answer is wrong but the question still is valid.
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <cmath>
#include <stdexcept>
#include <climits>

typedef std::vector<unsigned long long>::const_iterator prime_it;

#define MAX_COL 900000

struct large_vector
{
public:
  large_vector(unsigned long long size, unsigned int row) :
    m_Row(row)
  {
    m_RowVector.reserve(size);
  }
  std::vector<bool> m_RowVector;
  unsigned int m_Row;
};

struct prime_factor
{
public:
  prime_factor(unsigned long long N);
  ~prime_factor() {}
  void print_primes();
private:
  std::vector<bool> m_Primes;
  std::vector<large_vector>m_Vect_Primes;
  unsigned long long m_N;
};

prime_factor::prime_factor(unsigned long long N) :
  m_N(N)
{
  // If number is odd then we need the cieling of N/2 / MAX_COL
  int number_of_vectors = (m_N % MAX_COL == 0) ? (m_N / MAX_COL) : ((m_N / MAX_COL) + 1);
  std::cout << "There will be " << number_of_vectors << " rows";
  if (number_of_vectors != 0) {
    for (int x = 0; x < number_of_vectors; ++x) {
      m_Vect_Primes.push_back(large_vector(MAX_COL, x));
    }

    m_Vect_Primes[0].m_RowVector[0] = false;
    m_Vect_Primes[0].m_RowVector[1] = false;
    unsigned long long increment = 2;
    unsigned long long index = 0;
    while (index < m_N) {
      for (index = 2*increment; index < m_N; index += increment) {
        unsigned long long row = index/MAX_COL;
        unsigned long long col = index%MAX_COL;
        m_Vect_Primes[row].m_RowVector[col] = true;
      }
      while (m_Vect_Primes[increment/MAX_COL].m_RowVector[increment%MAX_COL]) {
        increment++;
      }
    }
  }
}

void prime_factor::print_primes()
{
  for (int index = 0; index < m_N; ++index) {
    if (m_Vect_Primes[index/MAX_COL].m_RowVector[index%MAX_COL] == false) {
      std::cout << index << " ";
    }
  }
}

/*!
 * Driver
 */
int main(int argc, char *argv[])
{
  static const unsigned long long N = 600851475143;
  prime_factor pf(N);
  pf.print_primes();
}

Update
    I am pretty sure this is a working version:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <cmath>
#include <stdexcept>
#include <climits>

typedef std::vector<unsigned long long>::const_iterator prime_it;

#define MAX_COL 900000

struct large_vector
{
public:
  large_vector(unsigned long long size, unsigned int row) :
    m_Row(row)
  {
    m_RowVector.resize(size);
  }
  std::vector<bool> m_RowVector;
  unsigned int m_Row;
};

struct prime_factor
{
public:
  prime_factor(unsigned long long N);
  ~prime_factor() {}
  void print_primes();
private:
  std::vector<bool> m_Primes;
  std::vector<large_vector>m_Vect_Primes;
  unsigned long long m_N;
};

prime_factor::prime_factor(unsigned long long N) :
  m_N(N)
{
  // If number is odd then we need the cieling of N/2 / MAX_COL
  int number_of_vectors = (m_N % MAX_COL == 0) ? ((m_N/2) / MAX_COL) : (((m_N/2) / MAX_COL) + 1);
  std::cout << "There will be " << number_of_vectors << " rows";
  if (number_of_vectors != 0) {
    for (int x = 0; x < number_of_vectors; ++x) {
      m_Vect_Primes.push_back(large_vector(MAX_COL, x));
    }

    m_Vect_Primes[0].m_RowVector[0] = false;
    m_Vect_Primes[0].m_RowVector[1] = false;
    unsigned long long increment = 2;
    unsigned long long index = 0;
    while (index < m_N) {
      for (index = 2*increment; index < m_N/2; index += increment) {
        unsigned long long row = index/MAX_COL;
        unsigned long long col = index%MAX_COL;
        m_Vect_Primes[row].m_RowVector[col] = true;
      }
      increment += 1;
      while (m_Vect_Primes[increment/MAX_COL].m_RowVector[increment%MAX_COL]) {
        increment++;
      }
    }
  }
}

void prime_factor::print_primes()
{
  for (unsigned long long index = 0; index < m_N/2; ++index) {
    if (m_Vect_Primes[index/MAX_COL].m_RowVector[index%MAX_COL] == false) {
      std::cout << index << " ";
    }
  }
}

/*!
 * Driver
 */
int main(int argc, char *argv[])
{
  static const unsigned long long N = 400;
  prime_factor pf(N);
  pf.print_primes();
}

Comment: [valgrind](http://valgrind.org/) has a much better chance of helping you. Generally, when you see an empty destructor crash, it means that something else has corrupted the heap before the destructor is called.
Comment: Can you give an example of "large numbers"?
Comment: Is there any flags you would pass in on the command line? Or just run "valgrind --leak-check=full "
Answer: Your usage of reserve is incorrect.
m_RowVector.reserve(size);

Here m_RowVector has space reserved so that the vector can grow without being re-allocated. BUT the size of m_RowVector is still 0 and thus accessing any elements is still undefined. You must change the size of the array with either resize() or push_back() to put elements into the vector.
I can't see anything wrong but I am sure that you have other index beyond the end of vector problems. I would change the use of operator[] into the method at() this will throw an exception when you access elements of the end of the vector and give you a clue to the actual location of the error.
Comment: Your suggestion fixed the issue and using at() is a good point. I am going to repost the code in an update once I am done fixing the bugs.

Empty Destructor Crashing Program: C++


Getting weird results

Question: Consider two nonempty sets $ S $ and $ T $,  $S\subseteq T$. We can write:
$$\forall x (x\in S \Rightarrow x\in T) $$
Knowing, that $ p\Rightarrow q $ is equivalent to $\neg (p \wedge \neg q) $, we can rewrite the previous expression as:
$$\forall x (\neg (x\in S \wedge x\notin T)) $$
Turning the universal quantifier into the existential one:
$$\neg (\exists x (x\in S \wedge x \notin T)) $$
Splitting the quantifier into two:
$$\neg (\exists x (x\in S)\wedge \exists x (x\notin T)) $$
The first conjuct in parentheses is given to be true, so we rewrite the expression again:
$$\nexists x (x\notin T) $$
Or, more familiarly:
$$\forall x (x\in T) $$
Which is a complete nonsense. Where is the mistake in reasoning here?
Comment: You can't split the quantifier.
Answer: You can't split the quantifier as you did. That's where the problems begin.
$$\neg (\exists x (x\in S \wedge x \notin T))\not\equiv \neg (\exists x (x\in S)\wedge \exists x (x\notin T)) $$
The existentially quantified statement $\exists x (x \in S \land x \notin T)$ asserts that there exists some $x$ for which two things are true about that one specific $x$, $P(x): x\in S$ and $Q(x): x \notin T$.
When you split the clause into two existentially quantified statements, you are asserting merely that there exists something, say $x$, for which $P(x)$ is true, and there exists something (perhaps something else, we'll call it $y$) for which $Q(y)$ is true. Those aren't equivalent statements.
Comment: Glad to help. Thanks for showing your work and stating the question so clearly!
Comment: I was told I can, here - http://math.stackexchange.com/questions/480830/equivalence-of-statements-with-quantifiers.
Comment: That's a different quantifier. $\exists$ and $\forall$ behave differently.
Comment: @amWhy, the last two sentences in your answer made perfect sense.
Answer: To expand a little on the comment, while we have $$\exists x(x\in S\wedge x\notin T)\implies\exists x(x\in S)\wedge\exists x(x\notin T)$$
the converse is false, so these are not equivalent statements. Adding the $\neg$ reverses the direction of the implication, so we get:
$$\neg(\exists x(x\in S\wedge x\notin T))\implies\neg((\exists x(x\in S)\wedge\exists x(x\notin T))$$
Therefore your "proof" only works in reverse, which is fine; if $T$ is the entire universe, then every other set in that universe is a subset of it.

Getting weird results


What's the most effective way to get wifi working?

Question: I'm using Ubuntu since a few years and I remember having trouble to connect to the internet with wifi on almost every version. I have been using laptop, desktop pc, with wifi dongle or with built in wifi card.
My question is : What is the safer (and by safer I mean with the best result) way to use wireless internet connection on Ubuntu ? I hope to have answers and different opinions from long-time user with experience on different pc and different way to use wifi.
The goal is for me to buy the best equipment and be able to use wireless without worrying at last.
I'm currently on Ubuntu 13.10 on a desktop pc with a Zyxel wireless dongle and it doesn't work good...
P.S. (sorry for my english :P)
Answer: WiFi performance depends mostly on the chipset on your WiFi card (or stick) and the driver for said chipset. At the moment, the driver least likely to cause problems seems to be the ath9k.
The driver info page has a list of all supported chipsets.
Usually, cards or sticks with one of those chipsets are easy (and cheap) to come by. Also, the newer models are capable of using both the n wireless standard and 5GHz frequencies, which makes them rather futureproof.
Comment: Any stick with the AR9374 chipset should do. It's hard to recommend a specific device without knowing where you want to buy it, but most decent shops include the chipset in the description.
Comment: Thank you ! Which stick would you advise me to buy for my desktop pc ?
Comment: OK Thx I will buy it ASAP and accept your answer once I have it working !
Comment: I can't find any stick with AR9374 chipset in the list of the driver info page.
Answer: Finally, I have chosen my USB wireless adapter stick by cross checking the store USB stick with the list of tested USB stick from help.ubuntu :
https://help.ubuntu.com/community/WifiDocs/WirelessCardsSupported
Comment: Installed the Edimax EW-7711UAn on 13.10 (on a desktop). It works perfectly out-of-the-box !


opencsv not reading CSV after Android update

Question: My code was working perfectly until my phone updated last night.
I'm reading a CSV file from the phones storage into an array in my app using opencsv.
This is the code...
    public static String[] getFileContents(File file) {
    String[] contentsArray = new String[500];
    if(file.exists()) {
        try {
            CSVReader reader = new CSVReader(new FileReader(file));
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                System.arraycopy(nextLine, 0, contentsArray, 0, nextLine.length);
            }
        } catch (Exception e) {
            System.out.println("Failed file: " + file);
            System.out.println("You are here and sad but at least the file exists");
            e.printStackTrace();
        }
    } else {
        System.out.println("File does not exist");
    }

    return contentsArray;
}

and this is the error I'm getting...
I/System.out: Failed file: /storage/emulated/0/Documents/text/36-12644-Test cert-2021.csv
I/System.out: You are here and sad but at least the file exists
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Documents/text/36-12644-Test cert-2021.csv: open failed: EACCES (Permission denied)

I have changed nothing. Can anyone point me in the right direction to resolve this please?
Has something changed in the new update (Android 11) with permissions that is now blocking openCSV from reading the file?
Edit:
This is the code that brings in the selected file from the fileExplorer...
                    Uri fileUri = data.getData();
                String filePath;
                try {
                    filePath = Utils.getRealPathFromURI(this.getContext(), fileUri);
                    selectedFile = new File(filePath);
                    contentsFromFile = Utils.getFileContents(selectedFile.getAbsoluteFile());

and this is the code that gets the path...
    public static String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
        return;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

Comment: Delete `getRealPathFromURI()`. Use `ContentResolver` and `openInputStream()` to get an `InputStream` on the content. Wrap that `InputStream` in an `InputStreamReader`. Pass that `InputStreamReader` to `CSVReader`.
Comment: Thanks again but I have that in the manifest already.
Comment: `InputStream input = this.getContext().getContentResolver().openInputStream(fileUri);` gets you the `InputStream`. `CSVReader reader = new CSVReader(new InputStreamReader(input))`; gives you your `CSVReader`.
Comment: "when it had been fine for a couple of months previous?" -- your existing code would have failed for lots of people in lots of situations. With respect to your device, Android 11 locked down filesystem access further, and there are locations that you cannot access by any `File` means. `getRealPathFromURI()` was always a bad solution; it has just gotten worse in recent years.
Comment: Since it's about permissions, maybe you need to re-install your app to fix permissions.
Comment: Thanks for replying. I've uninstalled and reinstalled the app dozens of times during the last couple of days. The problem persists.
Comment: Sorry, When I didn't see anything about reinstalling, I thought it was worth a shot.
Comment: I^ve found this  : https://developer.android.com/about/versions/11/privacy/storage  It mentions setting requestLegacyExternalStorage to true in your app's manifest file. That way, your app can continue to behave as expected on devices that run Android 10. If you haven't already done so already.
Comment: How are you getting the value of `file` that you are passing into `getFileContents()`?
Comment: @CommonsWare. I have edited the post to show more. The code fails at the point where I attempt to assign the new fileReader(file)
Comment: Duplicates include [this](https://stackoverflow.com/questions/59123162/android-kotlin-getting-a-filenotfoundexception-with-filename-chosen-from-file-p) and [this](https://stackoverflow.com/questions/49221312/android-get-real-path-of-a-txt-file-selected-from-the-file-explorer), among others.
Comment: @CommonsWare. Thank you very much for your reply and I'm sure you're absolutely right. However, I'm an electrician primarily and this is something I do as a hobby. I've spent the last 3hrs trying to figure how to do this as you've kindly suggested but I'm not getting very far. Could you please point me towards an example? I've explored the two links you provided and many others but I can't get anything to work.
Comment: @CommonsWare. Thank you so much for your patience with me. I have got it working again. If I haven't taken too much of your time already, could you please tell me why why method simply stopped working after the update when it had been fine for a couple of months previous?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228165/discussion-between-alan-haden-and-commonsware).
Answer: Thanks to CommonsWare I have now got the code working again.
Their solution was to

delete getRealPathFromURI(). Use ContentResolver and openInputStream() to get an InputStream on the content. Wrap that InputStream in an InputStreamReader. Pass that InputStreamReader to CSVReader.

Specifically...
InputStream input = this.getContext().getContentResolver().openInputStream(fileUri);
CSVReader reader = new CSVReader(new InputStreamReader(input));


Php delete from multiple tables

Question: I have a basic backoffice setup with a few tables listing the database content with an option to delete the rows, based on the id. But for every product that I have, I need to have different PHP delete files, in this example, "product_01", "product_02", etc.
How can I pass a custom id in the query string (href='delete_product_01.php?id=...) so I can have a conditional statement in the delete php file, this way I would only need one delete.php file.
Thank you
back.php.php
echo "x	";

delete_product_01.php
include('config_delete.php');

if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $query = mysql_query("DELETE FROM product_01_table WHERE id='$id'");
    if ($query) {
        header('location:back.php');
    }
}

Comment: ***Please*** have a look here: http://www.bobby-tables.com.  This code is very unsafe.  What if I tried to go to `delete_product_01.php?id=' OR 1=1; -- `?
Comment: Every product has its own table? That sounds like a DB design flaw, or am I reading this question wrong? You are open to SQL injections with this code.
Comment: I don't get why people keep using mysql, at least use mysqli_* if you don't want to learn prepared statements yet. but nonetheless, I don't understand how the database is set up. Could you clarify that?
Answer: You could pass the product id as second get parameter, like
delete_product.php?id=4&product_id=1

And in your delete.php you could manipulate your string in some way like
"delete from product_".$_GET["product_id"]."_table where id='$id'"

but you really should NOT do this!
Here are multiple reasons, why such code design is VERY dangerous and bad:

SQL-Injection
One could easily exploit your get parameter to get evil sql code executed. Imagine someone calling
delete_product.php?id=4';DROP database;

By doing that, he would not only delete one product, he would delete everything.
Have a look here for more information about that.
mysql_* functions
mysql_* functions are long deprecated and should not be used. There are many reasons for this, have a look at this SO-Post
Database design
Having a designated table for every single Product of yours is very bad database design. Imagine your company (or whatever instance is selling here) making a change in their product portfolio, removing or adding a product. You would need to make a huge amount of changes. If you consider revising your concept (You really should!) this post will provide you with a good starting point.

Php delete from multiple tables