Why is there unreachable code here?

Question: I am writing a c# app and want to output error messages to either the console or a messagebox (Depending on the app type: enum AppTypeChoice { Console, Windows } ), and also control wether the app keeps running or not ( bool StopOnError ).
I came up with this method that will check all the criteria, but I'm getting an "unreachable code detected" warning. I can't see why!
Here is the whole method (Brace yourselves for some hobbyist code!)

    public void OutputError(string message)
    {
        string standardMessage = "Something went WRONG!. [ But I'm not telling you what! ]";
        string defaultMsgBoxTitle = "Aaaaarrrggggggggggg!!!!!";
        string dosBoxOutput = "\n\n*** " + defaultMsgBoxTitle + " *** \n\n Message was: '" + message + "'\n\n";
        AppTypeChoice appType = DataDefs.AppType;
        DebugLevelChoice level = DataDefs.DebugLevel;

        // Decide how much info we should give out here...
        if (level != DebugLevelChoice.None)
        {
            // Give some info....
            if (appType == AppTypeChoice.Windows)
                MessageBox.Show(message, defaultMsgBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                Console.WriteLine(dosBoxOutput);
        }
        else
        {
            // Be very secretive...
            if (appType == AppTypeChoice.Windows)
                MessageBox.Show(standardMessage, defaultMsgBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                Console.WriteLine(standardMessage);
        }

        // Decide if app falls over or not..
        if (DataDefs.StopOnError == true)
            Environment.Exit(0); // UNREACHABLE CODE HERE
    }

Also, while I have your attention, to get the app type, I'm just using a constant at the top of the file (ie. AppTypeChoice.Console in a Console app etc) - is there a better way of doing this (i mean finding out in code if it is a DOS or Windows app)?
Also, I noticed that I can use a messagebox with a fully-qualified path in a Console app...How bad is is to do that ( I mean, will I get tarred and feathered when other developers see it?!)
Thanks for your help
Comment: By the way, there's no point in writing `if (something == true)`.  You can simply write `if (something)`.
Answer: DataDefs.StopOnError is a compile-time constant equal to false.
Therefore, the compiler replaces it with false (Or whatever you set it to) near the begining of the compiliation process.
Therefore, your code compiles to:
if (false == true)
    Environment.Exit(0); // UNREACHABLE CODE HERE

This is obviously unreachable.
The simplest solution is to make the DataDefs.StopOnError field readonly instead of const.
The compiler will only give this warning if all of the values involved are compile-time constants or literals, so using any other type of field for DataDefs.StopOnError will stop the warning.
Comment: Ah...So when does it become the value I want it to be?
or how do I make it the value I ant it to be?
Answer: If the value of DataDefs.StopOnError is false, then the body of the "if" will be unreachable.  Check to see if that's the default.
Comment: Yes, but only if it's `const`.
Answer: Look specifically at this code...
DebugLevelChoice level = DataDefs.DebugLevel;

        // Decide how much info we should give out here...
        if (level != DebugLevelChoice.None)

The code above will be unreachable because you set level to always be DebugLevel so it'll never be None.  It'd help us further if you could tell us more about what the error says, for example, what lines its on or which code is unreachable.
Comment: Wrong.  Since it's not `const`, that will not give an error.  (I checked)
Comment: -1. How would the compiler know whether DataDefs.DebugLevel can ever be None or not? Also, the unreachable code is not inside that if statement at all.
Comment: @Joren: It doesn't, and that's not where the error is.  This answer is wrong.
Comment: Ok, the Debuglevel is a const in the DataDefs class, set to

public const DebugLevelChoice DebugLevel = DebugLevelChoice.All; // ie. show ALL output
Comment: Yes, but the `level` variable is not `const`.
Answer: The fact that you're using a constant in a conditional statement is exactly why you're seeing this message. The compiler's telling you that the one of the paths in that statement can never be executed as this would often indicate a logic problem.
So, if as you say you define appType as a constant (AppTypeChoice.Console) then the first clause in this block will never be executed:
// Give some info....
if (appType == AppTypeChoice.Windows)
    MessageBox.Show(message, defaultMsgBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
else
    Console.WriteLine(dosBoxOutput);

Comment: yeah, I see it now - I want to set that for each program (Console or Windows), and NOT have it as a constant.
Duh! I DO NOT BELIEVE that I missed that!

Thanks, guys
Comment: Thanks to you all for your help - I've just gleaned a little more C# knowledge!
Answer: Regarding the message box, it is not a good idea to use a message box for reporting data from the command line.  When a message box pops up, it will prevent the command line program from finishing execution until the user interacts with it.  This can lead to problems when some other program invokes your program and no one is around to click OK.  It is better to use the console for error output; other developers will thank you for saving them from having to hack around the message box.

Why is there unreachable code here?


EF Initializer with multiple contexts for one database

Question: I have an existing application with a SQL database that has been coded using a database first model (I create an EDMX file every time I have schema changes).
Some additional development (windows services which support the original application) has been done which uses EF POCO/DbContext as the data layer instead of an EF EDMX file.  No initializer settings were ever configured in the DbContexts, but they never modified the database as the DbSet objects always matched the tables.
Now, I've written a seperate application that uses the existing database but only its own, new tables, which it creates itself using EFs initializer.  I had thought this would be a great time to use EF Code First to handle managing these new tables.  Everything worked fine the first time I ran the application, but now I am getting this error from some of my original EF POCO DbContexts (which never used an initializer).

The model backing the 'ServerContext' context has changed since the
  database was created. Consider using Code First Migrations to update
  the database

After some investigation, I've discovered that EF compares a hash of its schema with some stored hash in the sql server somewhere.  This value doesn't exist until a context has actually used an initializer on the database (in my case, not until the most recent application added its tables).
Now, my other DbContexts throw an error as they read the now existing hash value and it doesn't match its own.  The EF connection using the EDMX doesn't have any errors.
It seems that the solution would be to put this line in protected override void OnModelCreating(DbModelBuilder modelBuilder) in all the DbContexts experiencing the issue
Database.SetInitializer<NameOfThisContext>(null);

But what if later on I wanted to write another application and have it create its own tables again using EF Code first, now I will never be able to reconcile the hash between this theoretical even newer context and the one that is causing the issue right now.
Is there a way to clear the hash that EF stores in the database?  Is EF smart enough to only alter tables that exist as a DbSet in the current context?  Any insights appreciated.
Answer: Yes, Bounded DB contexts is actually good practice.
eg a base context class, to use common connection to DB, each sub class, uses the
Database.SetInitializer(null); as you suggest.
Then go ahead and have 1 large context that has the "view of the DB" and this context  is responsible for all migrations and ONLY that context shoudl do that.  A single source of truth.
Having multiple contexts responsible for the DB migration is a nightmare I dont think you will solve.
Messing with the system entries created by code first migrations can only end in tears.
Exactly the topic you describe I saw in A julie Lerman video.
Her suggested solution was a single "Migration" context and then use many Bounded DB contexts.
In case you have a pluralsight account:
http://pluralsight.com/training/players/PsodPlayer?author=julie-lerman&name=efarchitecture-m2-boundedcontext&mode=live&clip=11&course=efarchitecture
Comment: Great idea, I'll definitely make use of this.  Unfortunately I think it may not apply to this specific situation in that there is no shared code between these applications, so no place to have one large context.
Comment: Hi Mal, the single Context is for DB migration control only. The individual apps use a smaller context without initializer.  no need to share code. Anyway, you get the point... good luck
Answer: What EF version are you using? EF Code First used to store hash of the SSDL in the EdmMetadata table. Then in .NET Framework 4.3 thingh changed a little bit and the EdmMetadata table was replaced by __MigrationsHistory table (see this blog post for more details). But it appears to me that what you are really looking after is multi-tenant migrations where you can have multiple context using the same database. This feature has been introduced in EF6 - (currently Aplpha2 version is publicly available) Also, note that EdmMetadata/__MigrationHistory tables are specific to CodeFirst. If you are using the designer (Model First/Database First) no additional information is stored in the database and the EF model is not checked whether it matches the database. This can lead to hard to debug bugs and/or data corruption.
Comment: I am currently using 4.4, as it is a .Net 4, not 4.5 project.
Comment: In this case you should have __MigrationHistory table. EF6 does not depend as much on the components in .NET Framework as EF5 did and you should get the same functionality (less async) on both - .NET Framework 4 and .NET Framework 4.5 - including multitenant migrations.
Comment: EF6 depends on the .NET Framework. I have not tried but since .NET Framework 4 is supported on Windows XP EF6 should work as well.


What does "require" of directive definition object take?

Question:
require - Require another controller be passed into current directive
linking function. The require takes a name of the directive controller
to pass in. If no such controller can be found an error is raised. The name can be prefixed with:

? - Don't raise an error. This makes the require dependency optional.
^ - Look for the controller on parent elements as well.

Above is the definition from the official docs. The ambiguity here is what exactly is a "directive controller".
Take the tabs directive from the angularjs-ui bootstrap project, as an example.
angular.module('ui.bootstrap.tabs', [])
.controller('TabsController', ['$scope', '$element', function($scope, $element) {
  ... // omitted for simplicity
}])
.directive('tabs', function() {
  return {
    restrict: 'EA',
    transclude: true,
    scope: {},
    controller: 'TabsController',
    templateUrl: 'template/tabs/tabs.html',
    replace: true
  };
})
.directive('pane', ['$parse', function($parse) {
  return {
    require: '^tabs',
    restrict: 'EA',
    transclude: true,
    scope:{
      heading:'@'
    },
    link: function(scope, element, attrs, tabsCtrl) {
      ... // omitted for simplicity
    },
    templateUrl: 'template/tabs/pane.html',
    replace: true
  };
}]);

The pane directive has require: '^tabs', in which tabs is the name of a directive on its parent element, while the name of the controller attached to that directive is TabsController. From my own interpretation of the above definition, it should have been require: '^TabsController' not require: '^tabs' and that's obviously wrong. Please tell me what am I missing in my comprehension.
Comment: The documentation of Angular is the worst thing about the whole angular project. Its a shame.
Comment: If you use ^^ instead of ^, then it only checks the parent elements, skipping the current element.
Comment: I agree the documentation is confusing. But since it's impossible (unless you read the code) to know the name of the controller function--that's an implementation specific detail (can be an anonymous function)--perhaps they thought it was implicitly clear that it's the name of the directive.
Comment: Another thing that is not mentioned even here is that the elements of those directives must be in ancestor-descendat relationship. Am I right on this?
Comment: @user271996 - Here is an excerpt from the official docs on [Directives](http://docs.angularjs.org/guide/directive). _"^ - Look for the controller on parent elements as well."_ So, the Angular syntax implies they "can" be in parent-child relationship, but not mandatory. Theoretically speaking, you can do something like `` and that wouldn't violate the definition of the `require` attribute (`require: '^tabs'`). But you wouldn't want to do that because that simply wouldn't function as it was designed.
Answer: The require parameter, including its prefixes, is documented on the $compile API reference page.

Require another directive and inject its controller as the fourth argument to the linking function. The require takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the injected argument will be an array in corresponding order. If no such directive can be found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:

(no prefix) - Locate the required controller on the current element. Throw an error if not found.
? - Attempt to locate the required controller or pass null to the link fn if not found.
^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
?^ - Attempt to locate the required controller by searching the element and its parents or pass
null to the link fn if not found.
?^^ - Attempt to locate the required controller by searching the element's parents, or pass
null to the link fn if not found.
Comment: @URL87 In the current implementation, order does not matter.
Comment: @BenWilde : Does `?^` make the same as `^?` ?  Does there is order significance for these prefixes ?
Comment: Additionally (per docs), you can require multiple by passing an array, and they will come into the link function (4th param) as an array as well.
Comment: Note: My tests seem to indicate that multiple nestings using require will bring back the highest level parent's controller, rather than the immediate parent's controller. Which makes it useless for controlling big families because the grandson will always mistake his grandfather for his father.
Answer: This particular topic of the documentation is indeed confusing, however as strange as it seems to be it all makes sense.
The key to understand the logic behind this definition is to understand that "directive controller" refers to a directive's controller instance and not a controller factory.
Following the tabs example, when a tabs element is created, a new instance of the TabsController is also created and attached to that specific element data, something like:
tabElement.data('$tabsController', tabsControllerInstance)

The require: '^tabs' on the pane element is basically a request for that specific controller instance (tabsControllerInstance) being used on the parent tabs element.
Comment: Thx bmleite. How did you manage to find out the details on this topic? Did you have other learning resources other than the official docs?


transforming photo.uri to base64 file

Question: I am unable to transform an image to a base64 string, how would I do this? I tried filereader, canvas, etc. Please help.
  async snap() {
if (this.camera) {
  let photo = await this.camera.takePictureAsync();

  app.models.predict(Clarifai.GENERAL_MODEL, photo.uri)
  .then(
      function(response) {
        console.log(response);
      },
      function(err) {
        console.log(err);
      }
    );

}
}

Comment: Why would you want to?
Comment: to pass into the clarifai api as a base64 string
Comment: Once takePictureAsync is finished all you need is the path to the file name.
Comment: photo.uri is the file path
Comment: Hey @Brad , i use firebase storage to save images , this way right? I just take a photo uri from picker and save it to firebase as image ".jpg"
Answer: Without testing your code whatsoever FileReader should do the trick. Since snap is an asynchronous function:
async snap() {
  return await this.camera.takePictureAsync();
}

this.snap().then((photo) => {
  app.models.predict(Clarifai.GENERAL_MODEL, photo.uri)
    .then(
      function(response) {
        console.log(response);
      },
      function(err) {
        console.log(err);
      }
    );

  let reader = new FileReader()
  reader.onload = (item) => {
    console.log(item.target.result)
  }
  reader.readAsDataURL(photo.uri)

})

Comment: undefined is not an object (evaluating 'inputs.map')
Answer: Just add a flag base64: true:
 if (this.camera) {
    this.camera.takePictureAsync({
      base64: true,
    }).then(data => {
            console.log(data.base64);
             });
      }
    };

transforming photo.uri to base64 file


Upper bounds on distance between a random variable and Gaussian r.v.

Question: In the proof below, how is the inequality arrived at? I don't understand how $W$ is broken down in terms of: (1) the contribution from nodes further than node $i$ and (2) the rest. Can someone please explain?

This is Lemma 6.2 in paper --> https://arxiv.org/pdf/1109.1077.pdf
Answer: By defining $${A_1\triangleq f'(W)\left[1+\sum_i X_i(W_i-W)\right]\\
A_2\triangleq \sum_i X_i(W_i-W)f'(W)+\sum_i X_if(W)}$$we obtain$$f'(W)-Wf(W){=A_1-A_2}$$since $W=\sum_i X_i$. Hence the inequality reduces to $$|\Bbb E\{A_1-A_2\}|\le |\Bbb E\{A_1\}|+|\Bbb E\{A_2\}|$$or$$|\Bbb E\{A_1\}+\Bbb E\{A_2\}|\le |\Bbb E\{A_1\}|+|\Bbb E\{A_2\}|$$which is the celebrated triangle inequality: $$|u+v|\le |u|+|v|$$


Why the Email Body is giving different out put?

Question: I'm trying to trigger an email from Google App script.
const body = HtmlService.createHtmlOutput( "A  new task  have been added to the Task Manager
 www.abc.com")
if (props.val == "Jonh"){
MailApp.sendEmail("email@example.com",task,body,{name:"ABC"})
}

The problem is, email body give nothing but just this
screen shot
What is the mistake?
Comment: According to the [docs](https://developers.google.com/apps-script/reference/mail/mail-app) the **body** parameter expects a string. Your `body` probably gets stringified to its type name **HtmlOutput**. I never used it, yet according to [**HtmlOutput**](https://developers.google.com/apps-script/reference/html/html-output) something like `MailApp.sendEmail("email@example.com",task,body.getContent(),{name:"ABC"})` should work.
Answer: In your script, HtmlOutput object is directly used as the text body. I think that this is the reason for your issue. And, the 3rd argument of sendMail is the text body. In your situation, I thought that HTML body might be your expcted result. In this case, how about the following modification?
Modified script:
const body = HtmlService.createHtmlOutput("A  new task  have been added to the Task Manager
 www.abc.com")
if (props.val == "Jonh") {
  MailApp.sendEmail("email@example.com", task, null, { name: "ABC",htmlBody: body.getContent() });
}

Or, in your script, I think that you can directly use the HTML as follows.
if (props.val == "Jonh") {
  MailApp.sendEmail("firstname.lastname@example.com", task, null, { name: "ABC",htmlBody: "A  new task  have been added to the Task Manager
 www.abc.com" });
}

Or,
const body = HtmlService.createHtmlOutput("A  new task  have been added to the Task Manager
 www.abc.com")
if (props.val == "Jonh") {
  MailApp.sendEmail({
    to: "firstname.lastname@example.com",
    subject: task,
    htmlBody: body.getContent(),
    name: "ABC"
  });
}

Or,
if (props.val == "Jonh") {
  MailApp.sendEmail({
    to: "firstname.lastname@example.com",
    subject: task,
    htmlBody: "A  new task  have been added to the Task Manager
 www.abc.com",
    name: "ABC"
  });
}

References:

createHtmlOutput(html)
sendEmail(recipient, subject, body, options)
sendEmail(message)


Customise CAS Login page adds jsessionid to form action but breaks login

Question: I have successfully setup a CAS server for single sign on. Including the comestic stuff such as overriding the bottom.jsp, top.jsp and casLogoutView.jsp templates. My final step is to customise the login page (casLoginView.jsp). However when I do this customisation, the URL in the action attribute of the login form changes from /login?service=... to /login;jsessionid=...?service=...
This has the affect of the CAS login failing on the first attempt (although there is no error reported) and the login form presented a second time but this time the action attribute doesn't contain the jsessionid portion.
Why would this be happening?
Answer: I took a closer look at the differences between my jsp template and the default template (by Jasig) and made a stab in the dark: In my template I had changed the id attribute in the form to login. Changing it back to fm1 appears to remove the jsessionid portion of the url from the action attribute.
Go figure.
Comment: This has not fixed my problem of having to attempt login twice! After a day or two the issue return but this time there is no `jsessionid` in the action URL. In fact, every time I restart the service it works for only a limited time...


Disable django 2.0 admin responsive behavior

Question: This behaviour is not friendly for me and my team, we need a full view.
Is there a way to disable this:
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" type="text/css" href="/static/admin/css/responsive.css" />

Answer: Just put somewhere: {% block responsive %}{% endblock %}
In custom templates/admin/base_site.html


Prove an inequality between expected values of two random variables

Question: For $a \in \mathbb{R}$ we define the function $f_a$ as:
$$f_a(x) = \begin{cases}
x - a; & \text{if } x \geq a \newline
0; & \text{otherwise}
\end{cases}.$$
Let X and Y be random variables with integer values for which $E(|X|), E(|Y|) < \infty$. Let's assume that for every $x \in \mathbb{R}$ the following is true:
$$P(X > x) \leq P(Y > x).$$
Prove that for every $a \in \mathbb{R}$ the following is true as well:
$$E[f_a(X)] \leq E[f_a(Y)].$$
I assume that the key part is the fact that $f_a(X)$ and $f_a(Y)$ are both nonnegative random variables. I know that $E(X) = \sum_{n = 0}^{\infty}P(X > n)$ and I've tried solving the problem using these two facts but I couldn't really figure out how to use them.
Comment: Please show your attempt.
Comment: @geetha290krm Sorry, forgot about that. I will edit my post immediately.
Answer: \begin{align}Ef_a(X)&=\int_0^{\infty} P(f_a(X) >t)dt\\&=\int_0^{\infty} P(X > a, X>a+t)\\ &\leq \int_0^{\infty} P(Y > a, Y>a+t)\\&=Ef_a(Y)\end{align}
The inequality here follows from the hypothesis since $X>a,X>a+t$ is equivalent to $X>a_t$ and $Y>a,Y>a+t$ is equivalent to $Y>a_t$ where $a_t=\max\{a, a+t\}$.
Comment: Thank you for your answer! I have two questions - why is $Ef_a(X) = \sum{P(f_a(X) > n)}$? I know this would be true if $f_a(X)$ was a nonnegative integer-valued random variable but this is not the case. Is that equation true for a larger family of random variables?

The second question - I think you wanted to write $\sum{P(Y > a, Y > a + n)}$ in the penultimate step, right?
Comment: @HinkoPihPih You were right on both points. I have edited my answer.
Comment: I understand now. Thank you for your help!


Warm fridge cold freezer

Question: Hi I have a zanussi zrb23200xa frost free fridge freezer. The fridge is room temperature warm but the freezer is ice cold. Did a bit of reading and have tested the following which are all working fine
The defrost timer is working it sends signal to heating element which warms up and melts ice build u
The fan spins so it's working
The fridge thermostat is working tested it with multi Meter
I have defrosted the fridge for 48 hours and still warm anyone any ideas?
Thanks
Phelim
Comment: I had the same problem. I hired an appliance repair man and he said that the fan motor needed to be replaced. Even though the fan would spin, it was not spinning hard or long enough. I ordered and replaced the fan motor and everything works fine now.
Comment: You know what I think your right I just opened the it and fan was stopped I think it's just not blowing hard enough thanks for reply is there any way to test this?
Comment: It won't let me reply to your comment, but I remember the appliance repairman telling me the ice build-up was a sure sign that the fan was bad.
Comment: Is fridge gasket closing all the way around?
Answer: The user manual has this in the Control panel section (page 17):

Temperature Control Slider in refrigerator chamber
  The temperature control slider is used to
  adjust the refrigerator and freezer temperature, the slide on the thermostat is used to
  balance the distribution of air flow volume
  of each compartment. When the slider is
  turned down, there will be more air flow in the
  refrigerator and less air flow in the freezer, so
  the refrigerator will be cool faster. For normal
  operating use, keep the slider in the centre normal position. You should not need to
  adjust the temperature control dial if the slider
  is kept at the normal setting.

Is it likely that the slider control is simply at a bad setting?
Other manufacturer information is here.
Answer: This turned out to be what @Zbomb had recommended it was the motor went to local parts shop who had a second hand one I fitted it and solved the problem.
Thanks for help

Warm fridge cold freezer


What exactly is Ubuntu?

Question: From kernel all the way up to the Desktop Environment, where does Ubuntu reside?

Linux kernel is the kernel for all distros.
The basic utilities (fdisk, ls, bash, whiptail, etc.) are mostly GNU tools and (almost) compatible to almost-all Unix-like variants.
The systems of (userspace-resident) device drivers, pamd, udev, upower, etc. are also conformant to kernel APIs and ABIs interfaces.
The X system is also not Ubuntu.
The desktop environment (Gnome, Kde, etc.) is also not Ubuntu.

So, where is Ubuntu? In particular, where is Ubuntu's source code?
Comment: Package Management and support. apt uses Ubuntu's repositories to retrieve packages. These packages are generally managed by Ubuntu according to distribution, dependency and lifecycle of the release. If you change sources.list your OS will break horribly. I once tried replacing Ubuntu's sources with Kali's sources and then everything broke up. I needed to install the OS again.
Comment: https://en.wikipedia.org/wiki/Ubuntu
Comment: @Kulfy: That is due to the trigger scripts that are run in the post-processing phase of an apt/yum/pacman command. Mainly, where a particular config file is put is distro-dependent.
Answer: Ubuntu is not a single component of the system, it is a Linux distribution (aka distro).
This basically means a particular way of packaging all the components together. That includes selecting the right software (libraries, applications) to be able to work together seamlessly, choosing their right versions and provide patches where they're needed (typically kernel).
This is practically achieved by providing install images and package repositories.
Comment: So, in short, a distro makes final decision between choices unspecified by standards, interfaces.

What exactly is Ubuntu?


Hex to readable String using Python

Question: When I'm executing the following query:
SELECT HEX(FILL),ID FROM dbo.table WHERE FILL <> ''

It gives me below result:
404040404040404000000F40404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040

When I modified my query like this
SELECT FILL,ID FROM dbo.table WHERE FILL <> ''

I'm getting the result as shown in the picture:

used this URL for conversion: https://codebeautify.org/hex-string-converter
The above URL does not give me correct desired result. So I used, Python.
This is my python code to convert to a readable format:
import base64
hex_data   ='404040404040404000000F40404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040'
ascii_string = str(base64.b16decode(hex_data))[2:-1]
print (ascii_string)

I'm getting the result as:
@@@@@@@@\x00\x00\x0f@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

How can I make the string readable ( I wanted to read plain English chars)?
Comment: What is the output of that text supposed to be?
Comment: We are getting data from IBM DB2 iSeries machine and reading those for Analytics. So, we are excepting it to be a numbers or chars.
Comment: The image you uploaded appears to be a large blank rectangle with a small square in the top-left corner that says `FILL`, together with 3 1/2 rows of placeholder squares.
Comment: People are down voting this. However, I can challenge Python exports to at least give a proper clue, at least; as Python has been most popular language to analyze any data (I think even Data from Galaxy has been analyzed by Python). They may give the solution or not. If I got a solution, I'll definitely share here.
Answer: You mangled the bytes value by passing it to str().
By passing your bytes object through str() here, you produced a representation of the bytes object. That a representation is a string too is coincidental.
You can, at best, decode the bytes to text with the decode method:
bytes_object = base64.b16decode(hex_data)
text_object = bytes_object.decode('latin1')

I used Latin-1 (ISO-8859-1) to decode the data, because it is probably not ASCII data. Most ASCII text doesn't use NULL or SI (shift-in) bytes, to begin with. ASCII will work too, but as soon as you have any data outside of the 0x00-0x7F range you'll get an error instead.
The hex string converter you found includes the NULL and SI bytes too, but they are not printable so your browser doesn't show them. If you use print() then most likely your terminal won't show them either:
>>> import base64
>>> hex_data   ='404040404040404000000F40404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040'
>>> bytes_object = base64.b16decode(hex_data)
>>> text_object = bytes_object.decode('latin1')
>>> text_object
'@@@@@@@@\x00\x00\x0f@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
>>> print(text_object)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Answer: Try binascii.unhexlify():
>>> binascii.unhexlify('404040404040404000000F40404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040')
'@@@@@@@@\x00\x00\x0f@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'

Of course, you could also change your query to not hex encode the field:
SELECT FILL,ID FROM dbo.table WHERE FILL <> ''

which seems a better solution.
Comment: I have just modifies the question as per your suggestion and the data in a screenshot is shown. Please have a look at the data in the screenshot and suggest. I wanted to read plain English chars.Thanks.
Comment: The screenshot doesn't really help. The string contains `\x00` (NUL) and '\x0F` characters which are not printable, and that might explain the screenshot. What is the value supposed to be? It looks like those values are actually in the database. Try querying with your databases' native user interface.
Comment: `unhexlify` produces the same output `b16decode`. They are using Python 3, and have mangled the `bytes` object.

Hex to readable String using Python


Size subpanel needed for mini house

Question: I have 400 amp service in a 3800 square-foot home. I ran 100 amp to a garage.  I want to build a mini-home that will require approximately 130amps in appliances, etc. What size sub-panel do I need?
The mini house will  have:

stove 40 amp
water heater 18.75 amp
stackable washer dryer 30 amp
heat pump 8.87 amp
dishwasher 20 amp
fridge 8.5 amp
microwave/hood 15 amp
lights & outlets

That's why I figured 130 amps. The load in the main house should be able to handle a 100 to 150 amp sub panel. Need help deciding what size I should use.
Comment: @manassehkatz those are called "electric resistive heaters"...
Comment: @Tina Gregory don't get discouraged by the "sparkies" hashing it out, hang in there for a helpful answer (or reference the calculators mentioned in one of the comments...) If a comment asks for more info., try to provide it by editing it into your question, that helps with quality answers.
Comment: This sounds to me **not** like a true "tiny house" but rather more like a "small house next to a big house (3800 sqft!)" - i.e., "mini" is relative and not in the "tiny" sense.
Comment: @EdBeal -- the OP is really building a detached ADU, not a "tiny house" in the sense you're thinking of
Comment: @TinaGregory -- also, where are you on this planet? Heat pump emergency heat is second only to instantaneous electric hot water heaters at murdering service calculations...
Comment: Hello and welcome to stack exchange!  Approx 130 what?  It looks a bit like your question may have posted while you were still in the middle of writing it -- if that's the case you can use the edit button to add the rest of the info to your question.
Comment: amps in appliances etc that will be in mini house
Comment: We are all glad To hear of your project , but if your question is do you have enough power available to power a tiny house with 130 amps, I would ask a bunch of questions including how in the world are you going to put enough equipment in a tiny house to need a massive panel like that. Most motor homes max out at 50 amps and many only need 30 amps 120v.  To provide any kind of answer we would need to know the loads on your existing house and garage including heat, cooking type of water heater &  dryer , you may be able to provide another sub panel but if your home is 100% base board heat ?
Comment: To follow up on Ed's comment: 130A sounds like a LOT but keep in mind that, for example, 3 20A circuits for receptacles would not actually "use up" 60A in a panel (there are various calculations) plus a panel has "double" because it is 240V and most (but not all) circuits are 120V - e.g., 2 120V 20A circuits use only 20A @ 240V. So a **lot** more detail would help.
Comment: The process the code defines for a residential load calculation is based on square footage, specific appliances, and expected load diversity. There are forms that use some technical descriptions that are sometimes defined uniquely by the NEC. There are also some calculators that you might find useful.  https://ask-the-electrician.com/residential-electrical-load-calculation.html
Comment: @EdBeal I can name that tune in 1 appliance: on-demand water heater.
Comment: mini house has dishwasher 20 amp,fridge 8.5 amp, stove 40 amp micro hood 15 amp, water heater 18.75 amp, stackable washer dryer 30 amp heat pump 8.87 amp lights & outlets; that's why i figured 130 amps.  The load in the main house should be able to handle a 100 to 150 amp sub panel. Need help deciding what size i should use.
Comment: Now I know you have only added every load possible as the others that have a 'clue or think they have one ' have never wired a tiny house ,,,OOPS YES I HAVE AND FOR FREE, to help , I no longer do this after so many don't have a clue , power comes from some place at 130 amp for a tiny house , are they kidding , Rotflmao, tiny houses should be much more efficient , my much larger farm house draws less than 80 amps and we are all electric.
Comment: How many square feet is this tiny house?  That's what determines your lighting/outlet loads then and there...
Comment: @EdBeal Well, if it is a tiny house with lots of not-so-tiny servers mining Bitcoin...
Comment: The idea of a tiny house is a tiny impact on the environment, the tinys I have helped with had an average of 35 or 40 amps and most of this was was for the composting toilet! Heat was less than 3kw if I remember correctly and this included hot water. A Bitcoin is not part of my states power calculation, call it whatever you want but tiny houses / less than 500 sf , give me a break , yes I have only wired a few and this I did for free to help the homeless, never seen a tiny house that needs this kind of power,,  provide an answer if you want a lot of down votes from the Pacific Northwest
Comment: NEVER MIND!!!!!!!!
Comment: @TinaGregory -- we *really* need a square footage for this house
Answer: I ran your loads through a calculator and it spit out a main panel load of 66 amps.  That tells me you are probably alright.  But I am concerned you are not talking about heat pump emergency heat.  Heat pumps do not work in very cold temperatures, that's where emergency heat comes in. I note this building doesn't have any gas.
So while I think it'll work at 100A, I'd feel more comfortable seeing 150A because I worry that there are things you've left out.   So that's where I am with feeder.
As far as your subpanel size, there are 2 things we're concerned with.
Number of spaces in the panel
The usual mistake is to consider only panel ampacity and get a panel that is much too small (in spaces).  Remember, you have an all-electric house, which means a lot of 240V (2-pole, double-sized) breakers. You need the same number of electric appliances as a bigger house, they just have smaller numbers on the breaker.  So even a 30-space panel would be scary-small.  I would aim for 40-space.
There's a scam out there called "Circuits" - such as a panel that is 20-space/40-circuit. That relies on breakers that are now illegal - panel makers shouldn't be making these claims anymore, but they are.  By "Illegal" I mean a 40-"circuit" panel relies on very few of them being AFCI/GFCI or common-trip -- and in fact, most of them must be!
Ampacity of the panel
The amp rating of the subpanel itself is flexible.  It only needs to be greater or equal to the supply breaker. So if your supply breaker is 100A, then you can use a 100A, 125, 150, 200 or 225A subpanel.
Because it is an outbuilding not connected by a breezeway, your house will need its own main disconnect switch.  The easiest/cheapest way to get that is select a panel with a main breaker.  Again, any size will do >= the feed breaker size.
If you think "I'll get them the same size so the nearby breaker will trip first", unfortunately it does not work that way. It's a coin-flip  which one will trip first, unless it is raining and you are dressed for bed, then it will be the far one obviously.

Size subpanel needed for mini house


Set default browser to OPEN browser

Question: I am switching constantly between browsers (three different at the moment). So i was also switching default browsers to open my mail / new links etc...
I also saw that with the command sudo update-alternatives --config x-www-browser the browsers have different priorities.
So I had the idea that it could be possible that the default browser could be the browser/s that is/are actually open and running! And if two are running, the one with higher priority is chosen. Unluckily I did not find anything.. Is this possible? Would be really great!
cheers
dmeu
Comment: +1 for nice idea. Never thought of it, but it can be useful ^^
Comment: thanks a lot for these great answers (learned some new stuff ;-)
Comment: So if you happen to be running firefox, then all links would open in firefox, but if you happen to running Chromium, all links would use that, and if you're running both, it would use priorities to determine which one opens the links?  Might be possible with some manipulation of the /bin files that start each browser, but I'm afraid it's beyond my ability.
Comment: Interestingly, it's also possible to do this on Mac OS X: http://superuser.com/questions/41878/make-default-browser-whichever-one-is-currently-running
Answer: Here's something that works:
#!/usr/bin/env python

import sys, commands

browsers = [
    "firefox",
    "google-chrome",
    "chromium-browser",
    "epiphany-browser",
]

done = False
ps = list(i.split()[10] for i in commands.getoutput("ps aux").split("\n")[1:])
for i in browsers:
    if any(j.endswith(i) or j.endswith(i+"-bin") for j in ps) and not done:
        commands.getoutput(i + " " + (" ".join(sys.argv[1:]
            if len(sys.argv) - 1 else "")))
        done = True

if not done:
    commands.getoutput(browsers[0]["cmd"] + " " + " ".join(sys.argv[1:]))

Just re-order the list on top of the file any way you like, add and remove browsers.
The command you enter will be whatever you would type in the command-line to start this browser.
save this script somewhere, right click on it, go to properties → permissions and set executable. I recommend saving it in /home/<username>/.browser.
Find the file (hit Ctrl+H to show hidden files), right click and select Properties, then go to Permissions and set Allow executing file as program.
Go to System → Preferences → Preferred Applications, select Custom and type /home/<username>/.browser into the Command field.

The first browser that appears in the list and is running will be chosen to open the web site. If none of them is running, the first one will be opened.
I've tested this and it seems to work rather well, none the less, let me know if there are any errors in it. And it'd be cool if there was a method to do this that doesn't involve programming, this is just my peculiar solution.
Comment: works perfectly thanks! should be included in the ubuntu distribution ;-)
Comment: @Stefano, How is the last step setup for Ubuntu 15+ with Unity?
Answer: What a great idea!
I immediately set this up and it works great on my system.  Adapt the following script to your needs (you'll need superuser rights to install the script!):
#!/bin/bash

# looking for Firefox instances
pgrep -l '^firefox-bin$' > /dev/null

if [ $? -eq 0 ]; then
    echo
    echo "  Opening link in Firefox..."
    echo
    /usr/bin/firefox "$1"
    exit
fi

# looking for Konqueror instances
pgrep -l '^konqueror$' > /dev/null

if [ $? -eq 0 ]; then
    echo
    echo "  Opening link in Konqueror..."
    qdbus `qdbus | grep -m1 konqueror` /konqueror/MainWindow_1 org.kde.Konqueror.MainWindow.newTab "$1" False
    exit
fi

# no browser instances found, so open default browser
echo
echo -n "  No open browser found.  "

if [ -z "$1" ]; then
    echo "Opening new Firefox instance..."
    echo
    /usr/bin/firefox &
    exit
else
    echo "Opening link in new Firefox instance..."
    echo
    /usr/bin/firefox "$1" &
    exit
fi

The unmodified script will try to open a link (specified in $1) using Firefox.  If no instance of Firefox is found, it will try to reuse Konqueror.  Finally, if no instance of Konqueror is found, the script will open a new instance of Firefox.
When you're done, save the script at /usr/local/bin/reuse_open_browser and run the following commands:
sudo chmod +x /usr/local/bin/reuse_open_browser
sudo chown root:root /usr/local/bin/reuse_open_browser

sudo update-alternatives --install /usr/bin/x-www-browser x-www-browser /usr/local/bin/reuse_open_browser 100

Then select the script as default by running
sudo update-alternatives --config x-www-browser

Enjoy! :)
Comment: You can get rid of needing superuser privileges by just saving it to your home directory, possibly `.hidden`. Setting the default web browser via *Preferred Applications* is per-user.

Set default browser to OPEN browser


Text overflowing that has the Bootstrap class: form-control

Question: My text is overflowing within a span element which has the class: form-control
Code:

    Notes:
    <%= @stuff.notes %>

And when @stuff.notes has a lot of text, it overflows like this:

I did look at this question, as well as this ticket within bootstrap.  I am still having trouble coming up with a solution.
Update:
I realized I could use a form helper (even though it isn't a form) like this:

    Notes:
    <%= text_area_tag :notes, @complaint.notes, {class: "form-control", disabled: "disabled"} %>

Which renders it like this:

But I don't like how the disabled html attribute grays out the box and mutes the text.  It makes it difficult for the user to read.
Answer: You could use a basic panel to get a similar feel. See Bootply Here
Notes:

    Basic panel example

And if you really want to match the look of the form-control class, you could add a custom .inset-box-shadow class which would override the box shadow on the panel and give it that formy look. That may confuse users though, they may want to click and type in it.


Why is window.localStorage empty when I can see the data in the debugger?

Question: I'm storing some data in local storage, but having problem retrieving them when the page opens for the first time.
This is my code:
lib.getUserGeoLocation();
lib.getUserCityLocation();

var lib = {
    getUserGeoLocation: function(){
        navigator.geolocation.getCurrentPosition(onSuccess, onError);

        function onSuccess(position) {
            window.localStorage.setItem("latitude", position.coords.latitude);
            window.localStorage.setItem("longitude", position.coords.longitude);
        }

        function onError(error) {
            // (...)
        }

    },

    getUserCityLocation: function(){
        var lat = window.localStorage.getItem("latitude");
        var lng = window.localStorage.getItem("longitude");

    console.log(window.localStorage);
    }
}

The result is: Storage {length: 0}
But when I look in the debugger, the data is there:

Does anyone know why window.localStorage is zero / window.localStorage.getItem("latitude") returns null?
Update
I've also tried this solution to make sure I have the values before I call getUserCityLocation():
$.when(lib.getUserGeoLocation()).then(function(){
    lib.getUserCityLocation();
});

Solution
So my solution is this:
getUserGeoLocation: function(callback){
    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    function onSuccess(position) {
        window.localStorage.setItem("latitude", position.coords.latitude);
        window.localStorage.setItem("longitude", position.coords.longitude);
        return callback(true);
    }

    function onError(error) {
        return callback(false, error);
    }
},

Answer: Its because getUserGeoLocation will take some time to get the data and then insert values in localStorage and meanwhile you are calling the function getUserCityLocation, so this will return you null.
Comment: Yeah, I added callback `getUserGeoLocation: function(callback)`and in `onSuccess() ` I just do `return callback(true);`
Comment: Yeah, I've thought about that. While your answer might be an explanation, it's not a solution. I've tried using `$.when().then()` without success (see my updated Q). Any suggestions?
Comment: If you write getUserCityLocation in success function then it will work.
Comment: @Learning that wont be a proper solution. his scenario seems to be this "Whenever he used the function getUserCityLocation  he needs to get the location values", by using getUserCityLocation  inside success he is just getting the values on success but not when he needs it
Answer: "onSuccess" and "onError" are async calls which get called once the value is available where as getUserGeoLocation and getUserCityLocation are called one after another. So the code in getUserCityLocation is already called before onSuccess callback is called
When you use when and then, you should either return or call success or error of then from the when callback. Since getUserGeoLocation is not doing that you are still getting empty
Comment: Thanks. Do you know how can I get `getUserGeoLocation()` to use callback to return geoposition?
Comment: I will update the code! Your issue wont be solved by then,when or deferred since your purpose is use getUserCityLocation () function and the get the values.


How does Elastic Beanstalk know if EC2 server is busy?

Question: I've got a NodeJS application that does some moderately intense logic work when a user requests it. For example, a user on the frontend can click Analyze and the server will perform the work, which could take 30 seconds to 1 minute (non-blocking)
My app is not aimed at the wide public but at an audience of a few thousand. So there is a chance that several people might analyze at the same time.
I'm currently planning to deploy the app via Elastic Beanstalk, but I am not sure exactly how it will deal with a server when it is busy and if I have to implement some kind of custom signal to tell the load balancer to send requests to another instance, if the current one is busy performing analysis.
I understand that Lambdas are often held up as an option in this case, but I would much prefer to keep it simple and keep the code in my Node app.
How should I design this to ensure the app could handle doing analysis and still handling other requests normally?
Answer: Elastic Beanstalk uses Autoscaling Group to launch and maintain the EC2 instances required to run the Application. With Autoscaling Groups you can increase/decrease the EC2 instance count dynamically with Autoscaling Scaling policies. By default, Autoscaling Group provides scaling based on CPU, Network IN, Network Out, Request Count, Latency etc.. You can use any of these metrics and Scale-up your infrastructure dynamically.
You can refer to AWS Documentation here for more information.


How to format date in android output as : 11/12/2013 4:21 PM

Question: I have a timestamp in String which returns me below value in Android application
1398876631

How can i format it into below value
11/12/2013 4:21 PM

Comment: Did you searched over the SO?
Comment: Yes, I searched but i couldn't find an answer where the input is string and output is the format i am looking for.
Answer: Please try below function. Here you have to pass miliseconds and date format (like dd-MM-yyyy HH:mm:ss aa)
public static String getDate(long milliSeconds, String dateFormat)
    {
        // Create a DateFormatter object for displaying date in specified format.
        DateFormat formatter = new SimpleDateFormat(dateFormat);

        // Create a calendar object that will convert the date and time value in milliseconds to date.
         Calendar calendar = Calendar.getInstance();
         calendar.setTimeInMillis(milliSeconds);
         return formatter.format(calendar.getTime());
    }

Example
Log.i("====== Date "," :: "+getDate(1398876631,"dd/MM/yyyy HH:mm aa"))

Answer: convert your timestamp to a Date
Date d = new Date(Long.parseLong(timestamp) * 1000);

Then with SimpleDateFormat you can format your date as you want
String result = new SimpleDateFormat("dd/MM/yyyy hh:mm").format(d);

Comment: Integer overflow: use longs for millisecond timestamps, e.g. `1000L` instead of `1000`.
Answer: Your Problem answer
 SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy h:mm a");
 String date = df.format(Calendar.getInstance().getTime());
 Log.d("date",date.toString());// Output 01/09/2014 10:59 AM

Where as you can have DateFormat patterns such as:
"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
 "yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
 "yyMMddHHmmssZ"-------------------- 010704120856-0700
 "K:mm a, z" ----------------------- 0:08 PM, PDT
 "h:mm a" -------------------------- 12:08 PM
 "EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01

Check this link for more info.


lscpu gives no output in WSL

Question: I'm in Ubuntu on Windows. I'm in Ubuntu 16.04.2 LTS. I'm confused that lscpu doesn't give any output.

But man lscpu and lscpu -h will give me right information.
What's the problem and how can I fix it?
Comment: There's no reason to expect something that uses low-level APIs to work cleanly in WSL. File a bug report.
Comment: Vote to reopen because it's not a bug and as the accepted answer clearly shows it works as expected as of July 13th. Having the question closed could mislead others.
Comment: @WinEunuuchs2Unix On the one hand, isn't the fact that this currently works fine, at least on the latest version of Windows, more reason to think it *was* a bug? On the other hand, the answer [seems to be saying, "update Windows,"](https://askubuntu.com/questions/935403/lscpu-gives-no-output-in-wsl#comment1482705_935878) and that's an action that may be taken semi-*externally* to the Ubuntu system (i.e., external to the Ubuntu files that are intended to be accessed using WSL). I've gone ahead and voted to reopen this, somewhat reluctantly, but I would not be surprised if it gets closed again.
Comment: @WinEunuuchs2Unix drop by in chat and ping me, then remove this banter...
Comment: @EliahKagan Thanks for voting. For me at first blush I had the impression, looking only at the question,  that `lscpu` doesn't work. Had I not scrolled down to read the answer I would have walked away misled. Sorry for reopening old posts but I'm getting Win 10 next week and was doing some WSL research. Might have to change my name to WinEunuuchs2Unix2WSL :)
Answer: When using Windows Subsystem for Linux make sure you are on latest Windows version available.
(Win+R -> type winver)
I'm on version 1703 build 15063.483 (Creators Update) and lscpu works just fine.
onoma:~$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 15
Model name:            Intel(R) Pentium(R) Dual  CPU  E2200  @ 2.20GHz
Stepping:              13
CPU MHz:               2200.000
CPU max MHz:           2200.0000
BogoMIPS:              4400.00
Hypervisor vendor:     vertical
Virtualization type:   full
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm pni dtes64 monitor ds_cpl est tm2 ssse3 cx16 xtpr pdcm

Comment: I can get a normal result either after I upgrade Professional edition from Home edition today.And I'm in *10.0.15063* now
Comment: Can you set *default font* for your console?
Comment: About changing default font on conhost read this https://blogs.msdn.microsoft.com/commandline/2017/06/20/understanding-windows-console-host-settings/
Answer: You not only have to be at the latest version of Windows, you also have to have the latest updates for Ubuntu in WSL.
I was on Win 10 version 1709, OS build 16299.64 with WSL reporting Ubuntu 16.04.2, when when I ran the lscpu command and it provided no output. It also gave a return code of 1.
[ joelk: ~ ]$ lscpu
[ joelk: ~ ]$ echo rc=$?
rc=1
[ joelk: ~ ]$ uname -rv
4.4.0-43-Microsoft #1-Microsoft Wed Dec 31 14:42:53 PST 2014
[ joelk: ~ ]$

After I performed a
$ sudo apt-get update

and a
$ sudo apt-get upgrade

Ubuntu reported 16.04.3 and the lscpu command provided expected output.
[ joelk: ~ ]$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 142
Model name:            Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
Stepping:              9
CPU MHz:               2904.000
CPU max MHz:           2904.0000
BogoMIPS:              5808.00
Virtualization:        VT-x
Hypervisor vendor:     vertical
Virtualization type:   full
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave osxsave avx f16c rdrand
[ joelk: ~ ]$ echo $?
0
[ joelk: ~ ]$

lscpu gives no output in WSL


Is spraying peroxide on studs with mold enough?

Question: After removing some drywall in a basement that had mold on the bottom 1-2 inches, I was left with the base stud still black. Per the recommendation of a local company, I sprayed everything with hydrogen peroxide. I'm now trying to decide if I should have the framing removed and replaced, or if it is OK to drywall over this stud:
Comment: It is really hard to tell from your picture.  It looks like it is still wet.
Comment: It is not wet (been months since I sprayed it), that's the current dry color of the stud.
Comment: Is there a seal between the bottom plate and the concrete? FWIW, I (an many others) are not a fan of the 'trap wood behind a vapor barrier' method of doing basements. It leads to problems exactly like this.
Answer: I've seen peroxide and bleach mixtures used frequently to remove mold on studs.  The Natural Resources Defense Council suggests mixing a 1 in 10 bleach solution to clean. The NRDC might be a little too "green" for some people, but the Environmental Research Laboratory at the University of Arizona also has a great article regarding this.  They suggest a bleach to water ratio of 3/4 cup to 1 gal and a minimum 5 minute contact time before rinsing to inactivate and neutralize the mold. Since hydrogen peroxide and bleach do virtually the same thing, I would say the mold is dead if you allowed enough contact time.
However, my concern is the vapor barrier in your picture.
Concrete is porous and will slowly allow moisture to penetrate.  With the vapor barrier on the interior of the studs it will continually trap moisture in between the barrier and the concrete.  This could be the root cause of your moisture problem which caused the mold in the first place.  If so you may be seeing more mold in the future depending on where you live, etc. For more information the EPA has a great technical document on "When Continuous Water Vapor Barriers Shall Not Be Installed."
Comment: I agree.  The plastic and fiberglass insides are about the most common basement installation.  A lot of times causes no problems and makes sense... However the Building Science report on residential basements show this as one of the worst basement installs.  The fact is the fiberglass insulation and the vapor barrier create a wet zone and kill air flow... So you get mold.
Comment: Agree. The trapped moisture and cellulose creates a breeding ground for mold. Your vapor barrier is simply making this a sealed container -- it's a common mistake, as there is a lot of confusion regarding warm-side vapor barriers (such as for crawl-spaces/exterior walls) and the issues they cause when the source of moisture is outside the wall(not condensate). Removing the vapor barrier and replacing the drywall with paperless-backed would be better than nothing, but you'll always have issues until properly fixed. Also expect the wood to rot eventually, due to direct contact with the concrete.
Comment: Thanks. While I agree the vapor barrier could be improved, the water problem was a major recurring leak (which I have fixed).
Comment: Should I be concerned that the mold is deeper in the studs (where the peroxide might not reach it)?


Consider $E_f = \{(x,(x,f(x)))| x \in \mathbb{R} \}$ for an arbitrary function, $[E_f]_x$ is a borel set

Question: I have some sort of struggles solving this problem,
Suppose $f:\mathbb{R} \rightarrow \mathbb{R}$ is an arbitrary function, and $E_f = \{(x,(x,f(x)))| x \in \mathbb{R}   \}$. I have to show that cross sections $[E_f]_x$ and $[E_f]^{(x,y)}$ are Borel sets. Also I have to show that $E_f$ is not necessarily a Borel subset of $\mathbb{R}^3$.
I think Both $[E_f]_x$ and $[E_f]^{(x,y)}$ are single points or an empty set, that is why they are Borel subsets of $\mathbb{R}^2$ and $\mathbb{R}$ respectively.
For the second part I need to know that what Borel subsets of $R^3$ look like, then I can give a counter example.
Do you have any idea?
Answer: Consider a non-measurable set $V$ like the Vitali set and take $f = \chi_V$ its characteristic function. If $E_{\chi_V}$ was a Borel set then $E_{\chi_V} \cap \{\mathbb R \times \{1\}\} = V \cap \{1\}$ would be Borel. Which is not the case as it not even measurable.


Can I create a bootable Windows 7 installation USB from within Ubuntu to boot a 2010 model iMac?

Question: I have a 2010 model iMac on which I have installed Ubuntu 14.04 as the sole OS.
I would like to install Windows 7 as a dual boot. I have freed up some space on the HDD.
No matter what I try, I am unable to boot the iMac from either a Windows 7 USB or a Windows 7 DVD.
Is this possible at all? What do I need to do to create a bootable Windows 7 installation USB for the iMac?
So far I have tried:

Using Brasero to burn the ISO image to a DVD - could not boot from this DVD
Using UNetbootin to create a bootable USB from an ISO image (as well as modifying the boot folder on the USB to add a bootx64.efi file) - could not boot from this USB.

Unique issues for this question:

Install Windows 7 and not Windows 8
Install Windows 7 on an iMac
Install Windows 7 in UEFI mode
Tried the USB method mentioned in another question - iMac cannot boot from the USB
Comment: @markkirby Thanks, my question is unique and I have added reasons as to why I believe it is unique.
Comment: @markkirby I am not quite sure at this point, all I know is that I have tried the method mentioned in the question you suggested as a possible duplicate and am unable to boot the machine from that USB/DVD.
Comment: @markkirby I have an external HDD with OSX on it. I could boot the machine from that, what should I try in OSX?
Comment: OK the issue is the way a mac boots is different to a PC and you must use a specific tool to make a win 8 UEFI USB, just follow this tutorial from microsoft on your mac OSX and you will see what I mean http://windows.microsoft.com/en-gb/windows-8/install-windows-on-mac
Comment: @markkirby Thanks very much, but I need to install Win 7, not Win 8, is your link going to work for Win 7 ? :)
Comment: Here is a better tutorial for you, that mentions working with 7 http://www.howtogeek.com/186907/how-to-install-windows-on-a-mac-with-boot-camp/
Answer: Booting Windows 7 in EFI mode on a Mac is tricky at best. (Note UEFI is EFI 2.x, but Macs' EFIs are all 1.x versions, so Macs technically don't have UEFIs.) There's a very long thread on MacRumors about this subject:
http://forums.macrumors.com/threads/win7-x64-booting-natively-via-efi-no-bios-emulation.696523/
To boil this thread down, some people have successfully installed and booted Windows 7 on some Macs in EFI mode. The procedures for doing so are often convoluted, and most people who attempt it fail. At least, that's my impression from the last time I reviewed it, which was over a year ago. Perhaps somebody's made a breakthrough since then.
Windows 8 is much easier to get working on Macs in EFI mode, but even it doesn't always works. I haven't been keeping track of details of which models work best in EFI mode.
Dual- or triple-booting Windows 7 on a Mac is most easily done in BIOS mode. In fact, given a Windows/Linux dual-boot on a Mac (with no OS X), by far the easiest solution is to boot both OSes in BIOS mode. If you were starting from scratch, I'd say to create an MBR partition table, boot Windows 7 in BIOS mode, install it, and then boot and install Ubuntu in BIOS mode. Maintaining an EFI-mode boot on a Mac without OS X poses some challenges because Apple has deviated from the usual EFI boot procedures, so tools like Ubuntu's efibootmgr may not work quite right; you really need OS X's bless utility to properly manage the EFI boot process. Going with a strictly BIOS-mode setup bypasses these problems.
Comment: How would I go about getting everything installed in BIOS-mode on an imac though? I don't think they support BIOS or even BIOS emulation in any way do they ?
Comment: AFAIK all x86-based Macs provide a CSM (and hence BIOS/legacy support). The earliest models require a firmware update to add this support, but I'd expect it would have been present in your 2010 model from the start. This support is typically activated when the firmware notices an MBR (or hybrid MBR) partition table or a CD/DVD with BIOS-mode boot loader. The computer can still boot in EFI mode with the CSM activated; activation of the CSM simply enables a BIOS-mode boot as an option.


get the values passed through ajax on the php page to be executed

Question: i would like to send 3 parameters organisation name,location name and building name as the parameters to ajax i have coded it as follows i would like to get the values passed from the ajax to see in the page that i need to execute .
 //ajax calling
  function ajax()
  {
 var req;
var org=document.getElementById('category_id').value;
var loc=document.getElementById('category_id1').value;
var bui=document.getElementById('category_id2').value;
 if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
   req=new XMLHttpRequest();
 }
 else
 {// code for IE6, IE5
   req=new ActiveXObject("Microsoft.XMLHTTP");
 }
 req.open("POST", "addmachine.php?org="+org+"&loc="+loc+"&bui="+bui+"", true);
 req.send();
  req.onreadystatechange=function(){
   if(req.readyState==4&&req.status==200){
       $(".error").hide();
       result=req.responseText

 }

}

         <form name="theForm" method="post" action="addmachine.php" enctype="multipart/form-data" onSubmit="return validate();">
          Organisation Name
                    <select style="width: 305px;text-align:left ;"  name="category_id" id="category_id" onchange="OrganisationName(this);">
                    <option value="">Select</option>
                     <option value="1">1</option>
                     <option value="2">2</option>
                                      </select>

        Location

                     <select style="width: 305px;" name="category_id1" id="category_id1" onchange="LocationName(this);" >
                     <option value="">Select</option>
                     <option value="1">1</option>
                     <option value="2">2</option>

                     </select>

        Building

                    <select style="width: 305px" name="category_id2" id="category_id2" onchange="BuildingName(this);" onchange="ajax(this);">
                    <option value="">Select</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    </select>

                    Entrance/Exit
                    <input type="text" name="ent" id="ent" placeholder="enter entrance/exit"/>

                    Type
                    <input type="text" name="type" placeholder="enter your work station"/>

          Name
          <input type="text" id="workstnname" name="workstnname" placeholder="enter your work station" onblur="return name();" onkeypress="return onKeyPressBlockNumbers(event);">
          Description
          <textarea name="description" style="height:150px;width:300px;"></textarea>
          Machine Type
                    <select style="width: 305px;text-align:left;"  name="machinetype">
                    <option value="">Select</option>
                    <option value="kiosk">kiosk</option>
                    <option value="workstation">workstation</option>

                  </select>

                    <input type="submit" name="submit" value="Submit">

        </form>

here on change function of building i am supposed to call ajax to execute a php page called addmachine.php with parameters as selected organisation,location and building ,now i am afraid why i am not getting response from the ajax
can any one say me where i am doing wrong the php to be executed on onchange of the building is here
<?php
session_start();
$org=$_GET['org'];
$loc=$_GET['bui'];
$bui=$_GET['loc'];
$addmachine=array(
'org_name'=>$org,
'loc_name'=>$loc,
'building_name'=>$bui
 );
   echo json_encode($addmachine);
  $url='web service url';
    $data="$addmachine";
     echo("Input to Server : ".$data."\n");
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($addmachine));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    $response=  curl_exec($ch);
    echo('\n'."Server response : \n \n".$response);
    curl_close($ch);
      ?>

Comment: In your php code are you getting the values &org,$loc and $bui
Comment: well my question is that how to get thoose values in php code
Answer: If you normally post your form by clicking submit, you need to change your php code to
$org=$_POST['category_id'];
$loc=$_POST['category_id1'];
$bui=$_POST['category_id2'];

If you use your ajax function then it should be
$org=$_GET['org'];
$loc=$_GET['bui'];
$bui=$_GET['loc'];

cause your using GET variables in your querystring (remove the extra ampersand before org)
req.open("POST", "addmachine.php?org="+org+"&loc="+loc+"&bui="+bui+"", true);

Comment: sir,i have made some modifications can you please review it and say mae what i am doing wrong
Comment: change the req.open("POST", "addmachine.php?org and remove the &
Comment: i have changed it but no luck
Comment: does the server get the request?
Comment: ha ha i got it,i was looking for the response to come without alerting it, i have added alert(result) to the end of the ajax function and it comes.Thanks to all who helped chandresh_cool, Amir, Ruben-J
Answer: Put
var org=document.getElementById('category_id').value;
var loc=document.getElementById('category_id1').value;
var bui=document.getElementById('category_id2').value;

inside your
function ajax()

Then try once.
Comment: sir,i have made the modifications as you suggested can you please have a look at the code i have edited,the modifications could not bring any changes thank you
Comment: change req.open("POST", "addmachine.php?&org="+org+"&loc="+loc+"&bui="+bui+"", true); to req.open("POST", "addmachine.php?org="+org+"&loc="+loc+"&bui="+bui+"", true);
Answer: You have extra & in ?&org
req.open("POST", "addmachine.php?&org="+org+"&loc="+loc+"&bui="+bui+"", true);


Opencms in Java

Question: I have installed the OPENCMS in the Tomcat and I have configured it in eclipse. At first I was doing well but now it gives me error. I have the Tomcat version 7 and java 7. This is the error that I get:
Grave: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/opencms]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1009) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:985) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1127) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:2020) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/opencms] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [oracle.net.aso.C00->oracle.net.aso.C12->oracle.net.aso.C11->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object->java.lang.Object] at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:2174) at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2120) at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1981) at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1942) at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1927) at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1332) at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:888) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:388) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5519) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) ... 10 more
sep 29, 2017 12:18:08 PM org.apache.catalina.startup.HostConfig deployWAR Grave: Error durante el despliegue del archivo C:\apache-tomcat-7.0.81\webapps\opencms.war de la aplicación web java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/opencms]] at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1013) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:985) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1127) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:2020) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744)
Comment: `Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies.` ... have you looked into the suggestions coming from your stack trace?
Comment: Yes, run configurations=> arguments:-Xss2048m -XX:MaxPermSize=256m.
Comment: However, when I give debug it still gives me error
Answer: Had this exact issue today with a different app and it ended up being that oracle.net.aso.C00 was in multiple jars.
Found with following snippet of bash:
in the WEB-INF/lib folder run
for jar in $(ls *jar); do unzip -l $jar ; done | grep -P '(^Archive|oracle.net.aso.C00)'

which resulted in:
Archive:  com.springsource.oracle.jdbc-10.2.0.2.jar
      804  02-04-2009 13:18   oracle/net/aso/C00.class
...
Archive:  ojdbc14-10.2.0.4.0.jar
       683  02-02-2008 11:39   oracle/net/aso/C00.class

needed to remove one of the jars.

Opencms in Java


Passing object into array that are of the same parent class

Question: As I am still somewhat new to programming in C++ I was just curious if it were possible to pass objects pointers to an array in order for code consolidation.
Header file like such;
class.h

class parent
{
    some information.....
};

class child1 : public parent
{
    some information.....
};

class child2 : public parent
{
    some information.....
};

Main file like such;
main.cpp

#include "class.h"

int main()
{
    child1 instanceChild1;
    child2 instanceChild2;

    child1* pointer1 = &instanceChild1;
    child2* pointer2 = &instanceChild2;

    parent array[2] = {pointer1 , pointer2};
}

I am trying to achieve such so that I may create a function that uses a dynamic array in order to hold object pointers so that I may dereference them in the function and manipulate them accordingly. Though I am having issues getting the different pointers to work together when going into an array. I need such functionality since there will be many different objects(all under the same parent) going in and out of this function.
Comment: @pstrjds Would the slicing problem be non-existent if A was abstract?
Comment: Yes it is probably possible. But define `parent* array[2]={pointer1,pointer2};`
Comment: Not knowing exactly what you are doing, I would suggest `std::vector` instead of creating a dynamic array. You could add items to the vector this way `vecParents.push_back(&instanceChild1)`
Comment: Another thing to beware of, if you are passing derived objects as base class objects is the [slicing problem](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c#274636)
Comment: @remyabel you are correct if Base class is abstract then there would no slicing issue.
Comment: The Solution provided by Basile has worked(very simple and I commend you). But I am testing it so far, and yes I am running into the problem of having the object and all its variables(due to them being of class parent), but not having the functions that are specific to the child class that are needed in the function.
Comment: So as of right now I am testing to see if I can get a type test working in order to catch what type of child class it is when dereferencing so that it can be reconstructed in the function properly. If anyone has an easy solution to this I am all ears.
Comment: @user3065238 right, you still have pointers to the base class, so you can only access base class methods. The idea is that you define an "interface" of virtual methods in the base class. Then the derived types can implement these differently.
Comment: @juanchopanza Ok, yes all is working in harmony now. Thanks for the great input everyone.
Answer: Yes it is possible.
But you need to declare the array like this
parent * arr[] = { ... }

or it would be better if you use a vector
vector<parent *> arr;
arr.push_back(childPointer);//For inserting elements

as @pstrjds and @basile has written
and if you want to use child specific member functions, you can use dynamic cast
ChildType1* ptr = dynamic_cast<ChildType1*>(arr.pop());
if(ptr != 0) {
   // Casting was succesfull !!! now you can use child specific methods
   ptr->doSomething();
}
else //try casting to another child class

** your compiler should support RTTI in order for this to work correctly
you can see this answer for details
I prefer to use pure Virtual functions like this
class A {
        public :
        enum TYPES{ one , two ,three };
        virtual int getType() = 0;
    };
class B : public A{
public:
    int getType()
    {
        return two;
    }
};
class C : public A
{
    public:
    int getType()
    {
       return three;
    }
};


$\bigcup_{x\in K}B'(x,r)=\left \{x\in X |d(x,K)\leq r\right \}$ for $K$ compact

Question: Let $(X,d)$ be a metric space and let $K$ be a compact subset of $X$
Let $r>0$ be given
Prove, $\bigcup_{x\in K}B'(x,r)=\left \{x\in X |d(x,K)\leq  r\right \}$ where $d(x,K)=inf_{y\in K}d(x,y)$ (B' is closed ball)
Any hints ?
Answer: Hints:
$1).\ $ If $y\in \bigcup_{x\in K}B'(x,r),$ then $y\in B'(x,r)$ for some ball $B'$. Then, $d(x,y)\le r.$
$2).\ $ If $y\in \left \{x\in X |d(x,K)\leq  r\right \},\ $ then fix this $y$ and note that the function $d(y,\cdot ):X\to \mathbb R$ is continuous, so it attains its minimum on the compact set $K$.
Comment: I'm done with 1) , I found my way with the first inclusion,but I'm stuck with 2)
Comment: The key phrase is: " it attains its minimum on the compact set K."
Comment: You mean inf(d(y,K))=<d(y,K) ?
Comment: I mean the inf is reached. So now that means that there is a ___ in ___ such that ___.
Comment: There is a sequence in K that converges ??
Comment: Since $d(y,K)\le r$, there is a point $x\in K$ such that $d(y,x)\le r$ and this says that $y\in B'(x,r).$
Comment: If $K$ is compact then for every $y$ there is an $x \in K$ such that $d(x,y)=d(y,K)$.
Comment: Yes. Typo. Thanks-
Comment: I guess the statement should be in fact: $d(y,K)=s\le r$, so there is an $x\in $K$ s.t. $d(y,x)=s$.


For which $a$ and $b$ has $P = \begin{bmatrix} 1 & 1 & 1 \\ 0 & a & b \\ a&0&b \end{bmatrix}$ the eigenvalues $0$ and $3$?

Question:
If the matrix
  $$
P =
\begin{bmatrix}
 1 & 1 & 1 \\
 0 & a & b \\
 a & 0 & b
\end{bmatrix}
$$
  has eigenvalues $0$ and $3$ then to determine values of $a$ and $b$.

I know that $\det(P) = 0$ (because one eigenvalue is $0$) and got $a=0$ or $a=2b$. But how do I proceed from here?
Thanks a lot!
Comment: Try the characteristic polynomial.
Answer: $0$ and $3$ are supposed to be eigenvalues of $P$, i.e. $\det(P) = 0 $ and $\det(P - 3 I) = 0$. From the first condition you've correctly deduced $a = 0$ or $a = 2b$.
If $a = 0$, then the second condition yields $b = 3$. If you plug $a =2b$ into the second equation, you get $-6b^2 + 24b - 18 = 0$, i.e. $b = 1$ or $b = 3$.


Find table in firebase real time database given user email or some other arbitrary field

Question: I have a user stored in real time firebase with key uid (user id) and fields:
uid
email
emailVerfied

I would like to find the user record coresponding given an email. My current hack leaves much to be desired. In particular how to properly retrieve the actual user record given a snapshot:
function readByEmail( user_email : string, next : any ){

    firebaseApp.database().ref('/users/')
    .orderByChild('email')
    .equalTo(user_email)
    .once('value', snap => {

        // retrieve the user key:
        const record = snap.val();

        let key;

        for ( let _key in record ) {
            console.log('field: ', _key, record[_key])
            key = _key;
        }

        next(record[key])

    });
}

How should I get rid of the ugly loop hack which is not gauranteed to work at all?
Answer: If you have a child property email with the value you want to filter on, there may be multiple child nodes matching the value you filter in. That's why you need the loop, so I'd say that is working as expected.
A more idiomatic way of performing the loop is to use Firebase's built-in forEach method:
firebaseApp.database().ref('/users/')
.orderByChild('email')
.equalTo(user_email)
.once('value', snap => {

    let key;
    snap.forEach(child => {
        key = child.key;
    });

    next(snap.child(key).val())
});

If you know there is only one child that matches, you can listen for child_added, which fires for each child. So once("child_added" will fire only for the first child:
firebaseApp.database().ref('/users/')
.orderByChild('email')
.equalTo(user_email)
.once('child_added', snap => {
    next(snap.val())
});

But if your app already requires that the email value is unique amongst all nodes under /users, consider using the value as the key. You'll need to encode the email address, since . is not allowed in Firebase keys (encoding it as , is custom). When you use the (encoded) email address as the key, you can do a direct lookup like this:
firebaseApp.database().ref('/users/'+user_email)
.once('value', snap => {
    const record = snap.val();
    key = snap.key;

    next(record)
});

And since there's at most one node that matches this read, you no longer need a loop in the callback.


How can I shut off these water valves that won't turn?

Question: How can I shut off these water valves that won't turn? They connect to my washer, which I am trying to fix. I have sprayed the valves with WD-40 and partially unscrewed the screws, but that has not helped, so I'd welcome any ideas.
Comment: And make sure you're turning them the right way.  They only turn 90 deg.
Comment: Do NOT loosen the screws.  Those hold the valve handle on. (Well, except to change the valve handles, obviously :)
Comment: Can try lightly tapping them with a small hammer.  You want to vibrate them, not smash them.
Comment: Tap on the metal brass part.  Some vibration might loosen something up.  The screws are just to keep the plastic handles from coming off.
Comment: @crip659, I tried some light taps, but hammering for vibration is strange to me. Would I get the most helpful vibration by tapping down or tapping the side, and by tapping near the screw or tapping near the end?
Comment: If pliers won't turn them , you are turning the wrong way.
Comment: One benefit of loosening the screw and (temporarily) removing the handle is that you can verify whether you should turn CW or CCW to turn the valve OFF because there will be tabs on the undersides of the handles that interlock with tabs on the valve bodies that allow turning (90 deg) only in the correct sense. The washer valves in my house are turned CW to shut off. Put a small adjustable wrench on the handle and it should move.
Answer: Before doing anything - turn off the water further up the line - at the mains if needed.
Those levers are probably plastic, so to eliminate the problem when they break, remove the screws, and there will be a spigot of some shape that they were attached to. A well fitting wrench, Mole or suchlike, or a socket from a socket set, maybe, will give better leverage. Rotate a few degrees at a time, if possible. If still not, then warm up the brass with a heatgun or hairdrier and try again. WD40 probably didn't penetrate but may well do when the levers are off. Bear in mind they will only go 90 degrees - in ONE direction.
As with all water shut-off valves, it's worth closing/opening them at least once a year. Nothing worse than having a leak and finding the main inlet valve (if you actually know where it is..!) is solid - and wide open.
Answer:
Leverage.  You could use a pliers or vice grips to give you a longer lever arm.  But you have been working out a lot during Covid and you might be strong.  Be careful not to crack the handle.

Turn off water at the house, unhook hoses and take valves off.  Maybe God is showing you in advance that these things are broken, and if your water hoses burst in the dead of night you will not be able to turn them off.  Stuck open valve is a good problem to discover in cool blood while the sun is up.  You can take them off and mess with them until the valve works again, and then remember to work them periodically so they dont get stuck.  Which I am going to go do right now; thank you.    Or an opportunity to buy new ones that work as they should.
Answer: I would take the plastic handles off, then on many makes of valve the casting makes it obvious which way they should turn.
Then I would get a quality adjustable set so it fits tight in the shaft square and turn appropriately.
Always worked for the ones we had on our systems and we fitted lots of extra valves to be able to isolate sections as needed - they are cheap compared to the time draining and refilling...
Answer: I would be tempted to add a GHT extension with an in-line valve. Basically two valves in series on the same run.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

How can I shut off these water valves that won’t turn?


Windows 7 over Ubuntu without a CD Drive

Question: I am not that experienced in installing operation systems.
I bought a PC that has Ubuntu on it but I want to replace it with Windows 7.
I have been following all the steps that were covered in this video.
But the problem is that once I open the archive manager it only contains a text file saying this
<code>This disc contains a "UDF" file system and requires an operating system
that supports the ISO-13346 "UDF" file system specification.
</code>
The main problem is that the laptop does not have a CD drive at all
Can you please give me any possible solutions or guides
Answer: First make a backup of your flashdrive's files on another computer
Secondly download a Windows 7 ISO and Unebootin http://unetbootin.sourceforge.net/
Using Unebootin create a bootable USB (make sure it's plugged in) with the Win7 ISO
Follow this tutorial if you have problems https://www.youtube.com/watch?v=KPZJ0oCQxu0


Composition of invertible functions proof

Question: I have this proof to do, I do not think it is too hard if you I know the rules I should apply. In particular, is there anything i can do with the -1's in this case?
If now, what rules can I apply to this to get this out?

$(f \circ g)^{-1} = g^{-1} \circ f^{-1}$

So I'm stuck here,
$$(f \circ g)^{-1} = (f(g(x)))^{-1}$$
For example, I'm relearning a lot of stuff, I remember learning something like this:
$(AB)^{-1} = B^{-1} A^{-1}$
I'm thinking I can apply this? or is this result actually a result of the lemma I'm supposed to be proving anyway?
Help would be appreciate.
Thanks.
Comment: The definition of $h^{-1}$ is that the composition $h^{-1}(h(x)) = x$ and $h(h^{-1}(x)) = x$. Can you apply this definition to $h = f \circ g$ to get the result?
Comment: It is sometimes referred to as the "Socks and Shoes" principle.  You first put on your socks and then you put on your shoes.  If you want to reverse this process, you must first take off your shoes before taking off your socks.
Comment: Nope, I still don't see it @Nick. If two functions are invertible, does that mean the author means they are inverse of each other? or just that they have inverses? I'm wondering if this is what the author means of it has something to do with the solution.
Comment: Lemma: if f and g are invertible functions and $f \circ g$ exists, then $f \circ g$ is invertible and $(f \circ g)^{-1} = g^{-1} \circ f^{-1}$ that is what I have to prove. @Nick
Comment: and to you too @JMoravitz
Comment: You type it correctly in the second comment but your first comment suggests that you don't know what that means.  Assuming $f$ and $g$ are invertible functions and the composition $f\circ g$ exists then not only is the composition invertible too but it's inverse is the composition of the inverses of the two functions in the other order, $g^{-1}\circ f^{-1}$.  The hint again is to look closely at the definitions of what it means to be an invertible function and test to see if $g^{-1}\circ f^{-1}$ satisfies the properties of being the functional inverse of $f\circ g$.
Answer: We have the following definition of inverse function:

Let $F$ be a function. We say that $G$ is the inverse function of $F$ if it satisfies
  $$
G(F(x))=x,\ \forall x\in Dom\ F,
$$
  and
  $$
F(G(x))=x,\ \forall x\in Dom\ G.
$$
  In this case, we denote $G$ by $F^{-1}$.

We shall use the following basic stuff without mentioning:
i) $F^{-1}$ is unique;
ii) $(F^{-1})^{-1} = F$;
iii) $Im\ F^{-1} = Dom\ F$;
iv) $Im\ F = Dom\ F^{-1}$.
Let us consider the functions $f$ and $g$ of our problem.
Notice that there is a condition that is implicitly assumed. To be able to do the composition $f\circ g$, we must have that
$Im\ g \subset Dom\ f$. On the other hand, to be able to do the composition $g^{-1}\circ f^{-1}$, we must have $Im\ f^{-1} \subset Dom\ g^{-1}$, then
$$
Dom\ f = Im\ f^{-1} \subset Dom\ g^{-1} = Im g.
$$
Therefore, the identity is implicitly assumed:

$Im\ g= Dom\ f$.

Now, let us prove that $(f\circ g)^{-1} = g^{-1}\circ f^{-1}$.
The function $f^{-1}$ satisfies
$$
f^{-1}(f(x))=x,\ \forall x\in Dom\ f.
$$
In particular, for any $y\in Dom\ g$, we have that $g(y)\in Im g = Dom\ f$, and consequently, substituing $x$ by $g(y)$ above, we get
$$
f^{-1}(f(g(y)))=g(y),
$$
so $f^{-1}(f(g(y)))\in Im\ g = Dom\ g^{-1}$, and, applying $g^{-1}$ above, we get
$$
g^{-1}(f^{-1}(f(g(y))))=g^{-1}(g(y)) = y.
$$
This way we proved that

$(g^{-1}\circ f^{-1})((f\circ g)(y))=y,\ \forall y\in Dom\ g = Dom\ (f\circ g).$

Now, this fact is valid for any two invertible functions $f$, $g$ such that $Dom\ f= Im\ g$. But notice that
$$
Dom\ g^{-1}= Im\ g = Dom\ f = Im\ f^{-1}.
$$
Then the equality above is also valid if we replace $f$ by $g^{-1}$ and $g$ by $f^{-1}$. Then

$(f\circ g)((g^{-1}\circ f^{-1})(y))=y,\ \forall y\in Dom\ (g^{-1}\circ f^{-1}).$

By the definition of inverse function, the two underlined properties imply that $(g^{-1}\circ f^{-1})=(f\circ g)^{-1}$.
Comment: Thanks for that @AndrePorto assumptions in your answer here were not made obvious in the book. At least it is not obvious to me.


I want mortgage in currency format, but in my program instead of "$" sign it is giving me "? ' sign

Question: package calProject;

import java.text.NumberFormat;
import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
        final byte MONTHS_IN_YEAR = 12;
        final byte PERCENT = 100;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Principal: ");
        int principal = scanner.nextInt();

        System.out.print("Annual Interest Rate: ");
        float annualInterest = scanner.nextFloat();
        float monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;

        System.out.print("Period (Years): ");
        byte years = scanner.nextByte();
        int numberOfPayments = years * MONTHS_IN_YEAR;

        double mortgage = principal
                      * (monthlyInterest * Math.pow(1 + monthlyInterest, numberOfPayments))
                      / (Math.pow(1 + monthlyInterest,  numberOfPayments)-1);

        String mortgageFormatted = NumberFormat.getCurrencyInstance().format(mortgage);
        System.out.println("Mortgage: " + mortgageFormatted);
    }

}

OutPut:
Principal: 100000
Annual Interest Rate: 3.92
Period (Years): 30
Mortgage: ?472.81
Comment: What's the default locale of your system? I assume it isn't the US one so try `getCurrencyInstance(Locale.US)` instead.
Comment: What is your computer's locale setting? When you use `NumberFormat.getCurrencyInstance().format(mortgage)`, why do you expect it to interpret the `mortgage` amount as a number of *dollars*, rather than, say, euros, or pounds sterling, or pesos, or drachmas?
Comment: And does your terminal support UTF-8?
Answer: As mentioned in the comments, a Locale may need to be specified explicitly to get necessary currency sign:
String mortgageFormatted = NumberFormat.getCurrencyInstance(Locale.US).format(mortgage);
System.out.println("Mortgage dollar: " + mortgageFormatted);

mortgageFormatted = NumberFormat.getCurrencyInstance(Locale.UK).format(mortgage);
System.out.println("Mortgage pounds: " + mortgageFormatted);

mortgageFormatted = NumberFormat.getCurrencyInstance(Locale.JAPAN).format(mortgage);
System.out.println("Mortgage yen: " + mortgageFormatted);

mortgageFormatted = NumberFormat.getCurrencyInstance(Locale.GERMANY).format(mortgage);
System.out.println("Mortgage euro: " + mortgageFormatted);

Output:
Mortgage dollar: $7,164.31
Mortgage pounds: £7,164.31
Mortgage yen: ¥7,164
Mortgage euro: 7.164,31 €