Switching my VM Base Memory for Win XP from 192MB to 512MB when I have 2.7GB of ram okay?

Question: Do you think that me using 512MB of ram for my VM Base memory with Windows XP when I am running 2.7GB of ram is okay? or should I return it back to 192MB?
Answer: That completely depends on what else you run at the same time, but it should be fine. Track your Linux memory usage with free -m in a terminal window and if you start using even the slightest amount of swap, lower the RAM setting for the VM again.
When the OS runs out of actual RAM memory (which is, relatively speaking, blazingly fast), it has to use swap memory, which is a file or a dedicated partition on your harddrive (which is really slow, relatively speaking -- hundreds of times slower than RAM). Obviously, you don't want your system to run into this situation. Hypervisors (the programs that host virtual machines) tend to allocate the whole amount of RAM that you set aside for the virtual machine since allocating it bit by bit (what normal programs tend to do) would negatively impact the performance of the virtual machine guest OS.
The output of free -m looks about as follows:
username@hostname:~$ free -m
             total       used       free     shared    buffers     cached
Mem:          4025       1893       2132          0        306        956
-/+ buffers/cache:        630       3395
Swap:         4769          0       4769

As you see, the swap is not used in this case ("used" is 0). This is fine. But if you run many RAM-intensive programs, such as Firefox with a bunch of tabs (especially ones with Flash content), an image editor, and your virtual machine together, then you might be taxing your system's resources. If you computer feels like it's getting slower, you now know where to check.
I would also like to comment on the reply that quotes Ubuntu's minimum system requirements: these do not take your running applications into account, so they refer to what you need to just get the basic Ubuntu environment up and running. Any application you run on top of that environment will also require resources.
Comment: Swapping is just suboptimal from a performance point of view, not harmful. :-) Don't worry, just try and see and if it feels sluggish, close a few programs or lower the RAM setting.
Comment: what exactly do you mean the slightest amount of swap? like how do I know that and what exactly does that mean if it does start?
Comment: I've updated my answer to be more informative, @AlexPoulos, check it out.
Comment: So, how will I make sure for sure that I'm safe? because now Im worried to run it at 512MB...
Answer: According to Ubuntu reqs it would be enough if You have left for it 1GB of RAM. For example I have done something like this:
I have got a PC with 4GB of RAM, host is Ubuntu and the Guest is Windows 7. When I need to use Windows it means I need Windows at the moment, and not Linux, so my Win7 WM has 3GB of ram. The Linux is just working to run VM. But I don't run any apps on Linux in such situation.
For me such solution works really fine. So I think You could even enlarge the amount of RAM given to Your XP machine if necessary.
Comment: The post below mine says if I notice a change in swap I should lower it? so should I? or is swap okay?
Comment: Your Ubuntu will use swap if it will be forced to handle more data than it is possible for it to place in RAM. What happens then is that OS will write something like an image of piece of RAM onto the disk - exactly in the swap partition. The problem with this, is that it makes Your PC work slower, as it has to read some data from (generally slow)disk instead of fast RAM. However, due to my expierence if You run Your Windows guest and leave Ubuntu You will be able to work on Your XP without any problems. Just don't open apps on Ubuntu while using VM.
Comment: Run windows guest and leave Ubuntu? almost sounds like dualbooting.
Comment: Not really. It depends on what You need. If You want to run two systems in parallel, and to work very well, then the only option is to buy a proper hardware. For example i7, 2x GTX 480 and at least 16GB of RAM.


PHPUnit configure test

Question:
class ControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $object;

    public function  setUp() {
        $this->bootstrap = array($this, 'boostrap');
        parent::setUp();
    }

    public function bootstrap(){
        $this->application = new Zend_Application(
                    APPLICATION_ENV,
                    APPLICATION_PATH . '/configs/application.ini'
                );
        $this->application->bootstrap();

    }

    public function testIndexAction(){
        // body
    }

}

This is the class for the test. My question is how to implement the testIndexAction where the actual command on the command prompt is:
php zfrun.php -a ..index
Comment: Where does `zfrun.php` come from? Can you link to its source or post it if it's short? Zend's `ControllerTestCase` is designed to be given a route for dispatching, rendering the view, and making assertions about the resulting content.
Comment: zfrun.php comes from tests where it is also the root of the application. zfrun.php is like a bootstrap file. The actual bootstrap which is for the application Bootstrap.php also instantiates Zend_Console_Getopt which also defines the parameter to run the application.
Answer: Without seeing exactly what zfrun.php does, I can only guess, and it sounds like you need to ditch ControllerTestCase. ControllerTestCase is designed to mimic an HTTP request to send through the Zend dispatcher, but you don't need that.
Instead, you can try to mimic calling zfrun.php from the command line by setting up $argv as it would look and executing zfrun.php yourself:
function testIndexAction() {
    $argv = array(
            '-a',
            'module_name.controller_name.index',
        );
    require 'zfrun.php';
}

The problem is that this works for only one test, assuming zfrun.php defines classes or functions and cannot be required multiple times. Therefore, you'll need to do whatever zfrun.php does in a new test case base class without using zfrun.php itself. Essentially refactor its code into a reusable test helper method.
function executeControllerAction($module, $controller, $action) {
    ... whatever magic zfrun.php does ...
}

Comment: I just use manual testing. I actually needed to work on the setup of the PHPUnit test.
Comment: PHPUnit supports manual and automated testing as you've no doubt found. However, you must set up your environment to allow PHPUnit to access your classes and/or environment either route you take. Did this answer your question or help you solve the problem you're having?
Answer: If this is the test for your home page, use
$this->dispatch('/');

If not, you'll have to give it the URL that will trigger the route to load this controller.

PHPUnit configure test


How to bind an array of objects for controller PUT action

Question: I have an ASP.NET Core Web API project and I need to submit data in a specific format:
{
    "readings": [
      {
          "type": "temp",
          "value": "37",
      },
      {
          "type": "wind",
          "value": "10",
      },
    ]
}

I have a simple class Reading:
public class Reading
{
  public string Type {get; set;} = "";
  public int Value {get; set;}

  public Reading() { }

  public Reading(string type, int value)
  {
      Type = type;
      Value = value;
  }
}

And I have a class ReadingSet:
public class ReadingSet {
  public List<Reading> Readings = new List<Readings>();

  public ReadingSet() { }

    public ReadingSet(List<Reading> readings)
    {

        foreach (var reading in readings)
        {
            Readings.Add(reading);
        }
    }

}

In my controller I have:
[HttpPut]
public async Task<ActionResult<Score>> ComputeScore(ReadingSet readings)
{
  // ...
}

The problem is that the readings.Readings.Count is zero, even though I am passing three readings in. I think that the Type and Value for each Reading are not binding property (or at all) but I don't know how to go about it. Can anyone point me in the right direction to understand how to make this happen?
Comment: Which serialisation framework are you using, `Newtonsoft`, `System.Text.Json`, etc. Could be the capitalisation of "Readings" vs "readings".
Comment: Sorry I'm a bit new to .NET, how would I find that out? :)
Comment: What version of .Net are you using?
Comment: dotnet v7.0.304
Answer: I think this is because Readings is a field, not a property. Try changing:
public List<Reading> Readings = new List<Readings>();

to:
public List<Reading> Readings { get; set; } = new List<Readings>();

Comment: So it seems I need to both change it to a Property AND use FromBody (as @coyote suggested).
Answer: The problem might be in the API, try adding [FromBody]:

[HttpPut]
public async Task<ActionResult<Score>> ComputeScore([FromBody] ReadingSet readings)
{
  // ...
}
Comment: Thanks but I think the model binder might check the body automatically?
Comment: can you check and see if it works for you?
Comment: Yup, I did but unfortunately it does not.
Comment: I just tested this out in combination with SBFrancies answer and it works if I do both these things, but no with only one.


Send message to content script after page load

Question: I'm trying to iterate over an array of URL's inside background.js. For each URL, I want it to navigate the current tab, and then send a message to the content_script.js telling it to perform an action.
The problem is it's sending it immediately and not when the page loads (in fact it sends it before even updating the URL)
background.js:
  chrome.tabs.update(null, {
    url: 'https://www.example.com/' + path
  }, function(tab) {
    chrome.tabs.sendMessage(tab.id, {message: 'update_user'});
  });

content_script.js
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.message === 'update_user') {
      console.log('loaded');
    }
  }
);

Comment: The problem is likely that navigating to a new URL is async. for example if you run `window.location.href = ...; console.log("hello");`, hello will be printed and then the page will change. You can check that this is whats happening by logging `tab.status` before sending the message. It will either be "loading" or "complete". Are you getting "loading"?
Comment: I can't check at the moment but I'm certain the answer would be yes.. I can tell by not even trying it because if I do a console.log('anything') before it, I can see the prints it for a split second *before* the window redirects. Then, after the redirect that clears the console, so the word disappears, proving it logs before it even redirects.
Comment: you can check "preserve log" in devtools so that the redirect doesn't clear it. It will even log a line when the navigation takes place.
Answer: if the async page load is your issue, something like this could help:
chrome.tabs.update(null, {
        url: url
    }, function (tab) {
        chrome.tabs.onUpdated.addListener(function listener (tabId, info) {
            if (info.status === 'complete' && tabId === tab.id) {
                chrome.tabs.onUpdated.removeListener(listener);
                chrome.tabs.sendMessage(tab.id, {message: 'update_user'});
            }
        });
    });
});

