How to access nested function globally in Python 2.7

Question: I'm trying to find a way to access the confirmpath() function in the pathcond() function. Please help.
PS. I just began learning Python about a week ago, so any help regarding my code brevity and improving my overall skills will be really appreciated.
Following is the code I need help with:
def name():
    global call
    call = raw_input("What is your name?\n")
    print("Hello " + call)

def game():
    global charchoose
    charchoose = raw_input("What will be your character " + call + ": Mage, Wizard or Knight?\n")
    print("You chose " + charchoose)

def path():
    pathchoose = raw_input("You are a " + charchoose + " who was walking down Tranversia and came across a three-way road. Which on will you choose? Land, Sea or Clouds\n").lower()
    def confirmpath():
        global confirmpath
        confirmpath = raw_input("You chose " + pathchoose + ". Are you sure you want to continue? Yes or No?\n").lower()
        pathcond()
    confirmpath()

def pathcond():
    while confirmpath == "no":
        path()
    if confirmpath == "yes":
        print("Good choice, you win!")
    else:
        print("Sorry, we didn't get that. Can you answer again, please?")
        confirmpath()

def ask():
    askplay = raw_input("Would you like to play a game? Yes or No?\n").lower()
    if askplay == "yes":
        game()
        path()
    elif askplay == "no":
        print("That's alright. Thanks for hanging out, though. Bye!")
    else:
        print("Sorry, I didn't get that. Please try again.")
        ask()

name()
ask()

UPDATE:
I worked further on the program for sometime and ended up with a version that is now problem free. I've posted it below, please help me make it better by suggesting what I could change/improve/remove. The code is as follows:
def Initiate():
   global call
   call = raw_input("What is your name?\n")
   print("Hello " + call)
   begin()

def game():
   global charchoose
   charchoose = raw_input("What will be your character " + call + ": Mage, Wizard or Knight?\n")
    print("You chose " + charchoose)
    path()

def path():
    global pathchoose
    pathchoose = raw_input("You are a " + charchoose + " who was walking down Tranversia and came across a three-way road. Which on will you choose? Land, Sea or Clouds\n").lower()
    confirmpath()

def confirmpath():
    global confirmpaths
    confirmpaths = raw_input("You chose " + pathchoose + ". Are you sure you want to continue? Yes or No?\n").lower()
    pathcond()

def pathcond():
    while confirmpaths == "no":
        path()
    if confirmpaths == "yes":
        print("Good choice, you win!")
    else:
        print("Sorry, we didn't get that. Can you answer again, please?")
        confirmpath()

def begin():
    askplay = raw_input("Would you like to play a game? Yes or No?\n").lower()
    if askplay == "yes":
        game()
    elif askplay == "no":
        print("That's alright. Thanks for hanging out, though. Bye!")
    else:
        print("Sorry, I didn't get that. Please try again.")
        ask()

Initiate()

UPDATE 2: The code functions properly but still ends up printing the following string numerous times
if confirmpaths == "yes":
    print("Good choice, you win!")

I observed that it prints the string as many times as I reply to the confirmpath() function, regardless of whatever my response is.
Comment: Why are you defining `confirmpath()` inside `path()` to begin with? Just define it at the global scope.
Comment: Yes, do it outside the  path() function
Comment: Re Update 2: `while confirmpaths` should be changed to `if confirmpaths`
Answer: In essence, you're trying to create a Finite State Machine. In Python, this is probably best implemented using a class. Here's a similar example that may be useful.
The important part about a class is that it can keep track of the data in your game and allows you to avoid global variables. Here's your program converted to a class.
class Game:
    def __init__(self):
        self.name = raw_input("What is your name?\n")
        print("Hello " + self.name)
        self.ask()

    def ask(self):
        askplay = raw_input("Would you like to play a game? Yes or No?\n").lower()
        if askplay == "yes":
            self.game()
        elif askplay == "no":
            print("That's alright. Thanks for hanging out, though. Bye!")
        else:
            print("Sorry, I didn't get that. Please try again.")
            self.ask()

    def game(self):
        self.charchoose = raw_input("What will be your character " + self.name + ": "
            "Mage, Wizard or Knight?\n")
        print("You chose " + self.charchoose)
        self.path()

    def path(self):
        pathchoose = raw_input("You are a " + self.charchoose + " "
            "who was walking down Tranversia and came across a three-way road. "
            "Which on will you choose? Land, Sea or Clouds\n").lower()
        self.confirmpath(pathchoose)

    def confirmpath(self, pathchoose):
        confirmpaths = raw_input("You chose " + pathchoose + ". "
            "Are you sure you want to continue? Yes or No?\n").lower()
        self.pathcond(confirmpaths, pathchoose)

    def pathcond(self, confirmpaths, pathchoose):
        if confirmpaths == "no":
            self.path()
        if confirmpaths == "yes":
            print("Good choice, you win!")
        else:
            print("Sorry, we didn't get that. Can you answer again, please?")
            self.confirmpath(pathchoose)

Game()

When Game() is called, an object (an instance) is created. All of the instance methods in the class refer to self which is the name of this instance.
While this may seem like a bit much, classes can be very useful and are a good concept to get familiar with.
Answer: You got some issues here, I'll fix them for you.
def name():
    global call
    call = raw_input("What is your name?\n")
    print("Hello " + call)

def game():
    global charchoose
    charchoose = raw_input("What will be your character " + call + ": Mage, Wizard or Knight?\n")
    print("You chose " + charchoose)

def path():
    pathchoose = raw_input("You are a " + charchoose + " who was walking down Tranversia and came across a three-way road. Which on will you choose? Land, Sea or Clouds\n").lower()
    confirmpath(pathchoose)

def confirmpath(pathchoose):
    confirmpath_var = raw_input("You chose " + pathchoose + ". Are you sure you want to continue? Yes or No?\n").lower()
    pathcond(confirmpath_var)

def pathcond(confirmpath_var):
    while confirmpath_var == "no":
        path()
    if confirmpath_var == "yes":
        print("Good choice, you win!")
    else:
        print("Sorry, we didn't get that. Can you answer again, please?")
        confirmpath()

def ask():
    askplay = raw_input("Would you like to play a game? Yes or No?\n").lower()
    if askplay == "yes":
        game()
        path()
    elif askplay == "no":
        print("That's alright. Thanks for hanging out, though. Bye!")
    else:
        print("Sorry, I didn't get that. Please try again.")
        ask()

name()
ask()

Explanation:
First off, just put your functions on the global scope because in this context it doesn't make sense to do what you are doing (defining a function within a function) if you are calling that inner function in different places.  Secondly, instead of using global variables, pass variables into functions.  Using global variables that functions use is not good practice and leads to spaghetti code and shadow variables Why are global variables evil?.  Use the parameters of functions to pass values into it.
I tested the code above, it works.
Comment: The code still give me an error whenever I purposely try to create a situation to execute the else condition in the pathcond(confirmpath_var) function.


Change of Variable for Finding Total Photon Number Density

Question: I am doing physics work, but I must be overlooking something very obvious with my mathematics. I have an integral that is easier to solve by change of variable. However, when I change the variable, I get a negative sign that doesn't vanish, so my final solution is negative (which doesn't make sense in this context, because my solution is strictly positive). I must be making a mistake. Here is my work:
$$N = \int_{0}^{\infty}\frac{8\pi}{\lambda^{4}}\frac{1}{e^{hc/\lambda kT}-1}d\lambda$$
I set:
$$x = \frac{hc}{\lambda kT}$$
This means:
$$\lambda = \frac{hc}{xkT}$$
and
$$d\lambda = -\frac{hc}{x^{2}kT}dx$$
I make this substitution:
$$N = \int_{0}^{\infty}\frac{8\pi}{\left(\frac{hc}{xkT}\right)^{4}}\frac{1}{e^{x}-1}\left(-\frac{hc}{x^{2}kT}\right)dx$$
This simplifies to:
$$N = -8\pi\left(\frac{kT}{hc}\right)^{3}\int_{0}^{\infty}\frac{x^{2}}{e^{x}-1}dx$$
At least, I still have the negative sign. It should be positive, as the integral is the Riemann Zeta function and it evaluates numerically as a positive number (2.4 to be exact). The negative sign messes this calculation up, as my number N should be positive.
Can anyone spot where I may or may not have made an arithmetic error? Thanks.
Comment: You can get the parentheses (or any other pair of delimiters) to adjust to the size of their content by preceding them with `\left` and `\right`.
Answer: You forgot to change the bounds of the integral when you made the substitution. Correcting that will cancel the pesky negative sign.
Comment: I knew it was something obvious. I appreciate the quick response!


Statistical test for the difference in mean for two normal distributions

Question: I have measured $x$ and $y$ and estimated their uncertainty. They are both distributed normally. I found $x = 5 \pm 0.25$ and $y = 7 \pm 0.5$.
I want to know if these estimates are statistically different. Is it as simple as calculating $\sigma = |5 - 7|/(0.25 + 0.5) = 2.666...$, and hence (using R) $P(z > \sigma) = {\tt 1-pnorm(2.666)}\simeq 0.0038$?
Or should it be: $\sigma = |5 - 7|/\sqrt{0.25^2 + 0.5^2} \simeq 3.57$, and hence $P(z > \sigma) = \simeq 0.000178$?
Answer: It sounds like you've measured two samples and want to hypothesis test if they are different from each other. In which case, use chi-squared test if population standard deviation is known (unlikely), in R it's chisq.test. Or if population standard deviation is unknown (very common) then use the t test instead. In R it's just t.test(vector1, vector2). If you go with the T test then your null hypothesis is $H_0:\bar{X_1}=\bar{X_2}$ and the aletnaritve is taht they are not equal. Your formula is very close, but it's
$$\frac{\bar{X_1}-\bar{X_2}}{S_p\sqrt{\frac{1}{n_1}+\frac{1}{n_2}}}$$
where
$$S_p=\sqrt{\frac{S^2_1(n_1-1)+S^2_2(n_2-1)}{n_1+n_2-2}}$$
$S_1$ and $S_2$ are just the sample standard deviations which you have already figured out. And then you got to look it up on a T test table with degrees of freedom$=n_1+n_2-2$ If you know the standard deviation then the chi squared test uses $\sigma$ instead of estimating it with $S_p$ and you look it up on the chi squared table. Again, r has all this, but you wrote a lot of maths so i thought I'd write this here just in case.
If you wanted to know how to add and subtract normal distributions from a pure maths perspective then look here. Note that they have to be independent, otherwise there's a different way to work it out (which i can link further, but leave a comment). Sorry if I've missed your point.
Comment: Thanks. What are $n_1$ and $n_2$? It sounds like it might be the number of measurements for each, but I only have one measurement of each. (For example, if I have used two different rulers to measure the length of a table.) This leads to $n_1=n_2=1$ and thus $n_1+n_2-2 = 0$ and hence division by zero.
Comment: Yeah n is just the number of observations per group. But how did you get variance of+-0.5 and 0.25 if you only had one measurement?
Comment: just one more thought, the example with the rulers doesn't need really stats, they're just two different measurements you know they're different. *unless*, you have multiple measurements using two rulers which introduces some sort of measurement *error* and hence variability. If you wanted some sort of error bars around your difference, you can get that using the t test, it's called a confidence interval. $\bar{X_1}-\bar{X_2} \pm t_\frac{\alpha}{2}S_p\sqrt{\frac{1}{n_1}+\frac{1}{n_2}}$ where $t_\frac{\alpha}{2}$ is just the critical T value you got from your test.
Comment: Also, another thing, the T test I've written down is when the groups have equal variance but looking more closely at your question they're not the same, you should really look at the links for when groups have difference variance and other violated assumptions. Probably the Welch T test is what you should use (don't worry, it's the default in `R` anyway). But I'm not sure how to compare different samples when samples are literally 1--i don't know that it can easily be done.
Comment: The uncertainty from the ruler comes from the fact that the ruler doesn't have infinite precision. For example if I measure the table using a meter stick, the best resolution I can get is (say) 1cm. So from a single measurement I obtain something like 0.5 m +/- 1 cm. This is my situation.