This adds a separate listener to onUpdated for each of the bad URLs. Each listener is only good for the single tab that was explicitly opened so there is no chance of "accidents".
Once the tab is loaded the listener is removed and the message is sent.
Comment: Interesting... with this method is there the possibility of the content script "accidentally firing"? I ask this because the action I'm performing is a very dangerous action (it's banning a user), and because it triggers immediately on every page load, I want to make sure that if I visit a GOOD profile it doesn't automatically start running code to ban someone. The only time it can execute is if I explicitly loop over it in background
Comment: The current way I'm handing this is very ghetto (because I couldn't get the message passing method to work). I simply redirect to a URL with a `?key={{uuid}}` query string, and then in the content script I make sure the query string variable matches before doing the dangerous action. Id prefer however that it's explicit via a message pass so theres no accidentally adding the query string and banning a user you didnt mean to
Comment: hm. I see what you mean. when in this flow do you know whether the profile is "good" or not? I imagine you have some parsing logic to determine whether a ban is necessary. where does it go?
Comment: Basically the initial loop determines that (it comes from an input box in the extension popup window, and that gets sent to the background via a message). That array of URL's that the user pastes in is what I loop over. I didnt include the loop code in my example, I just simplified it to a single `chrome.tabs.update` call, but you can imagine it simply as calling that for every URL, delaying 4 seconds in between (using some ES6 await timeouts) (loop -> ban -> wait 4 seconds -> loop...)
Comment: Okay and where do you check whether the page is good or bad? In the `content_script`?
Comment: Well currently I check in the content script (using the ?key={{uuid}} method). However, the only reason I used that method is because I couldnt get message passing to work (my current solution doesnt send any messages at all, it just redirects it and checks for the ?key=). I want to switch to message passing though so I don't have to rely on a query string. I can simply redirect & message pass immediately (explicitly) so that theres no accidental triggering. So the 'check' would essentially be the array itself, because that will never be incorrect urls. then i would just delete the whole ?key
Comment: so you already know ahead of time which URLs are bad? and paste those into the extension dialog?
Comment: Correct, all URLs will be bad that the user pastes in. But I just want to prevent manually typing in a URL (say.. a few hours later when not using the extension) and the code triggers on that page of the same website which is a good profile
Comment: I'll mark it as correct even though I havent tested yet, and Ill let you know how it goes when I get home


How to search for strings inside files in a folder?