What's behind Excel Solver Evolutionary?

Question: I have an optimization problem on Excel, using Evolutionary algorithm.
Works fine, but i'd like to understand how it gets to the solution, ie what is or are the exact method(s) used.
Is that available anywhere ?
The final purpose being to move this project from Excel to a Java program, because it gets more and more complex.
Thank you
Answer: Do the same optimization in LibreOffice Calc. Algorithms done in LibreOffice Calc are available as part of the open-source project.


Which of the two approaches to routing a module settings page is the best practice?

Question: There seems to be two ways to link a route to a settings form for a module. I'm curious as to whether one is considered a better practice, and why.
<code>_controller: '\Drupal\mymodule\Controller\MyController::myMethod'
</code>
or
<code>_form: '\Drupal\mymodule\Form\mySettingsFormFile
</code>
Comment: Without knowing what is in myMethod() this would be the second one. The extra custom controller class only makes sense if you do something in myMethod() the form controller invoked by `_form` is not able to do.
Comment: Makes sense. Would you mind pasting your comment as an answer, so I can select it? Thanks!
Answer: Without knowing what is in the controller this would be the second one. The extra custom controller class only makes sense if you do something in myMethod() the form controller invoked by _form is not able to do.
See https://www.drupal.org/node/2117411#fapi-in-route
This integrates the form in a request so that it can receive route parameters and the request itself as well as returning a response if necessary.


PF OpenBSD states

Question: We have an OpenBSD server used as firewall using the famous pf. The firewall is connected to the Internet form one side and to a local network form the other.
we are experiencing a connection outage due to the fact that the pf is attaining its maximum number of states (which is 20000), this happens for less than hour then thinks goes back to normal.
Is there anyway of determining the hosts that are opening these states.
Does increasing the number of states in pf.conf helps?
Thanks a lot
Answer: There are a number of things you can do here.
To see which hosts are responsible for the large number of state table entries you can do pfctl -vs state.
To add more state table entries you can do what you suggested (set limit states to a bigger number), but if there is an underlying issue you probably don't want to do that.
You can also consider adjusting the state timeout values (set timeout), possibly using adaptive timeouts, in order to get rid of old/stale states more quickly.
See the manpage for pf.conf and the manpage for pfctl for more information
Answer: [Ref: Hitting the PF state table limit]
The PF State tables set the limit of connections that have been authorized, and thus limit the number new connections that the firewall will accept. You may have excess bandwidth available, but if there is no free capacity in the State Tables, then your firewall becomes a bottle-neck.
The configured limits for state information is accessible through pfctl:
# pfctl -sm
states        hard limit    10000
src-nodes     hard limit    10000
frags         hard limit     5000
tables        hard limit     1000
table-entries hard limit   200000

The above limits pre-sets the allocated memory of the defined structures, such that they are always available, and it also limits growth of the said data structures. If your firewall traffic exceeds the above settings, then performance will be affected.
It is now important to monitor the effects of your traffic on the counters for the above limits. The generic -si output gives us clues to where to further investigate potential bottle-necks in our firewall.
# pfctl -si
Status: Enabled for XXXXXXXXXXXXXXXX          Debug: Urgent

State Table                          Total             Rate
  current entries                       34
  searches                        96379206           15.2/s
  inserts                           726196            0.1/s
  removals                          726162            0.1/s

On the above gateway, connected to two infrequently used laptops,
the current entries is very low relative to the hard limit 10000 above. Obviously, the current entries will fluctuate due to use,
and on a busier gateway may fluctuate significantly.
[Ref: Hitting the PF state table limit,
Open BSD state hard-limit reached]
An important counter to monitor from pfctl -si is the memory
counter. The same details should be available through systat pf.
From an active gateway linking our 6 sites, we get the following from a standard install, no modification to state tables.
# pfctl -si | grep memory
  memory                          209230            0.1/s

The counter highlights how often PF has failed at least one of the pool(9). The higher the number, the higher the frequency of incidences where packets arriving at the firewall have most likely been dropped due to one of the hardware limits.
Our above example shows 209,230 times the memory limit was hit.
The next review is to check with Kernel memory allocations, using vmstat. To narrow our search down to the effects on the pf state table we check the entry for pfstatepl.
Below, we grab the lines with state or Fail (so we can get the column headers)
# vmstat -m | grep -E "state|Fail"
Name      Size  Requests  Fail   InUse Pgreq Pgrel Npage Hiwat Minpg Maxpg  Idle
pfstatepl  296  213123877 209235  5075  1050     0  1050 1050     0   2308   526
pfstatekeypl
pfstateitempl

pfstatepl is the label for memory allocated for the struct pf_state (/usr/src/sys/net/pf_ioctl.c) The failures do seem to be significant.
pfctl -vvsi | grep congestion

PF OpenBSD states


How to check who created VM and other resources in GCP?

Question: I believe this used to be the actor key, but I no longer see this in the logs in Stackdriver.
https://cloud.google.com/logging/docs/view/overview
How can I find which account provisioned a given resource?
Comment: I still see "actor". Perhaps you can expand your question with how you are creating a GCE VM instance, what you are seeing in Stackdriver and what you expected to see. You can also use `protoPayload.authenticationInfo`.
Comment: This is available via the Stackdriver logging page or via the activity logs (Home -> Activity tab)
Answer: You can access to all activity in the activity tab, in the home page of your project. But it's very manual
One of the best practice is to use Stackdriver logs. And especially to create a sink of the logs that you want to oversee into BigQuery. Indeed the audit log info are kept only 13 months (400 days exactly) and you could want to perform search above this limit.
And it's very interesting because you can perform these sink at folder or organisation level.
Finally, having data into BigQuery allow you to script your search/warning by simply query your table.
More information here
Comment: I prefer built in product. It's easier and cheap. But you can you the stack that you prefer for the analytics.
Comment: so you'd use Stackdrivers, BigQuery instead of something like ELK stack?


Why I can not use inline function in component prop? Can you explain in detail by giving an example? What means saying losing all state?

Question: Note: The component prop accepts component, not a render function. Don't pass an inline function (e.g. component={() => }), or your component will unmount and remount losing all state when the parent component re-renders. See Passing additional props for alternatives.
This warning from the simulator.
enter image description here
function HomeScreen(props: Object) {
  return (
    <Navigator initialRouteName="Empty1">
      <Screen
        name="Empty1"
        component={() => {
          return (
            <View>
              <Text>Example Text</Text>
            </View>
          );
        }}
      />
      <Screen name="Home1" component={HomeScreen1} />
    </Navigator>
  );
}

Comment: "What means saying losing all state?" Do you know what "state" is in the context of a React app? Because if not, I suggest starting with the [basic tutorials](https://reactjs.org/tutorial/tutorial.html).
Answer: It's warning you that component is going to be re-rendered every time screen is re-rendered. This is because every time the component arg is evaluated it returns a fresh inline function. (the prop changes every time thus it must always re-render)
Evaluation of the same inline function twice yields different objects.
Eg.
let funcs = []
for (let i =0 ; i<2; i++) {
  funcs.push(() => 1)
}
funcs[0] == funcs[1]
>>> false

You can wrap this is useCallback to get a stable function that only updates when it needs to (never in your case since it captures no state). More on hooks here
function HomeScreen(props: Object) {
  let component = useCallback(() => {
    return (
      <View>
        <Text>Example Text</Text>
      </View>
    );
  }, [] // no dependencies. This lambda will only be evaluated once.
  );
  return (
    <Navigator initialRouteName="Empty1">
      <Screen
        name="Empty1"
        component={component}
      />
      <Screen name="Home1" component={HomeScreen1} />
    </Navigator>
  );
}

Or since this function doesn't depend on anything stateful you could also just declare it globally at the top of this file.
let component = () => {
    return (
      <View>
        <Text>Example Text</Text>
      </View>
    );
  };

function HomeScreen(props: Object) {
    return (
    <Navigator initialRouteName="Empty1">
      <Screen
        name="Empty1"
        component={component}
      />
      <Screen name="Home1" component={HomeScreen1} />
    </Navigator>
  );
}

Answer: You need to understand what is hiding behind JSX syntax.
When you use <SomeComponent/> it is added to the React Virtual DOM and exists there until the tree is changing and component has to be unmounted. It survives rerenders, the DOM is updating, but component lives.
When you use () => <SomeComponent /> this component is a new object on every rerender of the parent. If it has state (via setState hook) it will be reinitialized. If it has some code in useEffect(() => {}, []) hook it will be called again.


Transitive group action in cube and icosahedral group

Question: There are two claims:

A group of symmetries of a cube acting on vertices have only 1 orbit, so vertices of a cube has transitive action
The action of icosahedral group is transitive on the vertices

Shouldn't the orbit be the number of vertices of cube or icosahedron? So the action of group of symmetries of a cube on its vertex has 8 orbits and the action of icosahedral group on its vertex has 12 orbits. I think I probably misunderstand something here. When will the # of orbit be 1 and when will the # of orbit be the number of vertices?
Comment: You need to keep in mind that an orbit is a set and not a number. In this case, the orbit is the set of those vertices. You seem to be confusing the orbit with the cardinality of an orbit.
Comment: @Chris Thx! That makes so much more sense
Comment: Does this make the answer to the questions in your last sentence clear, or would you like me to elaborate?
Comment: @Chris Yes it's very clear now! No you don't need to elaborate any further.
Answer: The orbit of a given vertex, say $v\in V$, is by definition the set of vertices $v$ can be brought to upon the action of the group of symmetries. If the action is transitive, then any vertex can be brought to any other one (by possibly more than one symmetry): there is one orbit, only, whose size is $|V|$.


Combine 2 DFAs to produce a new DFA that accept L1 U L2

Question: I am trying to solve a problem where i have to create a new DFA that accept $L_1 \cup L_2$ where $L_1 = \{0^{3i} 1^{3j+1} 0^{3k+2} \mid i \in \mathbb{N}, j \in \mathbb{N},k\in \mathbb{N} \}$ and $L_2 = \{0^{2i} 1^{2j+1} 0^{2k} \mid i\in \mathbb{N},j\in \mathbb{N},k\in \mathbb{N} \}$.
I created 2 seperpate DFAs for each of them so far but I don't know how I should union those 2 DFA.
This is for L1: https://i.stack.imgur.com/MSSYH.png1
L2: https://i.stack.imgur.com/YCC9Q.png2
Any help is appreaciated.
Comment: Do you know the procedure for converting an NFA to a DFA?  One possible approach would be to combine the two DFAs into an NFA and then convert that into the final DFA.
Answer: Use the product construction:
If $M_1=(Q_1, \Sigma, \delta_1, q_{01}, F_1)$ accepts $L_1$ and $M_2=(Q_2, \Sigma, \delta_2, q_{02}, F_2)$ accepts $L_2$, then create a third DFA $$M_3=(Q_1\times Q_2, \Sigma, \delta_3, (q_{01}, q_{02}), F_3)$$
where $\delta_3((q_1,q_2), a)=(\delta_1(q_1,a),\delta_2(q_2,a))$ and $F_3=(F_1\times Q_2)\cup(F_2\times Q_1)$.
In plain English, create a new DFA that has a state for each pair of states in the original two DFA's (one state from each). The transition function will take a pair of states, see where the next state would be for each, and then transition to that pair of states. The accepting states are the pairs of states such that one of the states is an accepting state in one of the original DFA's.


Centos 6.3 install reiserFS support

Question: I'm trying to change an existing ext4 partition to reiserFS in Centos 6.3 64bit.
I've updated the kernel to Centos Plus:
First, I've updated /etc/yum.repos.d/CentOS-Base.repo:

In the [centosplus] section:
enabled=1
includepkgs=kernel*

Then I ran yum ypdate and my Kernel was updated to Centos Plus:
[root@vappsil disk]# uname -r
2.6.32-279.11.1.el6.centos.plus.x86_64

Then, I've added this to /etc/yum.repos.d/CentOS-Base.repo

into the [centosplus] section:
includepkgs=kernel* jfsutils reiserfs-utils

into the [base] and [updates] section:
includepkgs=kernel* jfsutils reiserfs-utils

But when trying to execute:
yum install reiserfs-utils

I get:
No package reiserfs-utils available.

How can I install the reiserFS-utils package to create a reiserFS partition?
Comment: Why? Do you want to kill your files?
Comment: It's a killer filesystem, but not in a good way.
Comment: Why? Are you trying to use Reiser to solve a particular problem?
Comment: I have a slow database performance, simple INSERT queries takes much more time on my own server than on a simple GoDaddy Centos 5.8 32bit server. I've seen that the database files on the GoDaddy server are on a reiserFS file system. Do you have any idea what can be the problem ? Or how can I tune the ext4 file system to Database performance ?
Answer: Don't do it. ReiserFS is not regarded as a good filesystem option these days and may not be under active development.
You have several other solid filesystem options here in 2012. Are you trying to solve a particular problem? If so, XFS, btrfs, maybe even tuning of your ext4, may be better ideas for supportability and compatibility.
Comment: @PeterTeoh it would be a bad business and technical decision to deploy a filesystem like Reiser *today*. No mainstream support, shaky mindshare and is a solution to a problem that other filesystems have fixed. Also, the OP [found their solution](http://serverfault.com/questions/443134/centos-6-3-install-reiserfs-support/443137?noredirect=1#comment479456_443137) in this answer.
Comment: Using ReiserFS sounds good, but the support these days will kill you.
Comment: @Alon_A There are some filesystem tuning steps that could make a difference. I'd like to refer you to [my answer to this question](http://serverfault.com/questions/430955/openfiler-iscsi-performance/431112#431112), or advise you to open a new question on how to tune your database's FS performance. With RHEL 6.x, your biggest gain will come from changing the I/O scheduler to `deadline`.
Comment: It seems like installing the `tuned-utils` and changing the profile to  `virtual-host` solved the performance issue. Event without installing the Murder's file system ;0).... THANKS A LOT for the help !!! We were looking for a solution for almost 2 months !
Comment: I have a slow database performance, simple `INSERT` queries takes much more time on my own server than on a simple GoDaddy Centos 5.8 32bit server. I've seen that the database files on the GoDaddy server are on a reiserFS file system. Do you have any idea what can be the problem ? Or how can I tune the ext4 file system to Database performance ?
Comment: The answer seemed really weird.   The OP is asking for a solution, and the answer was not to use ReiserFS?   Having experiencing ext2, ext3, ReiserFS (10+years), and lately ext4 - none has the speed and robustness of Reiserfs.    Till today, ext4 still has the problem of not being able to free up space even though I had deleted lots of files.   Overall Reiserfs is still among the best.
Comment: @RobM I have no need for ReiserFS support since 10+years of using  it, instead, ext4 all the time is giving me problems, (eg, yesterday), and I am hardly can find support, or have to go a long distance to find support.
Answer: First of all, let me respond to the ReiserFS naysayers:
a) ReiserFS3 is a stable, fast, space-efficient (specially with lots of small files),  reasonably maintained (just check the kernel changelogs) and extremely robust filesystem: I've used ReiserFS in all my servers (a few dozen of them) since 2001 or so and it has never given me any trouble. In fact, in a client of mine with constant electrical power interruptions, they repeatedly had to restore EXT4-based machines from backups because the entire filesystem was frequently hosed beyond fsck repair, but the CentOS servers we configured for them almost 4 years ago (using ReiserFS3 of course) have never ever lost any data (and just keep on going to this day). I've noticed reader-writer-consistency problems with some of the more modern kernels (2.6.37 comes to mind), but with all stable 2.6.x kernels up to and including 2.6.32, ReiserFS3 runs solidly as a rock.
b) Of course what Hans Reiser did is wrong, and I for one am glad he's in prison paying for his crime. But an idea isn't responsible for the acts of its creator... Or would anyone seriously propose that Hans Reiser's murder of his wife is in any way connected with the ReiserFS filesystem?
c) The OP requested a solution to run ReiserFS on his CentOS server, not a lecture on the merits of other filesystems and/or the demerits of Mr. Hans Reiser, so I think we would all do a lot better if we just stick to the matter at hand.
That said, here's the solution the OP asked for:
1) Add the ElRepo repository to your YUM configuration: just follow the directions at the "Get Started" section of the ElRepo site.
2) Run "yum update" to pull in repo metadata about the available packages;
3) Run "yum install kmod-reiserfs reiserfs-utils"; that way you will install both the kernel module and the needed userland utility programs (mount, mkfs, fsck, etc).
Done!
Comment: +1 for the impassioned defense of Reiser. However, the OP's performance problems are a result of the new kernel scheduling algoritms in the 6.x release of Red Hat/CentOS. Filesystem choice was irrelevant at this point. Furthermore, I would not advocate deploying a dying or dead filesystem because of long-term stability and support concerns. There are indeed better options out there.
Answer: ReiserFS does not appear to be supported at all in RHEL 6 / CentOS 6. No such package exists in the CentOS repositories, nor is filesystem support available in the kernel.
Answer: Use centos plus repo to obtain kernel-plus RPM, then install reiserfs-util RPM from elrepo which seems latest. Now you can mount/mkfs reiserfs.

Centos 6.3 install reiserFS support


Free Actions of Finite Groups on Surface of Genus $2$

Question: Let $\Sigma_2$ be the orientable surface of genus $2$.  I am trying to show that if $G$ is a finite group that acts freely on $\Sigma_2$, then $G$ has order $1$ or $2$. My first thought is that, we would then get a finite cover $\Sigma_2 \to \Sigma_2/G$. If I can show that $\Sigma_2/G$ must also be a surface of genus $g$, then I get that $g = 1$ or $g = 2$, and I'm done. But, I don't have any result that says that $\Sigma_2$ doesn't cover anything that isn't $\Sigma_1$ or $\Sigma_2$. I am answering this question in the confines of a first class in algebraic topology that includes fundamental group, covering spaces, and homology (chapters $0$, $1$, and $2$ of Hatcher). Any help is appreciated.
Answer: The following relation is verified: $e(\Sigma_2)=|G|e(\Sigma_2/G)$ where $e(\Sigma_2)$ is the Euler characteristic. Since $e(\Sigma_2)=-2$, we deduce that $|G|$ divides $2$ and $G=1$ or $\mathbb{Z}/2$.
Euler characteristic of covering space of CW complex
Comment: This is a great answer.  I am helping some students study for their qualifying exam.  If they don't know this formula, it will be a great way of introducing it to them.
Answer: The trouble is that it is false that only order 1 and 2 groups act on $\Sigma_2$.
Perhaps you intended your question to have  a stronger hypothesis, namely by requiring the action to be free, and then the Euler characteristic arguement given by @TsemoAristide gives the answer.
But if you intended your question to be as stated, without a hypothesis that the action is free, then there are several other finite groups that can act. For example, gluing opposite sides of an octagon gives $\Sigma_2$, and the symmetry group of the octagon therefore acts, which is a dihedral group of order 16. Also, gluing opposite sides of a decagon gives $\Sigma_2$, with an action of a dihedral group of order 20. There are still more, arising from orbifold quotients of $\Sigma_2$.
Comment: I said "free" in the title, so didn't add it to the post.  I will edit to do that now. But, have an upvote for the neat group actions.


Is an array of an object stored in stack or heap?

Question: In the following code:
#include <iostream>
using namespace std ;

class TypeA {
 public:
  int a[10] ;
  TypeA () {
    int i ;
    for ( i = 0; i != 9; i++) {
      a[i] = double(i) ;
    }
  }
  void printVal() {
    int i ;
    for ( i = 0; i != 9; i++) {
      cout << a[i] << endl ;
    }
  }
  ~TypeA() {
    //delete[] a;
    cout << "TypeA destructor called"<<endl;
  }

} ;

int main() {
  TypeA * ptrA = new TypeA() ;
  ptrA->printVal();
  delete ptrA ;

  return 0 ;
}