Question: Is there any utility to make searches for a string inside ASCII files to avoid command line searches?
How to make a command line search, for example for the string "test" inside all files in the directory /var/x/?
Comment: You really mean _without_ using command line ? Because the best tool for that remains grep...
Comment: On CLI [The Silver Searcher](https://geoff.greer.fm/ag/) probably does a better job.
Answer: I assume that your first question is about a GUI alternative to the grep command. I can't help you with that, I always find the command line very effective.
As for the command line, try
grep "test" /var/x/*

If you want to search recursively (i.e. not only in /var/x/, but also in subdirectories thereof), do
grep -R "test" /var/x/

To avoid grepping the files which grep thinks to be binary, use the -I option:
grep -I "test" /var/x/

If grep thinks a file is binary (based on first few bytes of the file), it will assume it does not match instead of going through the whole file.
Comment: There should be a `*` after the final slash in the path or grep does not appear to do any work in 14.04
Comment: Will it work if the folder contain some non-ascii files?
Comment: Well, grep will also try search for the string in a binary file, and report it if it matches: `Binary file file.jpg matches`
Comment: @January When a binary file is read as text, it often has extremely long "lines" (because a character or character sequence that would be interpreted to designate the end of a line may not appear for a long time, or ever). Depending on the way a text search utility is implemented, this could cause performance problems if each "line" is read fully into memory and then checked to see if it matches the search string (which is a reasonable way for `grep` to be coded, though I don't know if Ubuntu's `grep` is written that way).
Comment: "grep -i" for case insensitive search
Comment: but it may take a long time which is unnecessary
Comment: However, formally there is no difference between binary and ASCII files on a POSIX system. Therefore, I don't see why grepping "binary" files should take more time than equally large text files. Unless you completely want to avoid grepping binary files (yes, it can be useful).
Comment: Well, it all depends on the files you have. I've got plenty of ascii files with extremely long lines. Also, grep (Ubuntu uses the standard GNU grep) has a bit more complex algorithm (you can see the sources with `apt-get source grep`), and, in short, it reads long lines in chunks.
Comment: @January Is there any option for `grep` to print the actual lines matching the string? Currently I only get `Binary file myFile.pdf matches`. Thank you.
Comment: This is better than the accepted answer.
Answer: You can use searchmonkey. The tool is available in the repositories, so you can simply
sudo apt-get install searchmonkey

On the other hand, command line search with grep is really intended for that...
Here is a screenshot from searchmonkey
Comment: i have had issues with searchmonkey.  It is not trustworthy in the sense that it lets slips lots of occurrences
Comment: crashed due to too much load :(
Comment: how do I run "searchmonkey" from the GUI? after installed using the command line, I'd rather not use the command line
Answer: You can use regexxer it is a great GUI search/replace tool for regular expressions.
you can download by:
sudo apt-get install regexxer

Comment: it is super fast, but the issues i have with this application are: 1. it does not have a readonly mode, so I don't accidentally replace or delete anything 2. it shows the text, but it will not move to the specific line that the pattern has matched. (I scrolled around 2000 lines of code to find what I was after after changing the color to bright red!)
Answer: Try Recoll, best GUI one I ever used. To install recoll in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install recoll

It needs some time to index the files first (you can define blacklist path or extensions or mime).
Comment: I can confirm that Recoll is completely another world with respect to `gnome-search-tool` or `search-monkey`. It uses Xapian, so it's able to inspect and index word documents (both .doc and .docx), pdf files, mail folders, etc.
Comment: Uh, it's available through deb packaging (`sudo apt install recoll`) and it does its job where even grep fails, e.g. with .docx documents that are compressed with pkzip compression.
Comment: note that `recoll` requires building index first.
Answer: You can use the grep command from terminal:
grep -r string *
This command will find all occurrences of "string" in all the files under the current directory (or subdrectories).
For hidden files, you can use:
grep -r string ..
Answer: Unfortunately grep does a very poor job of searching inside Word (.doc) files, but you can pipe catdoc output into grep. I'm no programmer but this little script works well for me:
#!/bin/bash
export GREP_OPTIONS='--color=auto'
echo -e "\n
Welcome to scandocs. This will search .doc (NOT .docx) files in this directory for a given string. \n
Type in the text string you want to find... \n"
read response
find . -name "*.doc" |
while read i; do catdoc "$i" |
grep -iH --label="$i" "$response"; done

All improvements and suggestions welcome!
Comment: This question was about graphical applications and plain text files. I'm not sure what `grep` and `.doc` have to do with the question.
Comment: Seems OK, see January's detailed answer about `grep`.
Answer: I've just released a simple tool to do the job. Thought mainly for software developer, it has the (unique?) characteristic of openning several files in the same window. It presents the results in the browser using Ace editor (recomended!) or html textarea. It is a java based tool so it runs in windows as well as in linux.
check it out!
https://sourceforge.net/projects/queacetu.gastona.p/
Answer: per https://askubuntu.com/a/1141367/47073
You can use mate-search-tool, which is the same thing as gnome-search-tool that was removed. I had problems with searchmonkey, it was missing some results and was slow, do not recommend.
To install mate-search-tool:
sudo apt install mate-utils
mate-search-tool

Answer: You can use Sublime Text Find in Files option from Find menu to search for strings inside files from a folder.
To Install Sublime Text 3
sudo add-apt-repository ppa:webupd8team/sublime-text-3
sudo apt-get update
sudo apt-get install sublime-text-installer

You can also follow this question for other possible ways of installing Sublime on Ubuntu.
To search in all files for a string from a folder in Sublime Text you can follow this question for more clear answers.


The microphone is not recognized (Kubuntu)

Question: So I installed Kubuntu today (mic worked on Windows). The speakers work fine, but the mic doesn't and I think it is not even recognized.
There is only one option for input audio, analog input
Meanwhile I can either pick analog output or line out for output and line out gets the desired result
Clearly Kubuntu doesn't recognize the mic. And since Windows did recognize it, I doubt the cause is mechanical. What should I try to solve the issue?
EDIT: I tried taking the speaker cable out and in and I got a signal while doing this, but I didnt get a signal while putting the microphone in the microphone input, but I get it if I put it in the speaker input.
EDIT2: Curiously, the microphone works if only the microphone is plugged in but not the speakers???
EDIT3:If I plug the microphone first, the microphone works and the speakers don't. Anyone has any idea?
Comment: This is just so annoying, it would be stupid if I had to revert back to windows just due to this...
Answer: I think (I also rebooted but I think I also rebooted before lol, would it be funny if just rebooting fixed it tho - I am now almost sure it made it work, I rebooted once when not applying the setting (was able only to use the mic, actually never the speakers), and the again applaying and it worked) this handy program located here Xubuntu - how to use both front and rear audio output? helped fix the issue.


How can I fix this bathroom drain set up?

Question: Currently s trap with flexy tube and leak where pvc goes into metal pipe. I am not super concerned with s trap at the moment but would like a better set up and no leaks. I am just not sure the best way to go about it
Edit - added a picture of where it's leaking, where the pvc goes into the metal pipe. From what I can tell it is just shoved into the metal pipe, no gasket or anything. So I assume I need some kind of gasket? Not a joke, just trying to diy and make it drain efficiently without leaks. Thank you
Comment: What is your goal?? (What are you trying to fix? Is there something broken?). You mentioned you're not concerned with the S trap, so this question seems more like a puzzle.
Comment: I think this is a joke or some type of test.  The setup should be leaking badly.  The second section of the "S" trap is a ptrap upside down and the flange at the end means it must only be sitting on the first part of the ptrap from the sink.  I don't see how any of this doesn't leak.
Comment: Make sure the compression ring is facing the right direction.  In your case, I believe the flat end should face up and the tapered end should face down.
Answer: There is nothing inherently horrific with this setup.  A lot of people don't like flex tube, and I wouldn't choose it if I was doing this from scratch, but there's no gain from just replacing it for the sake of it.  It doesn't look elegant but this is in a cupboard right, so do you care?
Why not focus on the leaks?
Which end is leaking?  It's hard to see what's going on at the far end where the PVC joins a dark poorly lit pipe.  If that end is leaking, please take a better picture of it.  If it's the tail pipe end, open the connector and make sure a correctly sized compression washer is used (1-1/4, 1-1/2, or an adapting ring from one to the other) and is seating properly.
Answer: Metal pipe to PVC (S-trap) needs new seal.
Get a thicker o-ring to replace current seal. Or use some silicone or even plumber putty to seal it. Since there is no pressure both will work. I would prefer plumber putty since it is easy to remove if you have to.
Second:
The flexible tube connection from S-trap to the straight pipe could be overcome.
Loosen the nuts (just loosen do not unscrew). Now try to adjust the S-trap so you could use new (longer) straight pipe, thus eliminating the flexible tube two possible leak connections.
Comment: Genuinely curious: Where would a "new (longer) straight pipe" go in order to eliminate the flex pipe? Looks to me like the trap doesn't have enough movement to get to a vertical position over the drain stub out in the floor, so I'd think it would need a horizontal trap arm to a 90°. i.e. a new P-trap instead of the S-trap installed. Is that what you meant?


Logitech F710: Does it have cable?

Question: Can Logitech F710 be hooked up with a USB cable to computer, instead of using 2.4GHz wireless?
Comment: For those who aren't aware, since it is relevant, Logitech F710 is a Game Controller, not a mouse (as I intially thought), so I believe this IS a valid question, if not a very good one (Essentially, if you take out the shopping rec part, all you're left with is 'yes' or 'no'.)
Comment: Well, Logitech does have a wired option that's pretty similar to the 710.  I would suggest looking at that as an option.
Comment: It's **relevant** to gaming.
Comment: The first part of the question is valid. If the second part of the question is removed, then it is no longer a shopping recommendation.
Comment: Shopping rec. part removed from the question.
Comment: @WOOOOW I would suggest adding the reason why you want to do this.  Does your controller constantly disconnect, or something along those lines?  You'll probably get better answers if you do that.
Comment: @MBraedley I don't own a controller. Would like to get one. Wireless uses batteries which I don't like. Wireless is also spotty with connections which I don't like. Also, I already have 2.4Ghz band riddled with WiFi access points here, which I don't like.
Comment: @MBraedley Was thinking the same thing. Thanks, MBraedley.
Answer: A cursory glance at the product page reveals no cable attachment other than a 'reciever-extending cable' that connects into the reciever piece.  Though the reviews are vague, it seems this controller does not have a cable connection, nor the capacity to be connected by cable.
The reviews also seem to suggest that the controller has some wireless connection problems - inconsistently through different users, seeming to stem from windows versions or possibly USB Port versions.  USB 2.0 ports seem to be better suited for the controller, and windows 8.1 may have trouble reading the connection.  I suggest reading the reviews for further details.
Answer: I think there is no ability to use a USB cable with this controller, because there is no USB port.

Logitech F710: Does it have cable?


distribute $n$ white balls and $n$ colorful balls to $n$ cells

Question: I got stuck with a question stating "let there $n\ge2$ and $n\in N$. in how many ways can you distribute $n$ colorful balls (different) and $n$ white balls (similar) to $n$ cells, such that in the first $n-2$ cells there's at least one white ball and at least one colored ball?"
this is what I did, would appreciate your advice if I did it correctly or not:

by using the complementary method - let's evaluate in how many ways can we distribute all the balls without any limit - there're $\binom{2n-1}{n-1}$ ways to distribute the white balls and $n^n$ ways to distribute the colored balls. in total $n^n* \binom{2n-1}{n-1}$
let's evaluate the rest ("bad possibilities") - the bad possibilities would be there isn't a white ball in the first n-2 cells$\lor$there isn't a colored ball in the first n-2 cells =

there isn't a white ball in the first n-2 cells + there isn't a colored ball in the first n-2 cells - neither colored either white ball in the first n-2 cells

=> then accordingly the number of options: $\binom{n+1}{2}n^n$, $n^2 \binom{2n-1}{n-1}$, $n^2 \binom{n+1}{2}$.

then in total: $n^n \binom{2n-1}{n-1} - [\binom{n+1}{2}n^n + n^2 \binom{2n-1}{n-1} - n^2 \binom{n+1}{2}]$

$$$$
what do you think?
Answer: The structure of the argument is good, as are most of the details. However, there are $2^n$ ways to distribute $n$ distinct coloured balls among the last two cells. (Your calculations used $n^2$.)
Remark: If this is a homework question, it might be worthwhile to get clarification. One could interpret the wording as meaning that each of the first $n-2$ cells has at least one white and at least one coloured. I think your interpretation is the most reasonable one, but the "each" interpretation is possible.
Comment: Nicolas:  Sir, do you have a minute to check one of my answers? You could deny if you are busy.  I am not in the academic circle to discuss this and hence the reliance on you.
Comment: @satishramanathan: I can have a look at it, if you provide a link, or a clear description in a comment. However, comments can be unsuitable for typing symbol-heavy material.
Comment: @Nicolas, Here is the solution that I posted that needs a check.  http://math.stackexchange.com/questions/1837120/the-probability-two-balls-have-the-same-number/1838030#1838030.  The OP's question is not all that clear. Especially when he say in "each" jar. Barring that, the comments have been in different direction.  Also, the question stem makes some one think if the OP is meaning it to be two different distinguishable balls to be in there in at least one jar.  Please take a look at it and see if my solution fits the bill.  Although none of the answer choices equate to mine. Hence not sure!!
Comment: @satishramanathan:  I have taken a preliminary look. My interpretation would be "at least $2$ balls, and you have chosen a different one. Also, the possibilities counted by Stars and Bars are not equally likely.  To solve the problem, one should probably use one of the standard approximations to the birthday problem, likely the Poisson approximation. I think the Wikipedia article has a partial discussion.  This is only a preliminary response, I should check whether one can expect your approach to give a ballpark approximation.
Comment: So, I must accept the OP indeed meant a different version of birthday problem.  Secondly, I knew that stars and bars possibilities are not equally likely.  But for a problem like this with $10^6$ jars, you could use an approximation like the one I have done.  Thanks for answering, I shall go back and read up on the poisson approximation in Wikepedia to answer this question.  Thanks for your time. Really appreciate.  I reserve my requests to you often times.  Only at times when I am unsure about a solution to a complex problem, do I tend to "disturb"!! you.  Thanks Sir


Swift - Prevent Entire View Render on Property Change

Question: TLDR is it possible to update a single published property in a ViewModel without causing the entire View that observes it to reload?
I have a Lottie animation on a subview, and am using Firebase Realtime Database to observe changes from a cloud object.  When using MVVM, anytime a property receives a change from Firebase the entire view re-loads, causing my animation to start again.  I need to maintain an observer of Firebase as other UI changes require a dynamic update, however when any one of them change I don't want to re-draw the entire view (and subsequently set off my animation).
I've tried both @EnvironmentObject and @StateObject (simplified version seen here), as well as using != as a way of preventing an update to the local data from Firebase unless it's different.  I've read about Equatable (link), however not sure if that's applicable here?  Is it possible to update individual properties and have the view respond specifically to them only?  Thanks!
// SomeViewModel() gets created in the App struct

// Main View
struct ContentView: View {
  @StateObject var someViewModel: SomeViewModel

  var body: some View {
   LottieView(someViewModel: someViewModel)
  }
}

// Subview
struct LottieView: View {
  @StateObject var someViewModel: SomeViewModel

  var body: some View {
    Lottie(name: someViewModel.lottieToShow, loopMode: .playOnce)
      .frame(width: 250, height: 250)
  }
}

// ViewModel
class SomeViewModel: ObservableObject {
  @Published var lottieToShow: String = "lottie_city_animation"
  @Published var someOtherProperty: Bool = false

  private var isCity: Bool = false { didSet {
    updateLottie()
  }}

  private func updateLottie() {
     if isCity == true {
         self.lottieToShow = "lottie_city_animation"
     } else {
         self.lottieToShow = "lottie_park_animation"
     }
  }

  // Firebase

  private func readObject() {
     ref.child("users").child("01")
        .observe(.value) { snapshot in
           do {
              let firebaseObject = try snapshot.data(as: Object.self)
               if self.isCity != firebaseObject.isCity {
                    self.isCity = firebaseObject.isCity
               }
               if self.someOtherProperty != firebaseObject.someOtherProperty {
                    self.someOtherProperty = firebaseObject.someOtherProperty
               }
           } catch {
               print("Error reading value")
               }
            }
    }
}

Comment: Note, you should be using
 `@ObservedObject var someViewModel: SomeViewModel` in your
 `ContentView` and `LottieView` instead of `@StateObject`.
Answer: It looks like some pieces of code may have been oversimplified, CallerViewModel isn't used anywhere (unless it is presumably the same as SomeViewModel). @Published properties within an ObservableObject all trigger the same publisher to fire, namely the objectWillChange publisher.
So that will be a dead end. In general be wary of ObservableObjects getting too big. You can refactor them apart, or pass in a Publisher to the view and use onReceive(_:perform:) to respond to changes. Or pass certain data dependencies directly to a subview to try and keep changes targeted
Comment: Thanks for the comment (I have corrected the class name).  I see what you mean now by having the `ObservableObject` getting too big.  Since all of the properties come from the Firebase call, how would I refactor the ViewModel apart?
Comment: I ended up using `Equatable` [(Stack Overflow example)](https://stackoverflow.com/questions/60482098/swiftui-how-to-prevent-view-to-reload-whole-body) and setting a `var` in the view that gets checked.


How to decrypt AES/CBC with known IV

Question: I have an impossible task of decrypting AES/CBC encrypted data packets sent from a client. I've done tons of research leading me to believe that the encryption is insecure if the IV is static. For this task specifically, the IV is always statically set to 0. Is there any way this can be done?
EDIT:
The plain text is snippets from the script of Hamlet. The client sends them in random chunks so the length is not even consistent. The packets may eventually repeat but I'm not 100% sure.
Comment: Are there known patterns/repetition in the plaintext?  I don't know an approach for completely random plaintext.
Answer: Not without the key.
Specifically, assuming there's no padding, the vulnerability that occurs with using the same IV every time is that if you start out encrypting the same data you encrypted last time, you'll get the same encrypted string both times.  This allows attackers to infer something about the message content, though it doesn't help them decrypt it.
Answer: Just for notation, the term "decrypting" means the normal operation using the key. If you don't have the key, this is normally called "breaking", "cracking" or "cryptanalysis".
CBC with a fixed initialization vector has the property that messages (encrypted with the same key) with identical starting blocks will also show identical starting blocks in the ciphertext ... and this is about the only weakness. So if you can get your victim to encrypt some guess for your message (with the same key), you can compare its ciphertext to the one used in the message you are using.
This is easier when the message is of some fixed format, and hopeless if the message contains enough random data before the interesting part (this is "poor man's initialization vector").
Other CBC weaknesses which depend on chosen ciphertext attacks where you chose the initialization vector and observe some validation of the decryption thereof might also be applicable (you would set the first ciphertext block and observe whether the second block has valid padding).
Answer: The main problem with a non-random IV is that two identical initial blocks encrypted with the same key will produce the same output. So, given your description of pieces out of Hamlet, knowing that you are using the same IV repeatedly, I would do the following:

I would compute the ciphertext for "To be or not to " (16 bytes) for a wide variety of likely passwords (as might be generated by John the Ripper).
I would compare the resulting cipertext against all the messages, based on the premise that they might start with these 16 bytes.
If one matches, I know the password. Done.

I'd do the same with several other well-known phrases. This is an operation I can do massively in parallel even before I capture your file and cache in a database. The general term for this approach is a rainbow table.
My job gets much, much easier if I happen to know the first 16 bytes of your messages (such as if they're email messages to a known person, or HTTP requests with known headers or the like).
But what if you use random keys (or a proper KDF like PBKDF2)? Well, let's say I have a few messages from you, and at least some of them have the same first 16 bytes (again, headers in the protocol help me a lot here). Well, step one is that I know that these messages have the same first 16 bytes. That's pretty useful information. And now I have a crib for attacking your messages.
Reusing an IV+Key in CBC doesn't completely destroy its security (as reusing a Nonce+Key in CTR mode does). But it gives the attacker a lot of helpful tools in simplifying the attack.
I'm not saying that any of these would allow you to decrypt your specific ciphertext in some short period of time. But they all strongly degrade the alleged strong-cryptography of AES.
Answer: Zero IV can leak some information about the first  bytes of data, however, if they differ this should not be an issue (however, it is not recommended to use).
For instance, OpenPGP uses zero IV in some cases.

How to decrypt AES/CBC with known IV


c++ template specialization parameter duplication

Question: Recently I have noticed the following problem with template specializations.
Note if we have the following specialization for f and the template parameter name can be a very long type, possibly derived from other templates.
template <class T> void f(T t) {}

template <>
void f<VeryLongType>(VeryLongType t)
{
    using T = VeryLongType;
    // ...
}

Note this very long type name is duplicated 3 times. Also if f returns a value of this type, then another duplication will be introduced (auto
 will be a workaround).
I am wondering if there exists some simplified syntax for this so that no duplications are necessary?
Maybe like the following:
template <>
void f<T = VeryLongType>(T t)
{
   // ...
}

Comment: But what if I don't want to expose this `ShorterType` outside of f.
Comment: You could just alias the type before the specialization. `using ShorterType = VeryLongType; template <> void f(ShorterType t) { }`
Answer: You don't really need to explicitly specify the specialization type, e.g.:
template <>
void f(VeryLongType t)
{
    using T = VeryLongType;
    // ...
}

is fine. The type alias can be shortened with decltype(t) if VeryLongType is really very long...
using T = decltype(t); // makes it more generic too

Comment: Also `auto f(VeryLongType t) -> decltype(t)` if the type needs to be used as a return type.
Comment: But if `VeryLongType` does not occur in the parameter list, then we have to supply types for `<>` and `decltype` won't work. We will still have two duplications, i.e., the `<>` and `using`.
Comment: @Ling True. But if we are to make this generic then there are two options: make the type shorter, why so big? or sacrifice exposing it to the outside world with an alias.
Comment: @DeiDei I agree we should design types with short names. But the `VeryLongType` might come from another template specialization, for instance, one involving traits. In such a case there is no point of introducing a new type alias outside of `f`.
Comment: @List To be honest, templates can often times get notoriously obscure. That's C++. I don't believe there is a better way to shorten this.


Is there any better way of organising details in page

Question: Please have a look at screen shot attached. Is there any way to organise the details.

I am not a designer but tried with following but looks clumsy
Answer:

Your second effort is on the right track. What's important in real estate leads? Mainly the contact information which should be at the top followed by their "Guest Desires"...price range/move-in date/other must haves/etc.
Consider tabs for stashing "Additional Details" or other data not critical for the sale process.


What's the cleanest way to add a blank line after a section of a Mustache template?

Question: Let's say I want to render multiple collections in a Mustache template. I might have this:
some header content

{{#foos}}
some foo content
{{/foos}}

{{#bars}}
some bar content
{{/bars}}

some footer content

Now, supposing foos and bars above are both non-empty, then everything will look fine. But if foos is empty, for example, I'll see two blank lines after "some header content", which is ugly. On the other hand, if I omit the blank line between the foos and bars sections, then when both collections are non-empty there will be no break between them, which is also ugly.
Here's one solution that I think would work:
some header content

{{#foos}}
some foo content
{{/foos}}
{{#flag_that_foos_not_empty}}

{{/flag_that_foos_not_empty}}
{{#bars}}
some bar content
{{/bars}}

some footer content

But then the template is ugly.
Is there any clean way to achieve what I'm after here: inserting a line break at the end of a collection, only if the collection is non-empty?
To be clear: I realize this would be a pretty ridiculous thing to worry about if I were generating text for computer consumption, like HTML. In this case I'm attempting to use Mustache to generate some human-readable content, where attractive presentation of the content is important.
Answer: Something like this would do the trick, and not be as ugly, IMO:
some header content

{{# has_foos }}
{{# foos }}
some foo content
{{/ foos }}

{{/ has_foos }}
{{# has_bars }}
{{# bars }}
some bar content
{{/ bars }}

{{/ has_bars }}
some footer content

Depending on your Mustache implementation, you might be able to replace those "has" tags with {{# foos.length }}.


React router not rendering the correct component

Question: I am having a weird problem with react routing and this might just be something stupid. I a route /products which renders a component. Now I am trying to make another route /products/:id/confirmation-email but react redirects me to the products component. If I change either of the routes to something else it works fine.
<ProtectedRoute
        path="/products"
        component={Products}
/>

<ProtectedRoute
        path="/products/:id/confirmation-email"
        component={ConfirmationEmail}

/>

Comment: can you add code to the question ?
Comment: @adityakumar look at it now?
Answer: Try passing exact props inside your route.
  <ProtectedRoute
            exact
            path="/products"
            bootIntercom={bootIntercom}
            trackPageVisitOnMixpanel={trackPageVisitOnMixpanel}
            component={Products}
    />

<ProtectedRoute
        exact
        path="/products/:id/confirmation-email"
        bootIntercom={bootIntercom}
        trackPageVisitOnMixpanel={trackPageVisitOnMixpanel}
        component={ConfirmationEmail}

Answer: Try moving the confirmation route above the products route in your code like this.
<ProtectedRoute
        path="/products/:id/confirmation-email"
        bootIntercom={bootIntercom}
        trackPageVisitOnMixpanel={trackPageVisitOnMixpanel}
        component={ConfirmationEmail}

/>

<ProtectedRoute
        path="/products"
        bootIntercom={bootIntercom}
        trackPageVisitOnMixpanel={trackPageVisitOnMixpanel}
        component={Products}
/>


java.lang.IllegalStateException: No clusters found. Check your -c path

Question: I use the following command at the commandline to cluster data using Mahout kmeans algorithm
mahout kmeans -i /vect_out/tfidf-vectors/ -c /out_canopy -o /out_kmeans -dm
org.apache.mahout.common.distance.SquaredEuclideanDistanceMeasure -cd 1.0 -x 20 -cl

where /out_canopy is the directory containing clusters created using Mahout canopy clustering which contains a clusters-0 directory which itself contains a directory named _logs and a file named part-r-00000
but it keeps reporting the following error
java.lang.IllegalStateException: No clusters found. Check your -c path.
at org.apache.mahout.clustering.kmeans.KMeansMapper.setup

Answer: are you sure that /out_canopy is directory? Did you tried:
file /out_canopy

It seems there is a typo and you wanted to write only out_canopy or somehow similar ...
Comment: out_canopy does indeed appear to be a directory. This is what `hadoop fs -ls /` gives

`drwxr-xr-x   - rupinder supergroup          0 2013-03-07 17:11 /out_canopy`
Answer: This is a particularly vexing problem.
1. Swallow IllegalStateExceptions thrown by removeShutdownHook in FileSystem. The javadoc states:

    public boolean removeShutdownHook(Thread hook)
    Throws:
    IllegalStateException - If the virtual machine is already in the process of shutting down

So if we are getting this exception, it MEANS we are already in the process of shutdown, so we CANNOT, try what we may, removeShutdownHook. If Runtime had a method Runtime.isShutdownInProgress(), we could have checked for it before the removeShutdownHook call. As it stands, there is no such method. In my opinion, this would be a good patch regardless of the needs for this JIRA.

2. Not send SIGTERMs from the NM to the MR-AM in the first place. Rather we should expose a mechanism for the NM to politely tell the AM its no longer needed and should shutdown asap. Even after this, if an admin were to kill the MRAppMaster with a SIGTERM, the JobHistory would be lost defeating the purpose of 3614


IC2 brewing recipes?

Question: Whenever I try to brew things in Industrial craft 2, I always get "Black Stuff". What are some brewing recipes that make things other than Black Stuff?
Comment: Are you talking about alchemy, or beer brewing?
Comment: I'm talking about beer brewing.
Answer: Fermenting booze in Industrial Craft2 is one of the more complicated (and under-documented) parts of the mod. There are something like 200+ possible recipes that produce something drinkable when you include fermentation time variables.
It sounds like you're getting out either "Dark Stuff" or "Black Stuff". Depending on who you ask, that's what happens when you put the ingredients for a dark brew in (1:2:3 ratio of wheat to hops to water, I think) but tap and drain it before it really starts to ferment, or it's what you get out of a booze barrel when you put in too many solids with too little water. Either way, they're both a useless drink, unless you enjoy poison and want to impress your spider friends. Fermentation takes between 2 hours (real hours) and 12+ hours for beer, and up to a day (again, a real day, not a minecraft day) for good rum.
You can vary the result even for very young (no fermentation) brews by altering the ratio of wheat, hops, water. You can get even more variation by leaving it fermenting for several Minecraft days or weeks to let the character and alcohol develop – just like a real-life homebrew.
The IC2 Wiki has a decent starter guide to beer and rum brewing on the Empty Booze Barrel page, including many of the ratios and the beer styles that they give. The effects of each is left up to the player to discover.
Note that if you filled the barrel up quite a bit (many multiples of the wheat:hops:water mix), you will get out as many drinks as you put in water cells. If you have a substantially-full barrel, you can tap it, fill a mug and try it, and then take the tap out to let the rest continue fermenting. You can set up a few barrels in a cellar so you can start a variety of mixes at once to see what they do as they age. This is a good way to experiment to find out what kind of beer (and its effects) you prefer. Beware of unfermented drinks though – they tend to have strictly harmful effects, and some of it can outright kill you. There is a long thread about brewing recipes on the IC2 forums that is an attempt to collect research on recipes and their effects.

IC2 brewing recipes?


What are the lyrics for the opening music?

Question: I've noticed that there are a few versions of the rap that plays when you first launch Trials Evolution. How many versions are there? What are the lyrics for each version?
Answer: There are at least 3 different versions.  Although, I couldn't verify the exact answer to this question, here is what I have found to be a close verification to it:

Song 1:
  Give me the keys to this motorcycle let me start up
  yeaaaaaaaah
  vroom vroom im ready to go
  time to let the mo mo mo monday night stroll
  this is the moment you've been waiting for
  lock up the basement and the front door
  noone coming in
  time to time trials
  im getting ready baby im racing all night and while
  everybody here is waiting to play my highscore stands all day
  yeah here we go
  do not hold me back
  do not try to ride on the back of my motorcycle
Song 2:
  I think theres something you should know about me, I just happen to....
  like trials i like danger i like fire i like nitro i like getting it wild
  i like a bit of blast i like taking it fast i like going to the end and doing it with no class
  trust trust trust trust me on this
  the moment you've been waiting for kiss kiss kiss of death
  and ill meet you at the next step but you cant make it so baby get in line i guess
  where im coming from, from all sides high above fire flakes (????) monday nitro
Song 3 - (Very hard for me to understand him)
  Whenever I'm riding, I'm always extra careful and I like to...
  Burn my tires hotter than hell
  You can always smell the rubber burnin' as well
  Be on the limit and stop when im going safe
  Destruction Devastation thats my play
  Welcome home
  put your feet up lets begin
  time trials is ready bu-bu-bu-bu-bu baby its in
  ready fast the full gear flyin
  through the sky nitro is burning you're dyin
  this is the mo mo mo mo moment you been waiting for
  nitro time trials need i say more
Comment: I heard the soundtrack to this game is bad, but this... this is something completely different...
Comment: @Brysonic Hope it helped!
Comment: Thanks for the answer! It looks like there's at least one other intro rap (see here: http://www.youtube.com/watch?v=QARQsvf9v0M&src_vid=JUtSiE0jwWQ). I wonder if there are even more than four.
Comment: The word "hell" is faded out in "Song 3" I think and this is likely so that the game meets the criteria for a young audience.
Answer: Foxtrot did a terrific job of transcribing the lyrics for the first three intros, so I'd like to contribute my version of the fourth one:
Voice 1:
Hmm, did you say Monday nitro?
This looks like a great game, do you mind if I give it a sho-

Voice 2:
Shut up, sucka! It's time to begin
Light the hot metal of fire and sin
We're burning and the bikes are flying through the air
Beat my high score and I'll beat you again
That's the tie (?), get ready for the moment you've been
Waiting for and the nitro is burning down your door
Who's there? Knock, knock, pizza party all day.
Friday night quench your thirst and stay
Over for a sleep over. Time trials trials
Everybody is here, now we can't stop.

Also, here are the links to the Youtube videos:
Intro 1,
Intro 2,
Intro 3 (The one in my answer),
Intro 4


Estimate $\sqrt{10}$ with an error smaller than $0.01$

Question: I´m trying to find this using Lagrange Error bound.
$$|R|\leq \frac{f^{n+1}(t) (x-a)^{n+1}}{(n+1)!}$$
Basically I thought of using the function $f(x) = \sqrt{x+1}$ centered on $a= 8$ (but when I was calculating the derivatives I couldn't find a "pattern")
So, I tried using $f(x) = \sqrt{x+1}$, $a= 0$ but in Langrage Error bound I need to work with the $n+1$ derivate and I couldn't find a pattern or how to work with it (I know that $(x-a)^{n+1}$ in this case is equal to $9^{n+1}$ and I have to try with differents "$n$" to know what order I need to work with). I'd appreciate some help to know how to deal with $f^{n+1}(t)$ (with t between $0$ and $9$ in this case). (I tried to find a general Taylor Polynomial but it has double factorial $!!$ and I get confused a little bit)
Comment: If you want to approximate $\sqrt{1+x}$, then it's only useful when $|x|<1.$ So you should first do something like:
$$\sqrt{10} = 4\sqrt{\frac 58} = 4\sqrt{1 - \frac 38}=...$$
There might be better choices other than $4$. Actually, pulling out $3$ will work better I think.
Comment: What did you get for the various derivatives of $\sqrt{x+1}$? It may help to not multiply the coefficients when you bring them down to see the pattern.
Comment: You specifically need just two decimal places, so (1) you actually need to explicitly evaluate each term to get the answer and (2) you'll only need a certain number of terms to bound the error to $0.01$, and then you can stop. Technically you don't need a general formula.
Comment: What are you allowed to use?  I know that $\sqrt {10} \approx 3.162$, so I can just square that and estimate the error to show it is good enough.
Comment: I know that I could try with differents n¨s for $f^{n+1}$ but I don´t think is the right way to do this kind of problem
Comment: Are you looking for a formula or a numerical method?
Comment: Thanks! I see the main Idea, it´s very helpful, I couldnt find how to establish a generic "n+1 derivate" for the polynomial of Taylor
Comment: @copper.hat I was looking for a numerical method but I though that maybe I needed a general formula to work with
Comment: @RossMillikan I'm allowed to use polynomials of Taylor
Answer: Note that $$\sqrt {10}=\sqrt{9+1}=\sqrt{9\left(1+\frac{1}{9}\right)}=3\sqrt{1+\frac{1}{9}}$$
Without using the binomial coefficient, you can express $\sqrt{1+x}$ as follows:
$$\sqrt{1+x}=1+\sum_{k=1}^{+\infty}\frac{(-1)^{k+1}}{k!}\frac{(2k-3)!!}{2^k}x^k $$
Comment: @Jean do you need a simpler solution or this is ok? You can express the formula with the binomial coefficient. Let me know :)
Comment: Thanks! I think that I can use that for what I need in the Langrage Error bound (I can calculate the n+1 derivate, and use x=1/9) and find the n
Comment: I think I understood, but just to be sure. To calculate te error (with Langrage error bound) I have to work with that formula (derivate it) and multiply it by 3?
Comment: @Jean Sure, that's correct :)
Answer: It is not entirely clear what you are looking for.
If you apply Newton's method to $f(x) = x^2-10$ and start from some $x_0 > \sqrt{10}$, say $x_0 = 4$, then the sequence of iterates $x_{n+1} = {1 \over 2} (x_n+{10 \over x_n})$ decreases to the positive solution $x_n \downarrow \sqrt{10}$. The sequence converges quadratically since $f'(\sqrt{10}) \neq 0$.
Here is a crude formula to bound the error in terms of $f$. Note that the iterates satisfy $x_n \in [3,4]$,
Note that for $x \in [3,4]$, we have $f(x) = (x-\sqrt{10})(x+\sqrt{10}) \ge 6(x-\sqrt{10}) $ and so
$x-\sqrt{10} \le {1 \over 6} (x^2-10)$.
Starting with $x_0=4$, we get $x_1-\sqrt{10}\le 0.9375$, $x_2-\sqrt{10} \le 0.0012452...$, with $x_2 =3.163461...$.
(Not that it matters, but $x_3-\sqrt{10} \le 0.00000023351...$.)
Answer: The Taylor formula of order $n$ at point $a$, with Lagrange remainder, for the function  $f(x) = x^N$, ($N$ not necessarily a natural number) is
$$x^N = \sum_{\ell=0}^n \binom{N}{\ell} a^{N-\ell} (x-a)^{\ell} + \binom{N}{n+1} \xi^{N-n-1} (x-a)^{n+1}$$
where $\xi \in [a, x]$. So it looks  like the binomial formula ( we have $\binom{N}{\ell} = \frac{N(N-1) \cdots (N-\ell+1)}{\ell!}$, and the remainder term would look like the next one, except that instead of $x$ we have $\xi$ between $x$ and $x+a$).
Now consider $N=\frac{1}{2}$, $x=10$, $a=9$, $x-a=1$, so we estimate $(10)^{\frac{1}{2}}$. An approximation ( in excess)  with error $< |\binom{\frac{1}{2}}{2} 9^{\frac{1}{2}-2}| < 0.01$ is
$$\sqrt{10} \simeq 9^{\frac{1}{2}} + \frac{1}{2} 9^{\frac{1}{2}-1}\cdot 1 =3+\frac{1}{6}$$


Can AVR or loose speaker wires cause AFCI to trip?

Question: I have a newly constructed ADU and the AFCI breaker for the plug my AV system is in keeps tripping.  We've replaced the breaker twice with no change and checked all the internal wiring.  I had a Denon AVR plugged into the wall which sometimes makes a popping sound when it turns on. I removed the unit and now the AFCI never trips. So I see two possible issues: (1) the Denon AVR itself is arcing or (2) one or more speaker wires was loose and arcing.  Is #2 even possible -- would a loose speaker wire cause an AFCI breaker to trip?  I can't find an answer anywhere online.
Comment: @EdBeal, yeah, that makes sense -- dimmers definitely do put out tons of nasty harmonics.  In fact, a lot of times if you plug a cheap audio amplifier into the same circuit as a dimmer, you can hear those harmonics in the audio output.  That situation comes up a lot at concerts, which was my former career before becoming an EE.  I think our only point of disagreement is whether an audio amplifier can cause significant harmonic distortion on the power input like dimmers do.
Comment: I don't see how speaker wires could cause that.  They're not connected to the AC mains electrical system, and the amplifier better be isolating them fully!
Comment: I agree with Harper here; any properly functioning amplifier will fully isolate the speaker outputs from the power inputs, so speaker wire arcing (which should be hard tbh; the voltage isn't that high) should not be able to trip an AFCI in general.
Comment: @harper an arc on a power supply even low voltage is still a non Linear load it will be reflected through the transformer in high end gear and with switching gear is more directly connected, a pop from things in the unit charging up it looks like a short so the AFCI thinks this is an arc. I have seen it repeated on some equipment after ~3 minutes of being turned off.
Comment: Does the AFCI trip happen immediately when you plug the AVR in, or does it happen some time later?  And if it's later, is it when you're using it, or when it's just sitting there?  And finally, does this plug into a two prong or three prong outlet?
Comment: @EdBeal, you're talking about the power supply section, which I agree could possibly fool an AFCI with inrush current, though it is a little more unusual than with something like a motor.  Harper and I were meaning that the power supply section should be fully isolated from the audio outputs, and the only connection between the two parts should be a DC bus.  AC Transients shouldn't be able to get through a conversion to DC.
Comment: Adding the model number of the AVR, as well as a picture of what all is plugged into it, would also be helpful.
Comment: @nate s anything nonlinear can cause a AFCI to trip light dimmers a classic example there is no short there just a modified sine wave. You have to remember what happens in the secondary of a transformer happens on the primary, we can fuse the primary of the transformer. if there is a short the fuse will blow there is a direct correlation based on the turns ratio. This is where real hands on experience shows. yes the output is isolated but the isolation is from ground unless bonded. A 12v transformer blowing a 10 amp fuse would see a 1 amp primary short also a charging cap looks like a short.
Comment: @EdBeal, I don't think you're quite understanding what I'm saying.  Dimmers put tons of noise onto the AC line because they're drawing from it unevenly -- they switch on and off during different parts of the waveform to achieve the dimming, so their current draw is also turning on and off at 60Hz.  An audio amplifier, by contrast, draws power cleanly and constantly and converts it all into DC, and stores it in a big capacitor.  This DC from the capacitor is chopped up in non-linear ways, but that isn't flowing back through the rectifier.
Comment: @EdBeal Also, not every non-linear power draw is an arc, and AFCI breakers should be able to tell the difference.  Yes, capacitors can look like dead shorts at first, but not everything that has a capacitor will trip AFCIs -- and there's no good reason an amplifier should.
Comment: Thanks so much for the comments. It is a Denon AVR-1913.  Was plugged into a surge protector (in addition to the TV, Blu Ray,  and some video games) and that into a standard grounded outlet.  It sometimes tripped upon being turned on, but more often tripped after the unit had been on for a while. Inconsistently.- maybe 1 in 8 times? But sometimes 2-3 times in a row.  Has been completely unplugged for 2 weeks now and the circuit has not tripped once so am thinking it is the Denon.
Comment: @Nate I do understand, but you have not read the op statement about the popping sound, or have very limited experience with transformer circuits. I never said anything ever flowed back! Anything that happens on the secondary is happening on the primary divided by the turns ratio. Nothing flows back. Power on the primary is equal to power on the secondary is another way of saying it get a basic transformer book and look it up.
Comment: @EdBeal, I'm literally an electrical engineer who has designed audio amplifier circuits in the past; I know how transformers work.  I'm not saying things on the secondary of a transformer don't appear on the primary; I'm saying that when you connect the secondary to a rectifier and filter capacitor, then utilization of that resulting DC bus will not cause any significant transients on the primary, provided you stay within the design limits of the power supply.  And I agree with you that a problem in the power supply, such as a short between transformer windings, could cause this problem.
Comment: @nate then you understand the total harmonic load could in fact be the issue. AFCI circuits usually do fine with a small load but get to 50% of circuit capacity with dimmers and they almost universally fail. Ok we did that test a few years back but for this reason my state exempts AFCI for nuisance circuits (not sure if still in the 2020 as it's not adopted yet so I don't have the modified code) but this could be an example of the total harmonic load confusing the AFCI. And this can come from the popping noise should be immediate trip or when the total of all devices exceeds the threshold.
Comment: @EdBeal, you keep bringing up dimmers, but they're completely different from audio amplifiers like this one, and really aren't putting harmonics on the AC line.  The popping noise is likely the transistors in the audio section settling into their bias points, and has very little to do with the power supply section.  And the OP already said it's not always happening immediately on power-on but rather usually happens later, so I don't think it's about inrush current either.
Comment: Nate S. do you agree I probably need a new AVR?
Comment: @Michael, I just wrote up a detailed answer about it, but tl;dr: yes.
Comment: @nate I bring dimmers up because other than motor loads they are the most common issue with AFCI's and most people understand them I have seen AFCI's fault on 5-7 amp load when heavily dimmed.
Answer: A properly functioning audio/video amplifier should not cause AFCI trips
AFCIs work by monitoring the waveform of the AC power signal and looking for a particular type of distortion that is indicative of an electrical arc, and cutting power if that is seen.  This doesn't play well with every device -- some devices, such as brushed motors, have small electric arcs inside as part of their normal usage, and others such as dimmers, consume power in such a weird and inconsistent way that they can fool the detector.
However, none of these concerns apply to typical audio/video systems like you have.  In fact, audio amplifiers have quite a lot of filtering in the power supply section, to make sure that noisy incoming power won't be heard in the speaker output.  This same filtering means that the way audio amplifiers draw power is also very clean, and won't make any unusual noise on the AC line.  The video section of the unit is all digital electronics, and isn't any more likely to trip an AFCI than a regular computer.
Most likely, something is wrong with your AVR unit
The fact that the trip sometimes happens right away, and sometimes happens after a while makes me think it's likely your AVR does indeed have an intermittent fault internally.  My guess would be an insulation breakdown in the transformer somewhere.  Since devices this complex sometimes have several transformer windings for independent power supply rails, such a fault might not even cause the amplifier to stop functioning completely, but it is a real problem that the AFCI might detect.
Double check your grounding
This is a little more esoteric and less likely to be your problem, but for completeness I'll include it as well.  While most electrical equipment uses the ground wire only for safety purposes, audio equipment frequently also uses it for shielding of audio signals.  Often, the shells of all the HDMI and RCA plugs on the back are connected directly to the earth ground coming from the wall plug.  This then gives lots of opportunities for unusual signals to couple to the ground wire.
How does this affect AFCI?  If everything is wired correctly, it doesn't at all -- the AFCI doesn't look at the ground wire.  But if your outlet was wired with a bootleg ground, i.e. where the ground terminal is also connected to the neutral wire, then the AFCI will be able to see that ground noise, and it could interpret it as an arc.
Comment: Thank you!  The ground is definitely properly wired so I'll start looking for a new AVR.
Answer: The popping noise you hear on start up was probably the surge charging the electronics up and that confused the AFCI.
AFCI's monitor the load and a non Linear current draw the pop on startup could be the issue.
I have seen this in audio gear plugged into different circuits the first piece of equipment cross connected to the mixer tripped the circuit, leave things plugged in and reset the breaker and everything is fine I told them an arc is an arc they wanted the protection in there studio and because of the nuance tripping with that and some of the sound effects generators causing trips they had me go to GFCI receptacles at each outlet and no AFCI and that solved there problems and they felt safe.
Comment: Is that going to be all AVRs or is this older one just a problem then?  Denon AVR-1913.
Comment: Michael with the popping noise when turned on it could be completely disconnected from power thus when turned on it could be the issue. The intermittent issue after start up could be that with the multiple loads having different types of power supplies could cause the problem when something like a heavy audio or white screen there can be different reasons, I might try plugging it in with an extension cord to a different circuit to see if it's the total load and this is pushing it over the limit, if the extension cord works then swap the AVR and something else to prove, avr or total load issue.
Comment: Ed, thanks. I'm pretty sure there is no total load issue because there is almost nothing on the Circuit: LED TV, a BluRay player, a Nintendo Wii, an ethernet switch, and a Eero access point (plus the AVR which is now not in use). The electrician measured the load at the AFCI (not an engineer so I may have that terminology wrong) and said we are way under the limit.  He also thought it was the Denon AVR.  The Circuit is just for the plugs in that room (no lights or dimmers) and none of the other plugs have anything in them.
Comment: Sounds like maybe I just need a new AVR unit.
Comment: Michael maybe you do but do the extension cord test 6 different power supplies who knows.
Comment: Thanks to everyone for the very thorough and helpful responses!


CUPS moved to snap recently?

Question: I'm running Ubuntu 20.04. I just noticed after issuing snap list command that my list of installed snaps includes cups, version 2.4.2-4. Directory /snap/cups was updated a few days ago:
drwxr-xr-x 11 root root 159 Oct 22 07:21 836
lrwxrwxrwx  1 root root   3 Nov  1 19:38 current -> 836

This snap wasn't previously there last time I checked. I don't remember installing it manually. Synaptic Package Manager still shows cups-* DEB packages installed on my system in version 2.3.1-9ubuntu1.2 (cups-daemon, cups-common, cups-core-drivers etc.)
Both DEB and snap packages seem to be running on my system, if I read the output of ps correctly:
root         919       1  0 20:34 ?        00:00:00 /usr/sbin/cupsd -l
root         928       1  0 20:34 ?        00:00:00 /usr/sbin/cups-browsed
root         936       1  0 20:34 ?        00:00:00 /bin/sh /snap/cups/836/scripts/run-cups-browsed
root         938       1  0 20:34 ?        00:00:00 /bin/sh /snap/cups/836/scripts/run-cupsd
root        1223     938  0 20:34 ?        00:00:00 cupsd -f -s /var/snap/cups/common/etc/cups/cups-files.conf -c /var/snap/cups/common/etc/cups/cupsd.conf
root        1311     936  0 20:34 ?        00:00:00 /bin/sh /snap/cups/836/scripts/run-cups-browsed

Has Canonical recently replaced CUPS DEB version with snap version in Ubuntu 20.04 without telling anyone? If yes, why both are running? If no, what might have installed the snap version and what is it used for?
If this is of any help, here's the full output of my snap list:
Name               Version                     Rev    Tracking         Publisher      Notes
bare               1.0                         5      latest/stable    canonical✓     base
caprine            2.56.1                      52     latest/stable    sindresorhus   -
chromium           107.0.5304.87               2168   latest/stable    canonical✓     -
core               16-2.57.2                   13886  latest/stable    canonical✓     core
core18             20221027                    2620   latest/stable    canonical✓     base
core20             20220919                    1634   latest/stable    canonical✓     base
cups               2.4.2-4                     836    latest/stable    openprinting✓  -
gnome-3-28-1804    3.28.0-19-g98f9e67.98f9e67  161    latest/stable    canonical✓     -
gnome-3-34-1804    0+git.3556cb3               77     latest/stable/…  canonical✓     -
gnome-3-38-2004    0+git.6f39565               119    latest/stable    canonical✓     -
gtk-common-themes  0.1-81-g442e511             1535   latest/stable/…  canonical✓     -
overlay            0.2                         10     latest/stable    kyrofa         -
snap-store         41.3-64-g512c0ff            599    latest/stable    canonical✓     -
snapd              2.57.4                      17336  latest/stable    canonical✓     snapd
syzygy             v1.0.1                      2      latest/stable    popey          -

Update: There was an answer to this question (now non-existent) that told me to remove the CUPS snap - it should apparently be not possible if other snap depends on it. However, I was able to remove it without any problem. I checked snap list and it wasn't there. Today I got a notification that it wants to update (see screenshot below), so I did snap list again and it is there.
I checked journalctl -ru snapd as indicated in the (now non-existent) answer and it turns out that after I removed the snap on November 9th, it got somehow installed again on November 12th. The log shows:
Nov 12 22:01:20 jarek-02 snapd[786]: snap has no updates available: "bare", "caprine", "chromium", "core", "core18", "core20", "cups", "gnome-3-28-1804", "gnome-3-34-1804", "gnome-3-38-2004", "gtk-common-themes", "overlay", "snap-store", "snapd"
Nov 12 22:01:20 jarek-02 snapd[786]: storehelpers.go:748: cannot refresh:
Nov 12 16:49:20 jarek-02 snapd[786]: storehelpers.go:748: cannot refresh snap "chromium": snap has no updates available
Nov 12 16:48:58 jarek-02 snapd[786]: autorefresh.go:540: auto-refresh: all snaps are up-to-date
Nov 12 16:48:58 jarek-02 snapd[786]: snapstate.go:1591: cannot refresh snap "chromium": snap "chromium" has "refresh-snap" change in progress
Nov 12 16:48:58 jarek-02 snapd[786]: snap not found: "syzygy"
Nov 12 16:48:58 jarek-02 snapd[786]: snap has no updates available: "bare", "caprine", "core", "core18", "core20", "gnome-3-28-1804", "gnome-3-34-1804", "gnome-3-38-2004", "gtk-common-themes", "overlay", "snap-store", "snapd"

So If I read it correctly, on Nov 12, 16:48, the CUPS snap wasn't there (it is not listed in "snap has no updates available" message and the same set of snaps is listed in previous occurrences of that message), and on the next check, on Nov 12, 22:01, it was already there. Between these two, the Chromium snap was updated. So is it possible that the CUPS snap is automatically installed with Chromium?
Comment: You can use the commands in [this answer](https://askubuntu.com/a/1236201/590937) to find out which snap is pulling the cups snap in.
Comment: @PiotrHenrykDabrowski I need Chromium, and this is available only as snap, so removing snapd is not possible.
Comment: @mook765 Yep, looks it's Chromium. Thanks for the link! I posted this as an answer.
Comment: `sudo apt-get purge snapd`
Comment: @raj It is possible to install Chromium .deb from Mint repositories. Or use my repo to do the same: https://freeshell.de/phd/chromium/
Answer: Looks like it's in fact Chromium pulling in the CUPS snap. I followed the answer linked in the comment and got the following output:
raj@jarek-02:~$ grep "cups:" /snap/*/*/meta/snap.yaml
/snap/chromium/2238/meta/snap.yaml:  foo-install-cups:
/snap/chromium/2254/meta/snap.yaml:  foo-install-cups:
/snap/chromium/current/meta/snap.yaml:  foo-install-cups:
/snap/cups/836/meta/snap.yaml:  etc-cups:
/snap/cups/836/meta/snap.yaml:  cups:
/snap/cups/872/meta/snap.yaml:  etc-cups:
/snap/cups/872/meta/snap.yaml:  cups:
/snap/cups/current/meta/snap.yaml:  etc-cups:
/snap/cups/current/meta/snap.yaml:  cups:

The *.yaml files for Chromium snap contain foo-install-cups, so it looks like it's actually installation/update of Chromium snap that pulls in the CUPS one.
Comment: +1 Great detective work.

CUPS moved to snap recently?


SQL query having an issue

Question: Hi there I'm having an issue with an SQL query, it works but I don't know if it's right (I'm learning to code)..
I've written this statement..
SELECT CONCAT(Member_Name, ' ', last_name) AS full_name FROM members ORDER BY last_name DESC, Member_Name DESC

It's displaying this:

Is this right? Thanks!
Answer: Too long for a comment.
Your query looks right.  Just ignore "Tony House" and the results look correct too ;)  Sometimes, situations like this arise because the data isn't what you think it is.  I would suggest that you run the query with the basic data in other columns so you can see what is happening:
SELECT CONCAT(Member_Name, ' ', last_name) AS full_name, Member_Name, last_name
FROM members
ORDER BY last_name DESC, Member_Name DESC;

You are likely to find an anomaly in the data.  For instance, "Tony House" might be in the Member_Name field and the last_name field is blank.  Or, there might be an extra space or unprintable character in the last_name field.
Comment: Or maybe that the surname is `' House'` (looking at the output, it appears to me as though there is more than a single space between `'Tony'` and `'House'`).
Answer: Your query is absolutely correct. You need the data order by lastname, so however you may structure the query it will be same output.

SQL query having an issue


Generating a JWT token using AuthenticateAsync

Question: I am trying to login using ClaimsPrincipal and then fetch a JWT in .net core 2.0. With my current code, I get the error from the result of the SignInAsync function:
"No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Bearer"
Here is the controller I am currently using:
[Route("Login/{username}")]
public async Task<IActionResult> Login(string username)
{
    var userClaims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, username)
    };
    var principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
    var sign = HttpContext.SignInAsync(principal);
    await sign;
    var res = await HttpContext.AuthenticateAsync();
    var token = await HttpContext.GetTokenAsync("access_token");
    return Json(token);
}