By new TypeA(), an object is instantiated on heap and a pointer is returned and kept in main(). I wonder if a[] of TypeA is stored on heap? If so, what is the appropriate way to free it ?
Comment: You don't need to free it - C++ puts everything into the Class'es memory .. so allocating a new TypeA gives space for the int[10] array within the memory space for the rest of class.  When you delete the Class, you are automatically freeing the memory that is used for the int[10] array.  No memory leak there at all ...
Comment: Can you explain what led you to such an impression (it's not, BTW)?
Answer: Generally unless your class contains pointers then the entire object is contained in one allocation. As such you don't need to do anything special to clear it.
You can only call delete[] on things you've previously called new[] on, and it must be exactly the same pointer you were given. Since the a property was never directly instantiated, calling delete on it is undefined behaviour.
The way new works conceptually isn't that exotic, it just allocates sizeof(X) bytes and calls the constructor on that object. new[] differs only in that it allocates sizeof(X) * N bytes and calls the constructor N times.
Comment: `new[]` also stores how many objects where allocated.
Answer: Try this code:
#include <iostream>
#include <type_traits>
#include <cassert>
struct A{
    A() {
        std::cout<<"Called A() for "<<std::hex<<this<<'\n';
    }
};

struct B {
    A arr[10];
    B() {
        std::cout<<"Called B() for "<<std::hex<<this<<'\n';
    }
};

int main() {
    B* ptr = new B;
    static_assert(std::is_standard_layout::value); //Sanity check for this example's case
    std::cout<<"Got ptr = "<<std::hex<<ptr<<std::dec<<" + sizeof(B)  = "<<sizeof(B)<<'\n';
    delete ptr;
    return 0;
}

Output is:
Called A() for 0x10d4eb0
Called A() for 0x10d4eb1
Called A() for 0x10d4eb2
Called A() for 0x10d4eb3
Called A() for 0x10d4eb4
Called A() for 0x10d4eb5
Called A() for 0x10d4eb6
Called A() for 0x10d4eb7
Called A() for 0x10d4eb8
Called A() for 0x10d4eb9
Called B() for 0x10d4eb0
Got ptr = 0x10d4eb0 + sizeof(B)  = 10

If you see the code and the corresponding output, you can correlate that the object ptr of type B is allocated on the heap at 0x10d4eb0 and it has a size of 10 (corresponding to 10 bytes, 1 byte each for the object A). So the memory address from 0x10d4eb0 till 0x10d4eb9 is all on the heap. And if you see the address of the objects of A, they all fall in this address range. Hence, the objects of A do lie in the heap memory area.
Now coming to how to handle arr, one needs to call delete/delete[], as the case may be, only on objects that have been allocated using new/new[]. Since that's not the case for arr, one doesn't need to call delete[] on it.


why do we need regularization when there is a lot of data

Question: I am reading the textbook Machine Learning - A Probability Perspective, and in Chapter 8 (which talks about logistic regression) there is a paragraph that says:

Just as we prefer ridge regression to linear regression, so we should prefer MAP estimation for logistic regression to computing the MLE. In fact, regularization is important in the classification setting even if we have lots of data. To see why, suppose the data is linearly separable. In this case, the MLE is obtained when $\lVert w \lVert \rightarrow \infty$ ,corresponding to an infinitely steep sigmoid function, $I(w^Tx > w_0)$, also known as linear threshold unit. This assigns the maximal amount of probability mass to the training data. However such a solution is very brittle and will not generalize well.

Could somebody explain why the MLE for logistic regression is obtained when $ \lVert w \lVert \rightarrow \infty$ and why this assigns the maximal amount of probability mass to the training data?
Comment: Do you know the meaning of $w$?
Comment: w is the weight vector in logistic regression. I have edited the post to show that the discussion is about logistic regression.
Answer: The key assumption here is that the data are linearly separable, meaning that there exists an $w_0$ such that $I(w_0^T x_i>0)=y_i$ for all $i=1,\cdots,n$. If this is the case, the MLE is ill-defined because $cw_0$ has higher likelihood than $w_0$ on the data if $c>1$, and hence the MLE must be $\|w_0\|\to\infty$.
However, keep in mind that MLAPP is from a firm Bayesian perspective, and as a frequentist I do not agree with this argument (that justifies the use of significant regularization for large data sets) at all :) From a frequentist perspective, if the logistic regression model is true then as the data size grows larger, it is less likely that the data are linearly separable at all. As a result, asymptotically speaking MLE is the most statistically efficient estimator in a logistic regression model with fixed dimension.
Comment: I see. Thanks a lot!


Logging Hardware Interrupts (IRQs) which are using 10-25% CPU

Question: I have a server using 10-25% of the CPU time on Hardware Interrupts according to Process Explorer.
How would I go about logging/diagnosing the cause of all these IRQ calls?
The machine is virtual, so I know the physical hardware is not the problem (although could be drivers, etc).
UPDATE:
Tried the information from this article:
http://msdn.microsoft.com/en-us/library/ms797921.aspx
Regarding using tracelog.exe and tracerpt.exe to capture DPC and ISR events, but when I run the trace it doesn't have any of that information, even with the -dpcisr switch. I get disk and process info in the report but no interrupts...
I know interrupts are happening because Process Explorer is still showing them using 6-15% CPU
Answer: KrView
Start a command promt -> go to the KRView folder
C:\Program Files\KrView\Kernrates>Kernrate_i386_XP.exe
And you get something like

Time   51354 hits, 25000 events per hit

Module                                 Hits       msec    %Tot  Events/Sec
--------                              -----      -----    ----  ----------
intelppm                              36726      64582    71 %    14216809
ntoskrnl                               6681      64582    13 %     2586246
hal                                    5246      64582    10 %     2030751
Ntfs                                    637      64582     1 %      246585
tcpip

After you press CTRL + C ( but leave it running for a while ) and this should give you a indication of where to look.
Now to track down more information regarding these drives, if you cannot guess who made the drives based on its name you can find it in your windows system folder ( tcpip would be the file tcpip.sys, right click on the file and you can see who signed it).
When searching on your favorite search engine for other people that might have simular problems i would start searching for the none microsoft once.
Be aware that the intelppm can be can be the root of your problem, but it will show very high in the list because it sends the sleep command to the cpu so its position in the output will be very high ( If you have a AMD CPU replace intelppm with a amd driver ).
As you may have noticed this does not point a nice arrow to your problem, it will still require some work from you to track down what to do with the problem is, but it should give your a help in what direction to focus you searching.
Comment: Alright how do I break down intelppm, ntkrnlpa, hal, etc into something I can match to a driver or other issue?
Comment: Updated reply with some more information
Comment: My highest user is intelppm, how do I go about determining if the problem lies within?
Comment: Like i updated my reply, there is a chance thats is because its sending sleep commands to the CPU.
But you have to search yourself a bit, i know when i did this on my server i knew there could be issues with intelppm and virtual machine 2k5 i belive.
Answer: Try this:
KrView
The XP version of KrView works on Vista, but you need to run it as Administrator.  Start a cmd shell as Administrator and run c:\program files\krview\kernrates\kernrate_i386_xp.exe while the hardware interrupt problem is occurring. Compare the results to when the problem is not occurring.  This will tell you which hardware drivers are hogging the CPU.
Comment: Again, "The machine is virtual, so I know the physical hardware is not the problem"
Comment: I used the kernview.exe from the Server 2003 resource toolkit (the machine is running '03), but I didn't understand how to get the information I needed from the wealth kernview offers.

Could you provide a few more steps to narrow it down to finding out what's calling the IRQs?
Comment: SOmtimes it happens that a broken device (HDD, IDE cable, even motherboard) makes lots of IRQ interrupts. KrView shows you which drivers use CPU the most, so you're able to determine the possible hardware issue.
Answer: Try this: Start, Settings, Control Panel, System, Device Manager, IDE, Primary IDE Channel Properties, Advanced Settings, Set both Transfer Modes to "DMA if available".


Location variables as factor or numeric?

Question: I have a data set where my observations are geographically referenced by longitude & latitude, as well as by township & range. If you're unfamiliar with township & range:
The land is divided into survey townships of roughly 36 square miles. This is done by establishment of township and range lines. Township lines run parallel to the baseline, while range lines are true meridians. (https://en.wikipedia.org/wiki/Public_Land_Survey_System)
I want to run two different configurations of a Random Forest model. One where I account for spatial autocorrelation by including longitude & latitude as predictors, and one where I use township & range for the same. The point is to develop two models of different "spatial resolution", where the one with longitude & latitude is the high-precision case and the one with range & township is the lower-precision case (this would in a way resemble a county-level fixed effect).
At the moment, I have both these variables encoded as numeric variables (I am using R). For longitude & latitude, the precision can be infinitely increased by increasing the number of decimals, so this seems reasonable.
However, range & township may only be integers (there's no such thing as township = 5.5). I have tried to encode them as integers, but this doesn't seem to make any difference, as R seems to treat them in the same manner as normal numeric variables. If I encode them as factors, the variable importance gets way more messy since each category acts as a dummy variable, and I am not sure whether it's "more correct" anyway.
My question is: Would there be any problems related to keeping the township & range variables as numeric in this case? If so, does anyone have any suggestions on how to store these variables in a different way?
PS, I have read this post: GLMM: Elevation as numerical or factor in model?, but since random forests are capable of modelling non-linear relationships, the accepted answer does not seem to be exactly what I'm after.
Answer: I think it will be reasonable to consider encoding township and ranges in a way other than simply treating them as integers. While it is safe to assume that RF are able to encapsulate non-linear relations, it will still be rather difficult to interpreter results from a integer encoding. In addition, spurious effects might be very prevalent. For example, if a relatively low-counts categorical level has an assigned numerical value that is close to the assigned numerical variable of high-counts categorical level, it will be probably pooled together with it even if they encode relatively different information; and that would be just due to the encoding, another (random) integer encoding might give something else.
Similarly, as you have correctly deduced, because township and range have high cardinality (i.e. they have many distinct variables) as well as they have an inherit hierarchy, using them directly as factors quickly becomes unwieldy. The main problems are: 1. We might overfit out data when concerned about the influence of very unusual/rare factors and 2. with thousands of factor levels is difficult to estimate the overall importance of a factor as a whole. Bonus problem: (3.) We might not respect the hierarchy among two level (e.g. in the UK, where the post-codes (e.g. EC1Y 8LX) have an outward code (EC1Y) and inward code (8LX) part, it makes little sense to analyse inward post codes in absence of outward post codes).
I would suggest looking into target encoding (Micci-Barreca (2001) A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems) (or other target aware encodings like the James-Stein Encoder or the M-Estimator encoding). The basic idea is that a discrete factor variable is replace by a (regularised) average of the response variable. Here is a quick example: if we model a response variable y and we have three options of a variable Sex: Female/Male/Other, each of them represent 53%, 46% and 1% of our sample respectively. We will then create a new "numeric version" of the variable Sex where Female will be replaced with the mean of y for Female correspondents, $\mu_{y;Female}$, Male will be replaced with the mean of y for Male correspondents $\mu_{y;Male}$ (or something a bit closer to the overall average of y, $\mu_y$ due to regularisation) and Other will be replaced with the mean of y for Other correspondents, $\mu_{y;Other}$  (or likely something even closer to $\mu_y$, due to even stronger regularisation as the proportion is smaller).
That and a bunch of other goodies can be found in the vtreat package that has a number of pretreatment step for data. They have a number of vignettes that touch upon a number of different variable pre-processing issues.
Side-note: There are other encoding schema like Binary Encoding (i.e. turn everything into integers and then make $p$ distinct variable where they hold the $p$ digits 0/1 required to encode the integer) and Feature Hashing (Weinberger et al. 2009 Feature Hashing for Large Scale Multitask Learning). I do not touch upon them here as variable importance and influence is even harder to interpreter in these use cases. They are mostly dimensionality reduction pre-processing steps.
Comment: Good references. I agree that it makes much more sense to treat numeric information that are, in reality, categorical as categorical. *Impact coding* is another approach which may or may not be redundant with your suggestions. It's certainly similar in spirit. http://www.win-vector.com/blog/tag/impact-coding/
Comment: Think of it this way: if we have a large number of samples in a subcategory $A$ probably $\mu_{y,A}$ is a good representation of what is really happening with $A$'s samples and indeed $A$ members' values for $y$ should close to $\mu_{y,A}$. On the other hand, if for a subcategory $B$ we have only a handful of members we are less willing to believe that the average $\mu_{y,B}$ is a good representation of what is really happening with members of $B$; we will therefore regularise the value of $\mu_{y,B}$ such that it is closer to the overall mean $\mu_y$.
Comment: We will therefore not "multiply but 0.53" but rather "pull" $\mu_{y;Female}$ towards the overall sample mean $\mu_{y}$ with less force than we would "pull" $\mu_{y;Other}$. In the reference provided: Micci-Barreca (2001) this can be first seen in Equation (3), here the force of the "pull" towards the sample mean $\mu_y$ is captured in $\lambda$. James-Stein estimators have essentially the same form too.
Comment: @user332577: You have the correct idea. Impact encoding is very similar to target encoding. The main difference is that with impact encoding we subtract the "overall sample mean, $\mu_y$, while with target encoding the mean is still there. As the mean difference between impact and target encoding is a level shift, they encode the same information. I have seen the terms "impact" and "target" encoding, used interchangeably. I think it is mostly an author preference. (I hope this clarifies your comment).
Comment: @usεr11852 Thanks for valuable input. I will have a look at the references you provided. Just one question right away: When you refer to regularisation in your example, do you mean that, for instance, the mean for `female` is multiplied by 0.53?


Should using MOV instruction to set SS to 0x0000 cause fault #GP(0) in 64-bit mode?

Question: This question is inspired by a Reddit question in r/osdev except that this question focuses on the SS register. One may say RTFM (ISA entry for MOV), but when this question comes up it can get varying answers even among OS developers.

Question: Should using the MOV instruction to set SS to 0x0000 cause a general protection fault #GP(0) in 64-bit mode? For example: If I am in 64-bit mode with a Current Privilege level (CPL) of 0, should I expect to see a #GP(0) with this code snippet:
NULL_SEL_RPL0  EQU 0
mov eax, NULL_SEL_RPL0         ; EAX = 0x0000 = NULL Selector with
                               ;     Requested Privilege Level (RPL) 0.
mov ss, eax                    ; Try to set SS with NULL selector 0x0000
                               ; Should this cause a #GP(0) fault?

What the Intel x86 Instruction Set Reference says about MOV is:

Operation
DEST ← SRC;
Loading a segment register while in protected mode results in special checks and actions, as described in the
following listing. These checks are performed on the segment selector and the segment descriptor to which it
points.
IF SS is loaded
    THEN
        IF segment selector is NULL
            THEN #GP(0); FI;
        IF segment selector index is outside descriptor table limits
        OR segment selector's RPL ≠ CPL
        OR segment is not a writable data segment
        OR DPL ≠ CPL
            THEN #GP(selector); FI;
        IF segment not marked present
            THEN #SS(selector);
            ELSE
                SS ← segment selector;
                SS ← segment descriptor; FI;
FI;
IF DS, ES, FS, or GS is loaded with non-NULL selector
THEN
    IF segment selector index is outside descriptor table limits
    OR segment is not a data or readable code segment
    OR ((segment is a data or nonconforming code segment) AND ((RPL > DPL) or (CPL > DPL)))
        THEN #GP(selector); FI;
    IF segment not marked present
        THEN #NP(selector);
        ELSE
            SegmentRegister ← segment selector;
            SegmentRegister ← segment descriptor; FI;
FI;
IF DS, ES, FS, or GS is loaded with NULL selector
    THEN
        SegmentRegister ← segment selector;
        SegmentRegister ← segment descriptor;
FI;

In particular this part:

IF SS is loaded
    THEN
        IF segment selector is NULL
            THEN #GP(0); FI;

Behaviour I expect: I am loading SS with a NULL selector (0x0000). I would presume from this documentation that I should get a #GP(0). On real hardware, VirtualBox, QEMU, and BOCHS the code snippet doesn't fault.
Observed behaviour: No fault occurs and the 64-bit code continues to execute as expected.
Why does the behaviour I expect differ from what the documentation seems to suggest?

Complete Example
To make this a Minimal Complete Verifiable Example that can test the code snippet in emulators/VMs and on real hardware I present the following code. For test purposes the test code below is being placed in stage 2 of a bootloader. Getting into long mode is non-trivial. The code creates a GDT; an IDT to cause all exceptions and IRQs to triple fault; disables interrupts on the PICs; flushed pending IRQs; enables paging; identity maps the first 2MiB of memory; enters 64-bit mode directly from real-mode. The 64-bit code snippet came from the code at the very bottom at the label longmode64:
stage2.asm:
STAGE2_OFS EQU 0x7e00          ; Origin point (VMA) of stage2
                               ; Offset form base of memory where stage2 starts
VIDEO_TEXT_ADDR       EQU 0xb8000
                               ; Hard code beginning of text video memory
ATTR_WHITE_ON_MAGENTA EQU 0x57 ; White on magenta attribute

EFLAGS_IF_BIT         EQU 9    ; Interrupt Flag (IF) bit = 9

org STAGE2_OFS                 ; Set origin point (VMA) of stage2
bits 16

; Stage2 Entry point
; Upon entry these have all been set:
;     Direction Flag (DF) = 0
;     DS=ES=GS=FS=0x0000
;     SS:SP = 0x0000:0x7c00

stage2:
    mov si, nolm_err           ; Default error message to long mode error
    call check_longmode        ; Is long mode available on this CPU?
    jz .error                  ; If not print error and stop
    mov si, noa20_err          ; Default error message to A20 enable error
    call a20_enable            ; Enable A20 line
    jz .error                  ; If the A20 line isn't enabled then print error and stop
    mov edi, PAGING_BASE_ADDR  ; DS:EDI set to 4KiB aligned memory address 0x0000:0x1000
    jmp switch_longmode_64     ; Switch to 64-bit mode and
                               ;     and continue at label 'longmode64_entry'

.error:
    call print_string          ; Print error message
.end:
    cli                        ; Disable interrupts
.endloop:
    hlt                        ; Halt CPU
    jmp .endloop               ; Loop in case we get an NMI (non-maskable interrupt)

; Function: check_longmode
;           Check if long mode is available on the CPU
;
; Inputs:   None
; Clobbers: EAX, ECX
; Returns:  Zero Flag (ZF) set if CPU support long mode

check_longmode:
    call check_386
    jz .nolongmode

    ; Check whether CPUID is supported or not. If we can successfully
    ; flip bit 21 in EFLAGS then CPUID is supported.
    pushfd
    pop eax                    ; Get current EFLAGS
    mov ecx, eax               ; ECX = copy of original EFLAGS
    xor eax, 1<<21             ; Flip bit 21
    push eax
    popfd                      ; Set new EFLAGS

    pushfd
    pop eax                    ; ECX = updated EFLAGS
    push ecx
    popfd                      ; Restore original EFLAGS

    xor eax, ecx               ; Are any bits different between original and new EFLAGS
    jz .nolongmode             ;     If they are then CPUID is supported

    mov eax, 0x80000000        ; Get Highest Extended Function Implemented
    cpuid

    cmp eax, 0x80000001        ; Check support for at least Extended Function 0x80000001
    jb .nolongmode             ; If not, long mode not supported

    mov eax, 0x80000001        ; Get Extended Processor Info and Feature Bits
    cpuid
    test edx, 1 << 29          ; Test if the LM bit is set
    jz .nolongmode             ;     If not set then long mode isn't supported
    ret                        ; Otherwise long mode is supported return with ZF = 1
.nolongmode:
    xor eax, eax               ; Return with ZF = 0
    ret

; Function: print_string
;           Display a string to the console on display page 0
;
; Inputs:   SI = Offset of address to print
; Clobbers: AX, BX, SI

print_string:
    mov ah, 0x0e               ; BIOS tty Print
    xor bx, bx                 ; Set display page to 0 (BL)
    jmp .getch
.repeat:
    int 0x10                   ; print character
.getch:
    lodsb                      ; Get character from string
    test al,al                 ; Have we reached end of string?
    jnz .repeat                ;     if not process next character
.end:
    ret

; Function: wait_8042_cmd
;           Wait until the Input Buffer Full bit in the keyboard controller's
;           status register becomes 0. After calls to this function it is
;           safe to send a command on Port 0x64
;
; Inputs:   None
; Clobbers: AX
; Returns:  None

KBC_STATUS_IBF_BIT EQU 1
wait_8042_cmd:
    in al, 0x64                ; Read keyboard controller status register
    test al, 1 << KBC_STATUS_IBF_BIT
                               ; Is bit 1 (Input Buffer Full) set?
    jnz wait_8042_cmd          ;     If it is then controller is busy and we
                               ;     can't send command byte, try again
    ret                        ; Otherwise buffer is clear and ready to send a command

; Function: wait_8042_data
;           Wait until the Output Buffer Empty (OBE) bit in the keyboard controller's
;           status register becomes 0. After a call to this function there is
;           data available to be read on port 0x60.
;
; Inputs:   None
; Clobbers: AX
; Returns:  None

KBC_STATUS_OBE_BIT EQU 0
wait_8042_data:
    in al, 0x64                ; Read keyboard controller status register
    test al, 1 << KBC_STATUS_OBE_BIT
                               ; Is bit 0 (Output Buffer Empty) set?
    jz wait_8042_data          ;     If not then no data waiting to be read, try again
    ret                        ; Otherwise data is ready to be read

; Function: a20_kbd_enable
;           Enable the A20 line via the keyboard controller
;
; Inputs:   None
; Clobbers: AX, CX
; Returns:  None

a20_kbd_enable:
    pushf
    cli                        ; Disable interrupts

    call wait_8042_cmd         ; When controller ready for command
    mov al, 0xad               ; Send command 0xad (disable keyboard).
    out 0x64, al

    call wait_8042_cmd         ; When controller ready for command
    mov al, 0xd0               ; Send command 0xd0 (read output port)
    out 0x64, al

    call wait_8042_data        ; Wait until controller has data
    in al, 0x60                ; Read data from keyboard
    mov cx, ax                 ;     CX = copy of byte read

    call wait_8042_cmd         ; Wait until controller is ready for a command
    mov al, 0xd1
    out 0x64, al               ; Send command 0xd1 (write output port)

    call wait_8042_cmd         ; Wait until controller is ready for a command
    mov ax, cx
    or al, 1 << 1              ; Write value back with bit 1 set
    out 0x60, al

    call wait_8042_cmd         ; Wait until controller is ready for a command
    mov al, 0xae
    out 0x64, al               ; Write command 0xae (enable keyboard)

    call wait_8042_cmd         ; Wait until controller is ready for command
    popf                       ; Restore flags including interrupt flag
    ret

; Function: a20_fast_enable
;           Enable the A20 line via System Control Port A
;
; Inputs:   None
; Clobbers: AX
; Returns:  None

a20_fast_enable:
    in al, 0x92                ; Read System Control Port A
    test al, 1 << 1
    jnz .finished              ; If bit 1 is set then A20 already enabled
    or al, 1 << 1              ; Set bit 1
    and al, ~(1 << 0)          ; Clear bit 0 to avoid issuing a reset
    out 0x92, al               ; Send Enabled A20 and disabled Reset to control port
.finished:
    ret

; Function: a20_bios_enable
;           Enable the A20 line via the BIOS function Int 15h/AH=2401
;
; Inputs:   None
; Clobbers: AX
; Returns:  None

a20_bios_enable:
    mov ax, 0x2401             ; Int 15h/AH=2401 enables A20 on BIOS with this feature
    int 0x15
    ret

; Function: a20_check
;           Determine if the A20 line is enabled or disabled
;
; Inputs:   None
; Clobbers: AX, CX, ES
; Returns:  ZF=1 if A20 enabled, ZF=0 if disabled

a20_check:
    pushf                      ; Save flags so Interrupt Flag (IF) can be restored
    push ds                    ; Save volatile registers
    push si
    push di

    cli                        ; Disable interrupts
    xor ax, ax
    mov ds, ax
    mov si, 0x600              ; 0x0000:0x0600 (0x00600) address we will test

    mov ax, 0xffff
    mov es, ax
    mov di, 0x610              ; 0xffff:0x0610 (0x00600) address we will test
                               ; The physical address pointed to depends on whether
                               ; memory wraps or not. If it wraps then A20 is disabled

    mov cl, [si]               ; Save byte at 0x0000:0x0600
    mov ch, [es:di]            ; Save byte at 0xffff:0x0610

    mov byte [si], 0xaa        ; Write 0xaa to 0x0000:0x0600
    mov byte [es:di], 0x55     ; Write 0x55 to 0xffff:0x0610

    xor ax, ax                 ; Set return value 0
    cmp byte [si], 0x55        ; If 0x0000:0x0600 is 0x55 and not 0xaa
    je .disabled               ;     then memory wrapped because A20 is disabled

    dec ax                     ; A20 Disable, set AX to -1
.disabled:
    ; Cleanup by restoring original bytes in memory. This must be in reverse
    ; order from the order they were originally saved
    mov [es:di], ch            ; Restore data saved data to 0xffff:0x0610
    mov [si], cl               ; Restore data saved data to 0x0000:0x0600

    pop di                     ; Restore non-volatile registers
    pop si
    pop ds
    popf                       ; Restore Flags (including IF)
    test al, al                ; Return ZF=1 if A20 enabled, ZF=0 if disabled
    ret

; Function: a20_enable
;           Enable the A20 line
;
; Inputs:   None
; Clobbers: AX, BX, CX, DX
; Returns:  ZF=0 if A20 not enabled, ZF=1 if A20 enabled

a20_enable:
    call a20_check             ; Is A20 already enabled?
    jnz .a20_on                ;     If so then we're done ZF=1

    call a20_bios_enable       ; Try enabling A20 via BIOS
    call a20_check             ; Is A20 now enabled?
    jnz .a20_on                ;     If so then we're done ZF=1

    call a20_kbd_enable        ; Try enabling A20 via keyboard controller
    call a20_check             ; Is A20 now enabled?
    jnz .a20_on                ;     If so then we're done ZF=1

    call a20_fast_enable       ; Try enabling A20 via fast method
    call a20_check             ; Is A20 now enabled?
    jnz .a20_on                ;     If so then we're done ZF=1
.a20_err:
    xor ax, ax                 ; If A20 disabled then return with ZF=0
.a20_on:
    ret

; Function: check_386
;           Check if this processor is at least a 386
;
; Inputs:   None
; Clobbers: AX
; Returns:  ZF=0 if Processor earlier than a 386, ZF=1 if processor is 386+

check_386:
    xor ax, ax                 ; Zero EFLAGS
    push ax
    popf                       ; Push zeroed flags
    pushf
    pop ax                     ; Get the currently set flags
    and ax, 0xf000             ; if high 4 bits of FLAGS are not set then
    cmp ax, 0xf000             ;     CPU is an 8086/8088/80186/80188
    je .error                  ;     and exit with ZF = 0
    mov ax, 0xf000             ; Set the high 4 bits of FLAGS to 1
    push ax
    popf                       ; Update the FLAGS register
    pushf                      ; Get newly set FLAGS into AX
    pop ax
    and ax, 0xf000             ; if none of the high 4 bits are set then
    jnz .noerror               ;     CPU is an 80286. Return success ZF = 1
                               ;     otherwise CPU is a 386+
.error:
    xor ax, ax                 ; Set ZF = 0 (Earlier than a 386)
.noerror:
    ret

; Function: switch_longmode_64
;           Switch processor to 64-bit mode directly from real mode
;           See: https://wiki.osdev.org/Entering_Long_Mode_Directly
;           - Enable Interrupts (IF=1)
;           - Enable paging
;           - Identity Map first 2MiB of memory with a large page
;             by setting up proper PML4, PDPT, and PD
;           - Disable interrupts on the Master and Slave PICs
;           - Flush any pending external interrupts
;           - Use LIDT to load an IDT record with size of 0 to force
;             all software and hardware interrupts to triple fault
;           - Jump to 64-bit mode at label `longmode64_entry`
;
; Inputs:   DS:EDI 4KiB aligned address where there is at least
;                  12KiB of physical memory available
; Clobbers: N/A
; Returns:  Jumps to label 'longmode64_entry', doesn't return

PAGE_PRESENT       EQU (1<<0)
PAGE_WRITE         EQU (1<<1)
PAGE_USER          EQU (1<<2)
PAGEDIR_SIZE_LARGE EQU (1<<7)
PAGING_STRUCT_SIZE EQU 3*4096  ; Size of memory area to hold PML4, PDPT, and PD
PAGING_BASE_ADDR   EQU 0x1000  ; Offset in first 64Kb that is the start of a 16KiB
                               ; region that can be used for a default paging tree
PML4_OFS           EQU 0x0000  ; Offset of PML4 table
PDPT_OFS           EQU 0x1000  ; Offset of Page Directory Pointer Table
PD_OFS             EQU 0x2000  ; Offset of Page Directory Table

switch_longmode_64:
    push dword 1<<EFLAGS_IF_BIT; Reset all the EFLAG bits to 0 except IF=1
    popfd

    ; Zero out the 12KiB buffer used for PML4, PDPT, PD.
    ; We are using rep stosd (DWORD) thus the count should be bytes / 4.
    push di                    ; Temporarily store DI
    mov ecx, (PAGING_STRUCT_SIZE/4)
                               ; Number of DWORDS to set
    xor eax, eax               ; Value to set 0x00000000
    rep stosd                  ; Zero the memory
    pop di                     ; Restore DI

    ; DI = 4KiB aligned address to base of paging structures
    ; Create Page Map Level 4 Table (PML4)
    lea eax, [di + PDPT_OFS]   ; EAX = address of Page Directory Pointer Table (PDPT)
    or eax, PAGE_PRESENT | PAGE_WRITE | PAGE_USER
                               ; Set present flag, writable and user flags
    mov [di + PML4_OFS], eax   ; Store the address the PDPT to the first PML4 entry

    ; Create the Page Directory Pointer Table (PDPT)
    lea eax, [di + PD_OFS]     ; EAX = address of Page Directory (PD)
    or eax, PAGE_PRESENT | PAGE_WRITE | PAGE_USER
                               ; Set present flag, writable and user flags
    mov [di + PDPT_OFS], eax   ; Store page directory address as the first PDPT entry

    ; Create Page Directory (PD)
    mov dword [di + PD_OFS], PAGE_PRESENT | PAGE_WRITE | PAGE_USER | \
                             PAGEDIR_SIZE_LARGE | 0 << 21
                               ; Set first PD entry to present, writable, user, and
                               ; large page. Identity map to the first 2MiB in
                               ; physical memory

    ; Disable IRQs on the Master and Slave PICs
    mov al, 0xFF               ; Bits that are 1 disable interrupts, 0 = enable
    out 0xA1, al               ; Disable all interrupts on Slave PIC
    out 0x21, al               ; Disable all interrupts on Master PIC

    ; Flush any pending IRQs
    mov ecx, 8
    ; Do a loop to allow pending interrupts to be processed.
    ; Execute enough instructions to process all 16 interrupts.
.irqflush:
    dec ecx
    jnz .irqflush

    lidt [idtr]                ; Load a zero length IDT so that any hardware
                               ;     interrupt or CPU exception causes a triple fault

    ; Enter long mode directly from real mode without entering compatibility mode
    movzx esp, sp              ; Zero extend SP to ESP
    mov eax, 10100000b
    mov cr4, eax               ; Set CR4 PAE and PGE bits on and other features off
    mov cr3, edi               ; Set CR3 to address of PML4 (@ 0x00001000)
    mov ecx, 0xC0000080
    rdmsr                      ; Read EFER MST to EDX:EAX
    or eax, 0x00000100         ; Set the LME bit
    wrmsr                      ; Write back changes to EFER MSR
    mov eax, cr0               ; Get current CR0
    or eax, 0x80000001         ; Enable both paging and protected mode bits
    mov cr0, eax               ; Update CR0
    jmp .flushipfq             ; This JMP is to flush instruction prefetch queue
.flushipfq:
    lgdt [gdtr]                ; Load gdt from gdtr
    jmp CODE64_PL0_SEL:longmode64_entry
                               ; Start executing code in 64-bit mode

noa20_err db "A20 line couldn't be enabled", 10, 13, 0
nolm_err  db "Processor doesn't support x86-64 mode", 10, 13, 0

; Zero length IDT record to force all interrupts to triple fault
align 4
idtr:
.len      dw 0
.base     dd 0

; Macro to build a GDT descriptor entry
%define MAKE_GDT_DESC(base, limit, access, flags)  \
    (((base & 0x00FFFFFF) << 16) |  \
    ((base & 0xFF000000) << 32) |  \
    (limit & 0x0000FFFF) |      \
    ((limit & 0x000F0000) << 32) |  \
    ((access & 0xFF) << 40) |  \
    ((flags & 0x0F) << 52))

; GDT structure
align 4
gdt_start:      dq MAKE_GDT_DESC(0, 0, 0, 0)
                               ; Null descriptor
gdt64_code_pl0: dq MAKE_GDT_DESC(0, 0x00000000, 10011010b, 0010b)
                               ; 64-bit code, privilege level 0, l=1, sz=0
gdt64_data_pl0: dq MAKE_GDT_DESC(0, 0x00000000, 10010010b, 0000b)
                               ; 64-bit data, privilege level 0, l=0, sz=0
gdt64_code_pl3: dq MAKE_GDT_DESC(0, 0x00000000, 11111010b, 0010b)
                               ; 64-bit code, privilege level 3, l=1, sz=0
gdt64_data_pl3: dq MAKE_GDT_DESC(0, 0x00000000, 11110010b, 0000b)
                               ; 64-bit data, privilege level 3, l=0, sz=0
end_of_gdt:

; GDT record
align 4
    dw 0                       ; Padding align dd GDT in gdtr on 4 byte boundary
gdtr:
    dw end_of_gdt - gdt_start - 1
                               ; limit (Size of GDT - 1)
    dd gdt_start               ; base of GDT

NULL_SEL_RPL0  EQU 0
NULL_SEL_RPL1  EQU 1
NULL_SEL_RPL2  EQU 2
NULL_SEL_RPL3  EQU 3
CODE64_PL0_SEL EQU gdt64_code_pl0 - gdt_start
DATA64_PL0_SEL EQU gdt64_data_pl0 - gdt_start
CODE64_PL3_SEL EQU gdt64_code_pl3 - gdt_start
DATA64_PL3_SEL EQU gdt64_data_pl3 - gdt_start

; Entry point for 64-bit mode
; Upon entry these have all been set:
;     - CPU is running at Current Privilege Level (CPL) = 0 aka kernel mode
;     - Interrupts are enabled (IF=1)
;     - External interrupts are disabled on the Master and Slave PICs
;     - Direction Flag clear (DF=0)

BITS 64
longmode64_entry:
    mov eax, DATA64_PL0_SEL    ; Set DS/ES/FS/GS/SS to a
                               ;     privilege level 0 data selector
    mov ds, eax
    mov es, eax
    mov fs, eax
    mov gs, eax
    mov ss, eax

    ; Insert 64-bit code to test here
    mov eax, NULL_SEL_RPL0     ; EAX = 0x0000 = NULL Selector with
                               ;     Requested Privilege Level (RPL) 0

    ; Should loading a NULL selector with RPL 0 (0x0000) fail
    ; and cause an exception / triple fault / reboot? When tested in VMs and
    ; real hardware it works and `LM` is printed to the display below
    mov ss, eax                ; Try to set SS with NULL selector

    ; Write the letters "LM" (long mode) to upper left hand corner of display
    ; starting at text video memory address 0xb8000 using white on magenta attribute
    mov dword [VIDEO_TEXT_ADDR], (ATTR_WHITE_ON_MAGENTA << 8 | 'M') << 16 | \
                                 (ATTR_WHITE_ON_MAGENTA << 8 | 'L')

    hlt

stage2_end:

To assemble this file with NASM use:
nasm -f bin stage2.asm -o stage2.bin

A bootloader that this code is designed to work with can be found in this Stackoverflow answer. The code in that answer acts a test harness in the form of a bootable 1.44MiB floppy disk image. To build the disk - copy boot.asm and bpb.inc to the directory with stage2.asm (above) and use these commands:
nasm -f bin boot.asm -o disk.img

To test in QEMU you can run the command:
qemu-system-x86_64 -fda disk.img

If there is no fault the output should be similar to this:

If the code doesn't fault it should print LM in the upper left of the screen.
Answer: If this code is executed at CPL=0 in 64-bit mode:
NULL_SEL_RPL0  EQU 0
mov eax, NULL_SEL_RPL0         ; EAX = 0x0000 = NULL Selector with
                               ;     Requested Privilege Level (RPL) 0.
mov ss, eax                    ; Try to set SS with NULL selector 0x0000
                               ; Should this cause a #GP(0) fault?

The expected behaviour is to NOT fault with #GP(0). That seems contrary to the ISA documentation you quoted. The thing you didn't account for was in the pre-amble:

Loading a segment register while in protected mode results in special checks and actions, as described in the
      following listing.

The key thing is that the pseudo-code shown is for protected mode, not long-mode. Although you need to enable the PE (protected mode enable bit) to reach 64-bit mode ((a long mode submode), long-mode is not in fact protected mode. Wikipedia has a diagram for the x86-64 operating modes that shows the relationships very well:

This has tripped up a number of developers over the years. In some sections of Intel's ISA there is complete pseudo code to cover all the cases and different modes. The MOV instruction isn't quite documented the same way.
If you look further down the documentation you will find the table defining the 64-bit exceptions:

64-Bit Mode Exceptions

#GP(0)
If the memory address is in a non-canonical form.
If an attempt is made to load SS register with NULL segment selector when CPL = 3.
If an attempt is made to load SS register with NULL segment selector when CPL < 3 and CPL ≠ RPL.

In your code you're loading 0x0000 into SS with MOV. 0x0000 is the NULL selector with a Requested Privilege Level of 0 (RPL=0). You're running at Current Privilege 0 (CPL=0). In your GDT the code selector you're using has a Descriptor Privilege Level of 0 (DPL=0).

Why your code doesn't cause #GP(0)
Your code isn't loading the selector to be stored in SS from a memory operand so the first condition can't cause a #GP(0). You're running at CPL=0 so the second condition can't cause a #GP(0). You're CPL(0) < 3 but you're RPL(0) == CPL(0) so the third condition can't cause a #GP(0).
If however you were to do this:
NULL_SEL_RPL0  EQU 3
mov eax, NULL_SEL_RPL3         ; EAX = 0x0003 = NULL Selector with
                               ;     Requested Privilege Level (RPL) 3.
mov ss, eax                    ; This cause a #GP(0) fault?

Here you're still CPL=0 but your NULL selector1 has an RPL of 3 (user mode). You now have a CPL(0) < 3 and CPL(3) ≠ RPL(0) so by the third condition the code should fault with #GP(0).
Although the expected behaviour of setting a NULL selector with RPL=3 when you're CPL=0 on real hardware - not all emulators catch this exception! In particular QEMU without KVM doesn't appear to do this check so it doesn't fault. If you're on a system with hardware virtualization and a KVM enabled OS and run QEMU with the option -enable-kvm it should fault with #GP(0) as expected. BOCHS will also raise the #GP(0) exception. Note: Moral of the story is that you can't necessarily rely on a particular emulator or VM to actually conform to rules that govern a real CPU.
To test the second condition where loading SS with a NULL selector at CPL=3 should fault with #GP(0), the longmode64_entry code could be changed to:
longmode64_entry:
    mov eax, DATA64_PL0_SEL    ; Set DS/ES/FS/GS/SS to a privilege level 0 data selector
    mov ds, eax
    mov es, eax
    mov fs, eax
    mov gs, eax
    mov ss, eax

    ; Insert 64-bit code to test here

    ; Change to ring 3 (user mode)
    mov rax, rsp               ; Save current RSP and use it as stack pointer in ring 3
    push DATA64_PL3_SEL | 3    ; User mode SS = 64 data segment with a DPL of 3, RPL=3
    push rax                   ; User mode RSP
    pushfq                     ; Push current flags
    push CODE64_PL3_SEL | 3    ; User mode CS = 64 code segment with a DPL of 3, RPL=3
    push .usermode             ; User mode RIP - enter ring 3 at label '.usermode'
    iretq                      ; Use IRETQ to perform ring transition from CPL 0 to CPL 3

.usermode:
    mov eax, NULL_SEL_RPL3     ; EAX = 0x0003 = NULL Selector with
                               ;     Requested Privilege Level (RPL) 3
    mov ss, eax                ; Try to set SS with a NULL selector at CPL=3
                               ;     This should fault with #GP(0)

    ; Write the letters "LM" (long mode) to upper left hand corner of display
    ; starting at text video memory address 0xb8000 using white on magenta attribute
    mov dword [VIDEO_TEXT_ADDR], (ATTR_WHITE_ON_MAGENTA << 8 | 'M') << 16 | \
                                 (ATTR_WHITE_ON_MAGENTA << 8 | 'L')

    jmp $                      ; Can't use HLT in Ring 3

Footnotes

1There are 4 NULL selectors. A selector value of 0x0000, 0x0001, 0x0002 and 0x0003. They correspond to NULL selector with RPL=0, NULL selector with RPL=1, NULL selector with RPL=2, and NULL selector with RPL=3.
Comment: Generally the appropriate "Exceptions" section of the instruction's documentation is the best place to find out what exceptions an instruction can generate. After you can look at the Operation and/or Description sections to see if they give more details.
Comment: @RossRidge : I totally agree, however Intel muddies the waters by going into full pseudo-code for some instructions and not other (IE: The call and jmp instructions have near complete pseudo code for all situations). Many developers appear to rely on the pesudo-code and may not look at the specific exceptions. In this case the pseudo-code isn't complete (the answer for 64-bit long mode is in the exceptions tables). In this case the term **protected mode** catches people off guard. Even in the Reddit question one of the OSdevers quoted the wrong part ( (not uncommon) of the MOV instruction.
Comment: The SDM contains: *In 64-bit mode, the processor does **not** perform runtime checking on NULL segment selectors. ...* and *If the RPL and DPL [of SS selector/descripto] are not equal to the CPL, a general-protection exception (#GP) is generated.* Don't this conform to the behaviour you found? I've only skimmed the answer, sorry :)
Comment: @MargaretBloom : If you read the original Reddit question (linked in the question) one well known OS developer actually misinterpreted the information in the `MOV` instruction and provided the wrong answer. I wrote a Q&A about this mainly because this question has popped up on various forums and chats and has garnered a fair amount of misinformation and much of it relates to the incomplete pseudocode and misinterpreting the meaning of **protected mode**
Comment: @MargaretBloom : Yes it does in Section 5, but people are often relying on the information in the ISA for a particular instruction and don't read the entire SDM lol. That information is actually captured in the SDM under the `MOV` instruction, but only as a part of the exceptions for 64-bit mode. What happens is people miss the **protected mode** pre-amble to the pseudo code and assume that applies to 64-bit long mode when it doesn't. They haven't read the exceptions table.
Comment: @MargaretBloom : What doesn't help is that QEMU (without the KVM option) doesn't perform the check CPL < 3 and CPL ≠ RPL when SS is loaded with a NULL selector (ie: when CPL=0, RPL=3). In that case QEMU doesn't raise the #GP(0). That is captured at the bottom of the answer. This confuses people because they think they have working code tested in QEMU and then it fails on real hardware.


put the appBar at the bottom of the page

Question:
I have a project in order to monitor employees and I have an interface for user modification within the site, and at the bottom of this interface there is this blue-surrounded area which is "bottom App Bar", but I could not control its own style and I want it to be fixed at the bottom of the page even with the scroll.
In addition, "bottom app bar" did not appear on the page.
Noting that the first image is the image pulled from the website for which I want to create an interface similar to the image.
And the second image is the page that I made, but it lacks the "bottom App bar"

How can I solve my problem?
const drawerWidth = 240;

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        root: {
            flexGrow: 1
        },
        paper: {
            padding: theme.spacing(2),
            textAlign: 'center',
            color: theme.palette.text.secondary,
        },
        resize: {
            fontSize: 19,
            color: '#828588',
            borderBottom: '1px solid #e4e4e4',
            borderBottomColor: '#384047'
        },
        label: {
            color: '#d5d6d7',
            fontWeight: 560,
            fontSize: '1rem',
            fontFamily: 'Gotham Pro,Proxima Nova,arial,serif',
        },
        textField: {
            color: '#828588',
            background: 'transparent',
            paddingTop: '0.5rem'
        },
        appBar: {
            [theme.breakpoints.up('sm')]: {
                width: `calc(100% - ${drawerWidth}px)`,
                marginLeft: drawerWidth,
            },
        },
        dot: {
            height: '25px',
            width: '25px',
            borderRadius: '50%',
            display: 'inline-block'
        }
    }),
);

const MySettings: FC = () => {

    const classes = useStyles();

    return (

            {/*<Container maxWidth="lg" style={{backgroundColor: 'red'}}>*/}
            <Grid container xs={12} md={12}>
                <Grid item xs={1} md={1}>
                    <Avatar style={{width: '5.4rem', height: '5.4rem'}} alt="Remy Sharp"
                            src="https://images.unsplash.com/photo-1438761681033-6461ffad8d80?
                ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cGVyc29ufGVufDB8fDB8fA%3D%3D&ixlib=rb-
                1.2.1&w=1000&q=80"/>

                </Grid>
                <Grid item xs={11} md={11} spacing={3}>
                    <Grid item xs={12} spacing={3}>
                        Full name
                        <TextField
                            className={classes.textField}
                            fullWidth
                            name="name"
                            placeholder="Enter UserName"
                            variant="standard"
                            style={{
                                // paddingTop:'2.3rem',
                                display: 'flex',
                                alignItems: 'center',
                                flexGrow: 1,
                                position: 'relative',
                                color: '#828588',

                            }}
                            InputProps={{
                                classes: {
                                    input: classes.resize,
                                },
                            }}
                            defaultValue="Hiba Youssef"
                        />
                    </Grid>

                    <Grid item style={{marginTop: '2.4rem'}}>
                        Email
                        <TextField
                            className={classes.textField}
                            fullWidth
                            name="email"
                            placeholder="Enter Email"
                            variant="standard"
                            style={{
                                // paddingTop:'2.3rem',
                                display: 'flex',
                                alignItems: 'center',
                                flexGrow: 1,
                                position: 'relative',
                                color: '#828588',

                            }}
                            InputProps={{
                                classes: {
                                    input: classes.resize,
                                },
                            }}
                            defaultValue="email@example.com"
                        />
                    </Grid>

                    <Grid item style={{marginTop: '2.4rem'}}>
                        Password
                        <TextField
                            className={classes.textField}
                            fullWidth
                            name="password"
                            placeholder="Enter New Password"
                            variant="standard"
                            style={{
                                // paddingTop:'2.3rem',
                                display: 'flex',
                                alignItems: 'center',
                                flexGrow: 1,
                                position: 'relative',
                                color: '#828588',

                            }}
                            InputProps={{
                                classes: {
                                    input: classes.resize,
                                },
                            }}
                            defaultValue="......"
                        />
                    </Grid>
                    <Grid item style={{marginTop: '5rem'}}>
                        <Typography style={{color: '#d5d6d7', fontWeight: 640, fontSize: '1.8rem'}}>
                            Your color theme
                        </Typography>
                        <Grid item spacing={8} container  style={{marginTop: '0.6rem'}}>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                            <Grid item>

                            </Grid>
                        </Grid>
                    </Grid>
                    <Grid>
                    </Grid>
                </Grid>
            </Grid>

    );
}

export default MySettings;

Answer: right here

        appBar: {
            [theme.breakpoints.up('sm')]: {
                width: `calc(100% - ${drawerWidth}px)`,
                marginLeft: drawerWidth,
            },
        },

you could probably just add
                position: "fixed",
                bottom: 0

so that way you have this

        appBar: {
            [theme.breakpoints.up('sm')]: {
                width: `calc(100% - ${drawerWidth}px)`,
                marginLeft: drawerWidth,
                position: "fixed",
                bottom: 0
            },
        },


Chamar função javascript de dentro de um bloco ASP Clássico

Question: Como eu faço para executar uma função javascript de dentro de um bloco asp clássico. A função js não está no mesmo arquivo, está fora, em outro arquivo.
<%
if(MINHA_FUNÇÂO_JS_AQUI)
response.write " "
%>

Comment: Não foi eu que negativei. Mas concordo com você. Vota negativo, não fala o porquê e ninguém edita.
Comment: Eu fiz um comentário no meta, sobre downvote e estou recebendo downvotes sem mesmo merecer, ou seja, por puro ódio, mas ainda vou continuar com a minha opinião a respeito desses caras aqui. Estão escondidos, uns covardes.
Comment: Certamente é um problema do StackOverFlow. Tem o link do tópico, quero acompanhar!
Comment: Acho que os votos negativos dessa pergunta estão vindo por causa de não possuir nenhum código ou exemplificação do que deseja (O que acho que não seja um motivo para dar voto negativo). E sim, é mesmo um problema...
Comment: Pô, mas pense comigo. É uma pergunta bem genérica, não vejo o porque ter um código. Como eu disse, eu tenho uma página asp e preciso chamar uma função js, mas vou pegar uma das muitas vezes que isso vai acontecer, vou blocar o código.
Comment: Isto não é possível.
Comment: A própria plataforma da um "lembrete" para considerar um comentário ao negativar. É comum eu ver alguns downvotes e nenhum comentário. Chego a pensar se para a nossa realidade não seria necessário obrigar um comentário para usar o downvote, infelizmente.
Comment: up vote, pergunta clara e objetiva, é que está na moda dar downvote..rs
Answer: Não é possível.
ASP Classic é interpretado pelo servidor e enviado o html já processado para o client.
Javascript é processado apenas no client.
Seria possível fazer o contrário javascript chamar ou receber variável asp, ex
alert('<%=variavel%>');

pois na verdade quando o processamento ocorre primeiro no server iria retornar para o client
alert('valor_da_variavel');

Então, infelizmente não é possível você fazer isso mesmo programando ASP Classic com vbscript ou javascript.
Answer: Olá, utilize duas vezes as aspas """" desta forma o ASP irá interpretar normalmente, caso utilize apóstrofo ' o ASP entende que é um comentário.
no seu código de exemplo verifiquei que o src="" estava incorreto.
segue abaixo a maneira de inserir código javascript no ASP em uma variável:
<%
response.write " "
%>

Esta é a saída:

Answer: Não é possível você colocar o JS diretamente ligado ao ASP então esqueça utilizá-lo como parte da lógica pois a forma como o ASP e o JS são processadas é diferente, ou seja, se você tentar colocar sua função JS como condição para um laço de repetição ou mesmo em uma condicional simples(IF) ele não funcionará pois o ASP é interpretado pelo servidor e só depois no lado do cliente o JS será processado.
Porém é possível que você inclua a chamada a uma função JS dentro de um elemento HTML, desde que você tenha o script com função no documento seja ele um JS externo incluído ou não.
Então fora o if(MINHA_FUNÇÂO_JS_AQUI) que definitivamente não funcionará
um outro problema no seu código é que você concatenou o trecho de JS no elemento HTML de forma errada:
<%= "" %>

o correto seria:
<%= "" %>

Ou
<%= "" %>

Esse código será interpretado pelo servidor e criará o seguinte HTML:


nginx blank page with puma and rails on beanstalk

Question: I tried to deploy rails api to elastic beanstalk with nginx and puma as the app server. THe deploy was successful, database created and migrated.
However, when accessing the web, it just show whitepage.
I can see that the request was recorded in nginx access log, however its not recorded in puma log.
Following is nginx conf :
> user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local]
"$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

sendfile            on;
tcp_nopush          on;
tcp_nodelay         on;
keepalive_timeout   65;
types_hash_max_size 2048;

include             /etc/nginx/mime.types;
default_type        application/octet-stream;

# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;

index   index.html index.htm;

server {
    listen       80 ;
    listen       [::]:80 ;
    server_name  localhost;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
    }

    # redirect server error pages to the static page /40x.html
    #
    error_page 404 /404.html;
        location = /40x.html {
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

The conf uses include directives, which has following content :
    upstream my_app {
      server unix:///var/run/puma/my_app.sock;
    }
log_format healthd '$msec"$uri"'
                '$status"$request_time"$upstream_response_time"'
                '$http_x_forwarded_for';

server {
  listen 80;
  server_name _ localhost; # need to listen to localhost for worker tier

  if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
    set $year $1;
    set $month $2;
    set $day $3;
    set $hour $4;
  }

  access_log  /var/log/nginx/access.log  main;
  access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;

  location / {
    proxy_pass http://my_app; # match the name of upstream directive which is defined above
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  location /assets {
    alias /var/app/current/public/assets;
    gzip_static on;
    gzip on;
    expires max;
    add_header Cache-Control public;
  }

  location /public {
    alias /var/app/current/public;
    gzip_static on;
    gzip on;
    expires max;
    add_header Cache-Control public;
  }
}

What am I missing here?
Thanks!
Answer: Check your logs file probably nginx is not configured correctly, if so you can refer to these posts for the solution (https://stackoverflow.com/questions/49360715/elastic-beanstalk-customize-puma-configuration)
(https://stackoverflow.com/questions/40938155/right-way-to-deploy-rails-puma-postgres-app-to-elastic-beanstalk). Basically you need to ssh into your instance and customize the nginx configuration file stored at /etc/nginx/nginx.conf, you need to bind there the puma server to a unix socket and it connects with NGINX. Example of the NGINX configuration file:
user  root;

error_log  /var/log/app-nginx-error.log;
pid        /var/run/app-nginx.pid;

events {
    worker_connections  8096;
    multi_accept        on;
    use                 epoll;
}

http {
    ....

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    upstream appserver {
        server unix:///var/run/puma.sock;
    }

    ....
}

The important part that you should add to the NGINX configuration file is:
upstream appserver {
  server unix:///var/run/puma.sock;
}


Linear transformation with inner product.

Question: I'm a little confused with the following situation because inner products show up in this linear transformation.:
Take $\mathbb{R^3}$ with the standard inner product. Let $a,b \in \mathbb{R^3}$ so that $\langle a,b\rangle = 2$
$L: \mathbb{R^3} \rightarrow \mathbb{R^3}:x \longmapsto x - \langle x,a\rangle b$
How do I determine the eigenvalues of $L$? I want to see if $L$ is diagonalizable.
I always use a matrix to determine the eigenvalues but it doesn't seem the best idea to do that in this case.
Thank you in advance.
Answer: Let $c\in\mathbb R^3$ such that $c$ is orthogonal to both $a$ and $b$. Then $\{a,b,c\}$ is a basis of $\mathbb R^3$ and the matrix of $L$ with respect to this basis is$$\begin{bmatrix}1&0&0\\\lVert a\rVert^2&-1&0\\0&0&1\end{bmatrix}.$$Can you take it from here?
Comment: Can you please explain how you get to that matrix because I don't see it.
Comment: There was a typo in my answer, which I have corrected. The first column comes from the fact that $L(a)=a-\langle a,a\rangle b=a-\lVert a\rVert^2b$. The secondcolumn comes from the fact that $L(b)=b-\langle b,a\rangle b=b-2b=-b$. Finally, the third one comes from the act that $L(c)=c-\langle c,a\rangle a=c$.
Comment: I see it now, thank you. Can I now say that the eigenvalues are 1 and -1? I would say that it's not diagonalizable because you have two times 1 as eigenvalue. Is this correct?
Comment: Yes, the eigenvalues are $1$ and $-1$ and, no, it is not diagonalizable. However, just saying that you have the eigenvalue $1$ twice is not enough to prove it. After all, the same thing occurs with the matrix$$\begin{bmatrix}1&0&0\\0&-1&0\\0&0&1\end{bmatrix},$$which *is* diagonalizable.