The login portion was tested and works well with cookies. However when I use the following code with JwtBearerDefaults.AuthenticationScheme in my startup.cs:
services.AddAuthentication(config => {
    config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(config =>
{
    config.TokenValidationParameters = Token.tokenValidationParameters;
    config.RequireHttpsMetadata = false;
    config.SaveToken = true;
});

I get the error from the result of the SignInAsync function:
"No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Bearer"
My Token class was created with the help of a code I found online (at JWT on .NET Core 2.0) and is defined as follows:
public static class Token
{

    public static TokenValidationParameters tokenValidationParameters {
        get
        {

            return new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = GetSignInKey(),
                ValidateIssuer = true,
                ValidIssuer = GetIssuer(),
                ValidateAudience = true,
                ValidAudience = GetAudience(),
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };
        }
    }

    static private SymmetricSecurityKey GetSignInKey()
    {
        const string secretKey = "very_long_very_secret_secret";
        var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

        return signingKey;
    }

    static private string GetIssuer()
    {
        return "issuer";
    }

    static private string GetAudience()
    {
        return "audience";
    }

}

Answer: If I understand it correctly from looking at the source code for JwtBearerHandler, it does not implement IAuthenticationSignInHandler, which is why you are getting this error. Call to SignInAsync is designed to persist authentication information, such as created auth cookie which, for instance, is exactly what CookieAuthenticationHandler does. But for JWT there is no single well-known place to store the token, hence no reason to call SignInAsync at all. Instead of that, grab the token and pass it back to the browser. Assuming you are redirecting, you can tuck it into a query string. Assuming browser application is an SPA (i.e. Angular-based) and you need tokens for AJAX calls, you should store token in the SPA and send it with every API request. There are some good tutorials on how to use JWT with SPAs of different types, such as this: https://medium.com/beautiful-angular/angular-2-and-jwt-authentication-d30c21a2f24f
Keep in mind that JwtBearerHandler expects to find Authentication header with Bearer  in it, so if your AJAX calls are placing token in query string, you will need to supply JwtBearerEvents.OnMessageReceived implementation that will take token from query string and put it in the header.
Comment: User enters name/password into your client, they are passed to the server and validated. If everything checks out, token (in JWT format, and it's signed by the server, so server will be able to validate it later) is generated and sent back. Client stores token and uses it in further API calls. That's the flow.

It looks like in your Login action you are already generating JTW. That's perfect, because now all you need to do is return it. You can attach it to query string if you are doing redirect, or you can put it in response header, or as JSON if login was on AJAX.
Comment: what is the need to sent the token from the client and pass it back? do you know how to implement the IAuthenticationSignInHandler?
Comment: Token is only passed back from the server to the client once, immediately after login. Token contains signed user identity. Server is stateless, hence browser client must send token to the server with each API call, which means that your AJAX call should include Authentication header containing Bearer  notation.
Comment: In any case, it is my opinion that you do not need to implement IAuthenticationSignInHandler for this at all.
Comment: I was aware of how the flow works. I have worked with token in the client several times. In fact I was mainly looking for a way to generate the token in the server. The way above was not really working. I still have no idea what the `HttpContext.GetTokenAsync` actually does.
Comment: Token generation I use is close to what you have marked as correct answer. Except for I create token a bit differently:

`var token = new JwtSecurityToken(
                                        issuer: Options.Issuer,
                                        audience: Options.ValidAudience,
                                        claims: claims,
                                        expires: DateTime.UtcNow.AddMinutes(10),`
Comment: `                                        signingCredentials: new SigningCredentials(
                                            new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Options.IssuerSigningKey)),
                                            SecurityAlgorithms.HmacSha256)
                                        );

var tokenString = new JwtSecurityTokenHandler().WriteToken(token);`
Comment: Not sure you need to worry about GetTokenAsync at all. You are generating new token and returning it, so you are done. No need for SignInAsync either.

If you call
`services.AddAuthentication(options =>
{
  //set options here
 }).AddJwtBearer(options => {
{
  //more options for Bearer auth here
}`

Then token will be retrieved from Authentication header and claims identity created for you.
Answer: A signed token can be created using the JwtSecurityTokenHandler.
var handler = new JwtSecurityTokenHandler();
var jwt = handler.CreateJwtSecurityToken(new SecurityTokenDescriptor
{
     Expires = DateTime.UtcNow.Add(Expiary),
     Subject = new ClaimsIdentity(claims, "local"),
     SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256)
});
return handler.WriteToken(jwt);

Comment: How to use this with `SignInManager`'s `AuthenticateAsync` or `SignInAsync`?


Uniformity and overview

Question: I have a system to register attendance, displayed on a screen on the premises. First the user chooses his/her class, and then his/her name, which results in an "attendance registered" screen, which closes after 5 seconds, if no other input is given.
The class detail screen is agrid with three columns, with a "button" with the student's name in the center.
My issue is that some people with long names require very wide buttons. My interim solution is to display a "button" wide enough to display the longest names. This gives me a couple of issues:

There is not very much space left over. Since the buttons are the same length and colour, in big classes (~35 students) the overview is lost, and the kids who are slow readers, and the older grown-ups have trouble finding their name in time.
There is not enough screen real-estate left for displaying a starting letter or group (e.g. A, B, C or A-C, D-F, etc.)

How can I reduce the size of the buttons, without losing the uniquenes of the name? I considered replacing middle names with initials, but I am worried that for some names the uniqueness will disappear.
Any suggestions are much appreciated
EDIT: This is my current layout.

I forgot to mention that I have some restrictions. This is running in a Chrome browser in Kiosk Mode, and gestures do not work, which means that scrolling/gestures are out of the question. I am trying to fix that issue, but given my timeframe, it is not viable to wait for that.
Comment: do you have a mock to show your efforts so far? I will be more helpful to have something to show your efforts and constraints.
Comment: @MikeM i added some dummy data to my test system and took a screengrab. i also updated with som of my constraints.
Answer: Could you use just first name and initial?
Could you widen the button to span the three columns?
From the way you describe it, it seems like the student is choosing their name from a list of all names in the class. Couldn't this be just that - a list instead of a grid?
Comment: Hi Natalie. thank you for your suggestion. I have updated my question with  the reason for not attempting a bare list. the other reason is that with two classes comming in within the same 15-20 minutes, having to scroll through a list is not ideal. as long as the number of students registered is not varying too much, then the students will find their positions fairly quickly, or at least they do in the current setup.
Answer: Users need to orient themselves on the screen without having to read individual names.
Ordering names alphabetically in columns, rather than rows, would allow the user to get to the right area more quickly. In rows, eyes have to go back and forth 11 times across the width of the screen, in columns, they need only 2 back and forth across the height.
Considering you can't include headers for letters or group of letters, I would emphasize the first letter of each name visually (last name if alphabetical order is based on last name). If the letter stand out enough, the user can find their way through the screen without having to read each name.
Answer: When screen space is limited and shared, nobody's extra long name should abuse this common resource. Therefore let it be, say, first name and last name and possibly some middle, or its initials. For groups of up to 35 probability of name collision is very small. In this case a student should be able to choose their screen name.
So, keep students' screen names in separate field and edit them when needed. And by default generate them from full names according to some algorithm.
Shorter versions of names may also increase readability.

Uniformity and overview


Is my space a good candidate for a hybrid electric heat pump water heater?

Question: We're purchasing a condo, and the current water heater is almost 10 years old. I don't know that it needs replaced (I'll be researching replacing the anode next), but if it does, I'd like something more efficient.  I think I'm sold on hybrid. They don't seem like much work, and I definitely want to have something more efficient.
I've attached a photo of the room where the water heater is located. My only concern is the condensate line required for hybrid tanks. Could I tie it in at the clothes washer drain?
Comment: Is this room heated space? your hybrid water heater will be pulling heat from the room it is in, so if this room is inside your condo it won't be as efficient as you might think. If your condo is heated with a heat pump, it could still be worthwhile even if it's inside.
Comment: If you're using electric resistance heat to heat the space, part of the year the heat pump water heater will be no more efficient than a regular water heater, and it's noisier and more expensive. I'd skip it unless you're really interested in the dehumidifying effect you get for free with these units.
Comment: Warm air is fine. The problem is that during heating season, this unit is going to be pulling heat from the room that was put in there by your normal heating system. So if you live somewhere like Florida where you're using A/C most of the year, a heat pump water heater will be great. If you're in North Dakota, you're going to be just effectively doing a very roundabout version of heating the water with whatever fuel your regular heat system uses.
Comment: Depending on the quality of that heater, it should be middle aged.  Your use of hot water will be the the deciding factor if changing to a different type of heater is worth it, cost plus/minus savings.
Comment: @KMJ - This room is inside the unit and heated. Is cooler air better?
Comment: @KMJ - I see, thank you for that explanation. It's baseboard heating, which we're considering replacing with in-wall heaters in the future. Perhaps we'd add a standalone unit with its own thermostat at that point as well. Also, we're in a pretty mild climate (Seattle area), so winters aren't all that cold most of the season. Below freezing only for a few weeks, except at nights.
Comment: A hybrid will be a lot taller than your current heater, so it may need to be installed further from the wall that has the plumbing/wiring, shifting your side table out of the way.
Comment: Also, where does the piping from the overpressure/overtemp release valve on top go? Into the wall and outside somehow? There are code rules for that, so replacing the wh may involve plumbing mods.  Are you wanting to do this yourself, or hire a plumber?
Answer: Condos can have challenges and surprises.
If you are on the second floor or higher, there may be a drain built into the pan that isn't evident until the tank is removed. If you don't have that drain, perhaps you can tie into the AC drain.  I will let the plumbing experts answer on tying into the washer drain.  In my local it isn't allowed.
The other issue is the electrical needs.  Be sure you can get the power to the unit you want without a great expense.
Comment: A hybrid will be just fine electrical needs wise since there's an electric heater here already. They usually use exactly the same size circuits (due to the backup heating element, which you can disable in software if you don't want it coming on) and draw much less when in heat pump mode.
Comment: Thanks for the explanation,  I am not familiar with the electrical needs of Hybrids.


Virtualbox "system is not currently set up to build kernel modules"

Question: I'm trying to install Virtualbox on my Ubuntu 16.04.
When I try to open it, it gives me an error that tells me to run sudo /sbin/vboxconfig.
Running this command results in the following output:
vboxdrv.sh: Building VirtualBox kernel modules.
     This system is not currently set up to build kernel modules (system                  extensions).
     Running the following commands should set the system up correctly:

  apt-get install linux-headers-4.2.0-35-generic
(The last command may fail if your system is not fully updated.)
  apt-get install linux-headers-generic
vboxdrv.sh: failed: Look at /var/log/vbox-install.log to find out what went wrong.
This system is not currently set up to build kernel modules (system extensions).
Running the following commands should set the system up correctly:

  apt-get install linux-headers-4.2.0-35-generic
(The last command may fail if your system is not fully updated.)
  apt-get install linux-headers-generic

There were problems setting up VirtualBox.  To re-start the set-up process, run
  /sbin/vboxconfig
as root.

The suggested steps don't work on my machine. It says that the package is obsolete. The only available header packages are 4.4.0 packages.
Running uname -r gives me version 4.2.0 though.
Any ideas how to fix this?
Output of cat /etc/lsb-release:
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.1 LTS"

Output of sudo apt install linux-generic:
Reading package lists... Done
Building dependency tree
Reading state information... Done
linux-generic is already the newest version (126.96.36.199.38).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

Output of cat /etc/default/grub:
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT="                                                               Windows 10"
#GRUB_HIDDEN_TIMEOUT="0"
GRUB_HIDDEN_TIMEOUT_QUIET="true"
GRUB_TIMEOUT="5"
GRUB_DISTRIBUTOR="`lsb_release -i -s 2> /dev/null || echo Debian`"
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL="console"

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE="640x480"

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID="true"

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

export GRUB_COLOR_NORMAL="green/black"
export GRUB_COLOR_HIGHLIGHT="light-green/black"
export GRUB_MENU_PICTURE="/home/user/grub/maxresdefault.jpg"
GRUB_SAVEDEFAULT="false"

Comment: Please run `sudo apt install linux-generic` and post the output.
Comment: You probably used some grub customizer or something that fixes the kernel to boot.
Comment: Please post the output of `cat /etc/default/grub`.
Comment: When I first installed VirtualBox on my workstation (running 14.04 with a 4.2 kernel), I had to add package **dkms** to support the building of 'dynamic kernel modules' used by VirtualBox.  You will also need the kernel headers package for your current kernel.

The kernel your machine says its running is from wily, not xenial.  Did you do an in-place upgrade with the kernel packages pinned?  Have you rebooted since you upgraded?
Comment: Yes, I've done an in-place update, but I'm not sure about the kernel. I have rebooted since then.
Answer: You have a spoiled /etc/default/grub file.
Fix the line
GRUB_DEFAULT="                                                               Windows 10"

to
GRUB_DEFAULT=0

Then remove
GRUB_SAVEDEFAULT="false"

and run
sudo update-grub

Then reboot.
Comment: Thanks for the answer, but that didn't do anything. After the reboot, the output of uname -r is still 4.2.0. :-/
Comment: This means you do not have Ubuntu 16.04.
Comment: What does `cat /etc/lsb-release` show?
Comment: Fixing the grub file didn't help either but I noticed that there were 4.4.0 kernels listed during the `update-grub` process.
Comment: Did you remove `GRUB_SAVEDEFAULT="false"`? You can always boot with kernel 4.4 using grub menu. that will fix the problem. You will need to fix your broken grub anyway.
Comment: And you can always remove kernel 4.2 that is should not be used in 16.04.
Comment: Removing the suggested lines didn't really help. I was able to boot into kernel 4.4 using grub menu and the original problem was fixed that way. I'll see what I can do about that broken grub and the old kernel. Thanks for your help, it's much appreciated.