Statistical test for the difference in center positions of two receptive fields

Question: I am a neuroscientist, and have neuronal response measurements for a large range of stimuli delivered to my subjects. I use this data to construct receptive fields (RFs), which show the mean response magnitude as a function of stimulus value. So, two RFs, for two different neurons, when they are shown stimuli from a 2-d stimulus space, might look like this:

I have multiple presentations of each stimulus (here I am representing each stimulus as an $(x,y)$ pair: you can consider it as the location of a light presented to the eye, and the height is the mean neuronal response to the light presented at that location).
Note that the two receptive fields above are not probabilities, but the height represents the mean response to the stimulus.
I want to test whether the receptive field centers are different for the two neurons. That is, is the location of the peak in the above two bumps different? Let's say we assume the two bumps are Gaussian in shape: what is the best way to test the null hypothesis that the two RF centers are identical?
If all else fails, I could do some kind of bootstrap, where I sample with replacement from the set of all $(x_i, y_i, r_i)$ triplets from each group. But even then, I would be back to square one of figuring out what statistical test to apply to these two samples of the original data.
Potentially Relevant Links:

Significance of different mean values for two processes
Comment: Neuroscientist here as well. Instead of bootstrapping, you could do a permutation-based test. Choose a test statistic, e.g. fit a Gaussian to each cell and take distance $d$ between the peaks. Then pool all your $(x,y,r)$ measurements for both cells, randomly split them in two (as if these two groups were two cells), compute the same statistic $d$, and repeat many times. You will get a null distribution of your distances $d$ and can directly get a p-value for your actual empirical $d$ being larger than expected under null.
Comment: That is very clean and simple: nice idea! You should consider turning into an answer. :) Have you seen it done that way before? I.e., is there a reference out there on this, specifically wrt RFs? I would encourage you to turn this into an answer :)
Comment: I don't have a reference, sorry. I am not working with RFs myself, so I don't really know what people do, this was just the first/easiest thing that came to my mind. I might post it as an answer a bit later.
Comment: One nice thing about your answer is that it is relatively easy to extend to N>2 neurons (or N>2 recording sessions with the same neuron). And it can be applied to essentially any descriptive statistic you care to compare.
Answer: I am posting my earlier comment as an answer.
The easiest thing to do would probably be a permutation-based test. Choose a test statistic, e.g. fit a Gaussian to each receptive field and take distance $d$ between the peaks as your test statistic. Then pool all your $(x,y,r)$ measurements for both cells, randomly split them in two (as if these two groups were two cells) in the same proportion as in the actual data, compute the same statistic $d$, and repeat many times with different random splits. You will get a null distribution $f_0(d)$ of your distances $d$, and can directly get a $p$-value for your actual empirical $d$ being larger than expected under null.
This is a very general framework that can work in almost any circumstances.
PS. Wikipedia insists that it is only called "permutation test" when you actually loop over all possible permutations; otherwise it should (apparently) be called "approximate permutation tests, Monte Carlo permutation tests or random permutation tests". I find it weird; my understanding is that people do call it "permutation tests", and I don't see anything wrong with it.


Multiplication and division of values with geometric standard deviation

Question: What is the geometric standard deviation of a value, which is the result of dividing two independent values, each of which has its own geometric standard deviation ?
It is a frequent situation in science, that the the signal of the machines is in linear relationship to the logarithm of the analysed quantity, so it is appropriate to use geometric standard deviation to characterize the the error of the measured quantity. (I calculated geometric mean and geometric standard deviation from triplicate measurements for each value). Now I want to divide two such quantity values (one by another) to obtain a relative concentration. What will be the geometric standard deviation of the relative concentration ?
(I assume, that the two original values are independent - I do not want to deal with covariances etc.)

EDIT:
In desperation, I came up with a theory, but would appreciate a confirmation from a matematician, because I am a molecular biologist.
I wanted to do x=a/b.
I took my triplicate measurements and made all possible combinations of values, which are a1/b1, a1/b2, a1/b3, a2/b1, a2/b2, a2/b3, a3/b1, a3/b2, a3/b3.
Then I calculated geometric mean and geometric standard deviation, as if these 9 results were 9 independent measurements.
IS THIS STEP CORRECT ???
Another approach: I assume, that "lognormal distribution, geometric means, multiplication/division of geometric means, logarithms of geometric standard deviations" are all in the same analogy to "normal distribution, arithmetic means, addition/substraction of arithmetic means, arithmetic standard deviations".
For my "x=a/b" , it leads me to these formulas:

The resulting equation gives me the same results, as when I calculate from those 9 independent combinations described above. I calculate in Excel, which shows many decimal numbers, so it demonstrates very nicely, that the results of both calculations are identical.
Can someone confirm the formulas are correct, please ?
Answer: Yes, I believe your formula is correct. If $A$ is a random variable which takes positive values the geometric standard deviation of $A$ is by definition the exponential of the ordinary (arithmetic) standard deviation of $\log(A)$. Write $\sigma_g(A)$ for the geometric standard deviation and $\sigma(A)$ for the arithmatic standard deviation. Then:
$$\log \sigma_g(A/B)= \sigma(\log(A/B)) = \sigma(\log(A)-\log(B))$$
but we are assuming that $\log(A)$ and $\log(B)$ are independent, since $A$ and $B$ are, and so their variances add. Therefore
$$\sigma(\log(A)-\log(B))=\sqrt{(\sigma(\log(A)))^2 + (\sigma(\log(B)))^2} = \sqrt{(\log\sigma_g(A))^2 + (\log\sigma_g(B))^2}$$
which is what you found.
Comment: Thanks !!! Just out of curiosity - my/Your formulas and my manual calculating of geometric standard deviation from a1/b1, a1/b2, a1/b3, a2/b1, a2/b2, a2/b3, a3/b1, a3/b2, a3/b3 give the same result. Why does it not work that way for propagation of standard deviation (not geometric) in additive operations and for a1+b1, a1+b2, a1+b3, a2+b1, a2+b2, a2+b3, a3+b1, a3+b2 a3+b3 ? When I try that in Excel, stdevs are not the same, although similar.
Comment: I am not sure but my guess is that it probably has something to do with using an $n$ or an $n-1$ in the standard deviation formula. Possibly Excel uses an $n-1$ by default, or something like that.
Comment: Nope, I used Stdevp in Excel, which does not use n-1. Btw, my questions about arithmetic stdev are not really necessary for my research, I just like to understand things...


Htaccess redirect without url rewrite

Question: I have a little problem in hands.
I am setting up a domain that as 3 languages, example.com for principal domain, en.(...) for english and de.(...) for germany.
Usually I only redirect the httpdocs from the subdomains to the main with ln -S because all languages executes the same code, the difference is matched from php and mysql.
My new host don't provide any ssh connection so I have to use a different approach on this.
It was told to me that it can be done by .htaccess but I already tried a lot of things but only can redirect, changing the url and that's not possible, it have to keep the same, the contents yes, will be from another domain. Can someone help?
Answer: This code should looks like the one you're searching for :
www.domain.en .htaccess
RewriteBase /
RewriteRule ^(.*)$ http://www.domain.com/en/$1 [L,R=301]

www.domain.de .htaccess
RewriteBase /
RewriteRule ^(.*)$ http://www.domain.com/de/$1 [L,R=301]

You'll propably adapt the http://www.domain.com/lang/$1 part to your needs.

EDIT
Following your comment, this is a code for subdomains redirections :
domain.com .htaccess
RewriteCond %{HTTP_HOST} ^en\.domain\.com [NC]
RewriteRule (.*) http://domain.com/en/$1 [QSA,L]

RewriteCond %{HTTP_HOST} ^de\.domain\.com [NC]
RewriteRule (.*) http://domain.com/de/$1 [QSA,L]

Comment: Thanks @zessx but it's not really that. That code change the url also, and it's not intended, I just want to show the content of another page and maintain en.example.com/de.example.com.
Comment: It keeps doing the redirect. I already checked with phpinfo that mod_proxy is active. But it's almost that

Htaccess redirect without url rewrite


Pegar valor digitado pelo usuário no input com jQuery

Question: Olá! É o seguinte, no meu formulário, estou tentando obter o valor digitado pelo usuário no input da maneira abaixo:
// jQuery
function teste() {
var nome = $("#nome").val();
alert(nome);
}

// HTML
<form method="post" action="#">

        Nome
        <input type="text" name="nome" id="nome">

        Sobrenome
        <input type="text" name="sobrenome" id="sobrenome">

</form>
<button onClick="teste()">Teste</button>

Mas não retorna nenhum valor, gera um alert() em branco, independente do que o usuário tiver digitado. Alguém sabe o que pode ser? Caso seja útil, estou usando o Codeigniter
Comment: Isso pode acontecer caso você tenha mais de um elemento com o mesmo ID.
Comment: Verifiquei essa possibilidade, mas só há um elemento com o ID mesmo
Answer: Pode fazer assim que traz o valor do campo sem uso do JQuery:
function teste() {
   var nome = document.getElementById("nome").value
   alert(nome);
}

Comment: Tentei, mas também retornou vazio. Parece que ele só retorna o valor do atributo value="" se for inserido, ai como não inseri, volta vazio
Answer: Use jquery, no lugar desse onlick coloque uma Id <button id="teste">Teste</button>

<form method="post" action="#">

        Nome
        <input type="text" name="nome" id="nome">

        Sobrenome
        <input type="text" name="sobrenome" id="sobrenome">

</form>
<button id="teste">Teste</button>

Comment: Também não vai, parece que ele so consegue trazer o valor do atributo value="" e se ele não estiver, ai retorna vazio
Comment: se o valor estiver vazio vc precisa validar com um if($("#nome").val() == null) faca alguma coisa... mas o seu problema era o button que nao estava funcionando certo?


VBA "Application defined or object defined error"

Question: I have the following line of VBA code which is intended to find a column by header name and get the entire column as a range:
Set w1 = wbk.Sheets("Sheet1")
Set parentRange = w1.Rows(1).Find("portfolioName").Offset(1).Resize(num_rows - 1, 1)

It works perfectly fine in one workbook, however when I try it in a new workbook I get the following error:
<Application-defined or object-defined error>

I'm new to VBA so I'm not sure whether or not displaying code context or giving more details, is there something simple I could be neglecting to notice?
num_rows:
num_rows = w1.Cells(Rows.Count, 1).End(xlUp).row

Comment: `Range.Find` will return `Nothing` if it doesn't find what it's looking for, which will throw error 91 since you can't do `Nothing.Offset`. Also `Range.Find` "remembers" its optional parameter values between calls, so manually doing Ctrl+F and tweaking stuff between macro calls will make the macro behave differently - you should provide a value for each of the optional parameters.
Comment: Does this new workbook have a sheet named `"Sheet1"` ? It could also be that `.Find()` is just not returning anything and so the range `parentRange` doesn't end up with a value
Comment: ...and what's the value of `num_rows` when it fails?
Comment: @TimWilliams it seems like num_rows is 1, which I believe is what is causing the Range to be Nothing as Mathieu suggested. I have no idea why this is the case, I updated the post with how num_rows is calculated and it works in another sheet.
Comment: Sometimes chaining calls is the cause of problems. To find the root of the problem piece of code, split chaining calls into separate calls. For instance, `Set parentRange = w1.Rows(1).Find("portfolioName").Offset(1).Resize(num_rows - 1, 1)`. First, `w1.Rows(1)` can't be incorrect since there's will be always first row. Next, `Find(...)` - this one returns `Range`. Assign the return value into its own variable. Next step (if `Find` worked perfectly), you fetch `Offset(1)` and so far and so on...
Comment: You need to add a check on the value of `num_rows` to decide what to do if it's 1
Comment: Ah, the issue is that there are two columns with the same name in the sheet, and I need the second one which does have actual rows under it. How can I specify this in the find command?
Comment: you migth be pulling the wrong `Rows`. Try instead `num_rows = w1.Cells(w1.Rows.Count, 1).End(xlUp).row`
Comment: See [Making a CountRows function in Excel](https://stackoverflow.com/a/45405235/380384) for a robust way of counting non-empty rows under a cell reference.
Answer: Dim f1 As Range, f2 As Range

Set w1 = wbk.Sheets("Sheet1")
'find first instance
Set f1 = w1.Rows(1).Find("portfolioName",lookat:=xlWhole)
If Not f1 Is Nothing then
    'find second instance
    Set f2 = f1.offset(0, 1).Resize(1, w1.Columns.Count - f1.Column).Find("portfolioName",lookat:=xlWhole)
    If not f2 is nothing then
        'set range based on f2
        Set parentRange = w1.Range(f2.Offset(1, 0), _
                                   w1.cells(rows.count,f2.column).end(xlup))

    end if
end if

In your posted code you get the number of rows from ColA, but it seems like that might be unreliable?  In the code above it just selects all data below the second instance of the search term.
Comment: Would you mind explaining what this code does?  Why is the 2nd param of resize hardcoded to 200/what does it mean?
Comment: To find `f2` you want to look to the right of `f1` (starting from the cell to the right of `f1`) - I just hardcoded 200 as a maximum number of columns you might ever need to check when doing that, but if you want to check the whole of the rest of the row then `Resize(1, ws.Columns.Count - f1.Column)` would do that.
Comment: It gives me another run-time error, saying Object Required on the Set parentRange line. Am I missing something?
Comment: Sorry that line should have had `f2.Column`
Answer: It's either not finding portfolioName (if you have 'option compare text' off you might be running into case-sensitivity issues), or num_rows is not getting defined properly. Give those two a check.


how to enable comments only to subscribed users

Question: I'm creating a site for events where people can subscribe themselves to a single one.
Now, I'm using Node Registration module to allow users to subscribe. I would like to know if it is possible to enable comments of a particular event only to users who are members of it. Is there a module to do this? I tried with rules module but i couldn't...
Comment: do anonymous users allowed to register to events?
Comment: No, only registered users can subscribe to an event...if you are already a site member you can add comments only to events where you are subscribed in..
Comment: check the answer added below if that helps you
Answer: Here is a programmatic way to do this, add this code to your custom module
NOTE:
In the following code my content type name is article, change it to yours.
Also this code can not handle functionality for anonymous user as I couldn find a way to track if anonymous user is already registered or not.
<code>/**
  * Helper function to check if user is registered to a given event node or node.
 */
function check_if_user_is_registered($node, $uid) {
   $return = FALSE;
   $registrations = node_registration_load_multiple(FALSE, array(
      'uid' => $uid,
      'nid' => $node->nid,
      'cancelled' => 0,
    ));
  if(is_array($registrations)) {
    foreach($registrations as $registration) {
      if($registration->author_uid == $uid) {
        $return = TRUE;
      }
    }
  }
  return $return;
}

/**
  *  Implements hook_node_load().
 */
function MYMODULENAME_node_load($nodes, $types) {
  global $user;
  foreach ($nodes as $node) {
    if($node->type == "article") {
      $access = check_if_user_is_registered($node,$user->uid);
      if(!$access) {
       $node->comment = 0; // to close comments
      }
    }
  }
}
</code>
Comment: Thanks! but I have only used existing modules (node registration modules), not custom ones...How can i do? Do you suggest me to create a new one by myself?
Comment: check this http://www.packtpub.com/article/creating-your-first-module-drupal-module-development
Comment: basically you need two files mymodulename.info which tells drupal about your custom module and mymodulename.module where your funcitonality lays down. remember "mymodulename" should be replaced by a standard name mostly the name should revolve around the functionality it adds.So the above code in the answer will go to the your .module file and the link shared in the comments can tell you what to add in the .info file
Comment: Thanks for the answer! Now i'm going to read it. I hope to understand..
Comment: sure let me know if you have issues
Comment: Sorry, it still doesn't work...I put into the file .info all the informations of the module as name, dependencies, etc. etc. Then I put your code in .module and I have replaced "mymodulename" with the new name module I created; I have also replaced "article" with my content type(ads_contests) but nothing.
I can activate the module but after that I see php code at the top of the page..
Comment: Did you miss adding the php tags in the .module file
Comment: oops..stupid mistake! I'm sorry!
Comment: It works! Thank you! Now I'd want to insert a date control..if the contest is taking place, comments are open only for its  subscribed users..should I use the time() function?
Comment: yes change  if(!$access) to something like       if(!$access && time() > $content_time) // where $contest_time will be given to your code


How to use onClick() or onSelect() on option tag in a JSP page?

Question: How to use onClick() or onSelect() with option tag? Below is my code in which I tried to implement that, but it is not working as expected.
Note: where listCustomer domain object list getting in JSP page.

  <select name="singleSelect" ">
     <c:forEach var="Customer" items="${listCustomer}" >
     <option value="" onClick="javascript:onSelect(this);> <c:out value="${Customer}" /></option>
                </c:forEach>
          </select>

How do I modify it to detect that an option is selected?
Comment: `` elements don't fire the `click` event in all browsers, you should stray away from relying on this.  Also be careful when tagging, Java != JavaScript, ["Java is to JavaScript what Car is to Carpet."](http://stackoverflow.com/questions/58640/great-programming-quotes/58693#58693)
Comment: @Nick.. using the above code i am creating drop down menu in which customer names are displaying. if i select anyone of the value in drop down menu that value should pass to java script..
Please help me how to do it..
Comment: @Nick.. can you see the below comments i dropped for stephen and i expect your reply for that
Answer: Neither the onSelect() nor onClick() events are supported by the <option> tag. The former refers to selecting text (i.e. by clicking + dragging across a text field) so can only be used with the <text> and <textarea> tags. The onClick() event can be used with <select> tags - however, you probably are looking for functionality where it would be best to use the onChange() event, not onClick().
Furthermore, by the look of your <c:...> tags, you are also trying to use JSP syntax in a plain HTML document. That's just... incorrect.
In response to your comment to this answer - I can barely understand it. However, it sounds like what you want to do is get the value of the <option> tag that the user has just selected whenever they select one. In that case, you want to have something like:

  <select id="selectBox" onchange="changeFunc();">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>

Comment: In which case, you probably want to populate it server side. Do you use PHP on the server side, or another language?
Comment: @Stephen.. using the above code i am creating drop down menu in which customer names are displaying. if i select anyone of the value in drop down menu that value should pass to java script..
Please help me how to do it..
Comment: @Stephen.. i am having more than 1000 customer name ..in that case how can i create option#1,option#2. and also data is dynamic
Comment: @Stephen.. my requirement is i have drop down list menu(displaying in jsp page)  which contains n number of customer names. if i click anyone name in that list that selected name should send to javascript function.
Please provide solution for this..
Comment: Ah, so you're working in Java Server Pages (JSP). Sorry, but that's out of my experience range. I've only used JSP once, and that was for generating just an XML file, not proper HTML. I suggest you google for some tutorials on JSP. Sorry.
Comment: i am creating Lender/Borrower Application, in which as apart of my requirement i have to show all customer names for that Lender in drop down list of jsp page. In that drop down list if i click anyone customer name that name should pass to javascript ..after passing that selected name to javascript i am doing some manipulations..
Comment: **I do not know JSP.** I would suggest, as I said, that you go read some JSP tutorials - it seems like you're fairly unsure how to do something that may be quite simple. Apart from that, your question is now **too vague** for SO - we can answer specific programming questions, but what you are asking now is basically "Please can someone write the code to do this for me."
Comment: The way you're generating the options is fine. What you should do for event handling is to attach a "change" handler to the "select" element, as @Stephen said.
Comment: If you mess around with this page, you'll find that onclick() actually does work, just so long as the size attribute of the select tag is 2 or greater. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_options2
Comment: @Manu how did you solve the problem because I have to do exactly the same thing.
Answer: Even more simplified: You can pass the value attribute directly!

  <select id="selectBox" onchange="changeFunc(value);">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>

The alert will either return 1 or 2.
Comment: This could damn well be the accepted answer. It's a good decision to always look at the SECOND answer.
Answer: The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.
it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.
if you do this with the code below you will see that
var selectBox = document.getElementById("selectBox");

gets put in a box and stays there you don't do anything with it afterwards.
and
var selectBox = document.getElementById("selectBox");

is hard to debug and is confusing when you have a select id of  selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag
your code works until you add to it or modify it then you can easily loose track and get all mixed up

<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>

a leaner way that works also is:

<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>

and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.

<select id="getPostcodes" onchange="Mapit();">

<option>London North Inner</option>

<option>N1</option>

<option>London North Outer</option>

<option>N2</option>
<option>N3</option>
<option>N4</option>

// a lot more options follow
// with text in options to divide into areas and nothing will happen
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes

</select>

Answer: in this example de select tag is named as: aula_clase_cb
<select class="form-control" id="aula_clase_cb" >
</select>

document.getElementById("aula_clase_cb").onchange = function(e){
    id = document.getElementById('aula_clase_cb').value;
    alert("id: "+id);
};

Answer:

        ¿Qué tipo de vehículo está buscando?
        <form name="formulario" id="formulario">
          <select name="lista" id="lista" onclick="activa(this.value)">
              <option value="0">Vehiculo para la familia</option>
              <option value="1">Vehiculo para el trabajo</option>
              <option value="2">Camioneta Familiar</option>
              <option value="3">Camioneta de Carga</option>
              <option value="4">Vehiculo servicio Publico</option>
              <option value="5">Vehiculo servicio Privado</option>
              <option value="6">Otro</option>
          </select>

          <input type="text" id="form vr_negativo" class="form-control input-xlarge" name="vr_negativo"/>
        </form>

Answer: You can change selection in the function

window.onload = function () {
  var selectBox = document.getElementById("selectBox");
  selectBox.addEventListener('change', changeFunc);
  function changeFunc() {
    alert(this.value);
  }
}
<!DOCTYPE html>

    <title>Selection</title>

    <select id="selectBox" onChange="changeFunc();">
      <option> select</option>
      <option value="1">Option #1</option>
      <option value="2">Option #2</option>
   </select>

Answer:

<title>Cars</title>

Cars

Name

        <select id="selectBox" onchange="myFunction(value);">
            <option value="volvo" >Volvo</option>
            <option value="saab"  >Saab</option>
            <option value="mercedes">Mercedes</option>
        </select>

 Price :

```

Comment: Code only answers can generally be improved by adding explanation of how and why they work. Ten year old questions with accepted answers can still have answers added, but those answers should point out what new aspect of the question they address.
Answer: focus clears value, so select any value is a change and fires myFunc(this) and blur defocus for reselect

   <select id="selectBox" onchange="myFunc(this);this.blur();" onfocus="this.selectedIndex = -1;">
     <option value="1">Option #1</option>
     <option value="2">Option #2</option>
   </select>

Comment: This is a clever solution for anyone who needs onchange to work when you want to detect when the user selects the currently selected option again.  For example, when the page loads Option #1 is already selected so by definition onchange won't fire when the user selects Option #1.  However it will if you reset the selectedItem to -1 as in the code above on focus.  Neat.
Answer: Other option, for similar example but with anidated selects, think that you have two select, the name of the first is "ea_pub_dest" and the name of the second is "ea_pub_dest_2", ok, now take the event click of the first and display the second.

Answer: Change onClick() from  with onChange() in the . You can send the option value to a javascript function.
<select id="selector" onChange="doSomething(document.getElementById(this).options[document.getElementById(this).selectedIndex].value);">
<option value="option1"> Option1 </option>
<option value="option2"> Option2 </option>
<option value="optionN"> OptionN </option>
</select>

Answer: If you need to change the value of another field, you can use this:
<input type="hidden" id="mainvalue" name="mainvalue" value="0">
<select onChange="document.getElementById('mainvalue').value = this.value;">
<option value="0">option 1</option>
<option value="1">option 2</option>
</select>

Answer: example dom onchange usage:
<select name="app_id" onchange="onAppSelection(this);">
    <option name="1" value="1">space.ecoins.beta.v3</option>
    <option name="2" value="2">fun.rotator.beta.v1</option>
    <option name="3" value="3">fun.impactor.beta.v1</option>
    <option name="4" value="4">fun.colorotator.beta.v1</option>
    <option name="5" value="5">fun.rotator.v1</option>
    <option name="6" value="6">fun.impactor.v1</option>
    <option name="7" value="7">fun.colorotator.v1</option>
    <option name="8" value="8">fun.deluxetor.v1</option>
    <option name="9" value="9">fun.winterotator.v1</option>
    <option name="10" value="10">fun.eastertor.v1</option>
    <option name="11" value="11">info.locatizator.v3</option>
    <option name="12" value="12">market.apks.ecoins.v2</option>
    <option name="13" value="13">fun.ecoins.v1b</option>
    <option name="14" value="14">place.sin.v2b</option>
    <option name="15" value="15">cool.poczta.v1b</option>
    <option name="16" value="16" id="app_id" selected="">systems.ecoins.launch.v1b</option>
    <option name="17" value="17">fun.eastertor.v2</option>
    <option name="18" value="18">space.ecoins.v4b</option>
    <option name="19" value="19">services.devcode.v1b</option>
    <option name="20" value="20">space.bonoloto.v1b</option>
    <option name="21" value="21">software.devcode.vpnfree.uk.v1</option>
    <option name="22" value="22">software.devcode.smsfree.v1b</option>
    <option name="23" value="23">services.devcode.smsfree.v1b</option>
    <option name="24" value="24">services.devcode.smsfree.v1</option>
    <option name="25" value="25">software.devcode.smsfree.v1</option>
    <option name="26" value="26">software.devcode.vpnfree.v1b</option>
    <option name="27" value="27">software.devcode.vpnfree.v1</option>
    <option name="28" value="28">software.devcode.locatizator.v1</option>
    <option name="29" value="29">software.devcode.netinfo.v1b</option>
    <option name="-1" value="-1">none</option>
</select>

Answer: In my case:

   <select id="selectBox" onchange="changeFunction(this)">
     <option value="1">Option #1</option>
     <option value="2">Option #2</option>
   </select>


Question on corollary of Hahn-Banach theorem

Question: I read that a corollary of the Hahn-Banach theorem is that if $M$ is a closed linear subspace of $X$ and $x \not \in M$, there is a functional $\phi \in X^*$ with $||\phi||=1$, s.t.
$$
\phi M = 0, \phi x \neq 0.
$$
In particular, we can form the linear subspace;
$$
Y := [x] + M = \{\lambda x + a : \lambda \in \mathbb{R}, a \in M\},
$$
where $[x]$ denotes the span of $x$.
The desired functional $\phi$ is then:
$$
\phi(\lambda x + a) : = \lambda ||x + M ||
$$
I don't understand...what does $||x + M||$ mean ? since $x$ is a vector while $M$ is a subspace...also how does $ \lambda ||z + M ||=0$ if $z \in M$?
Comment: that should be the norm in the quotient space $X/M$. $x+M$ is a coset
Comment: Yes, thats the norm on the quotient by $W$, but if $z_i\in W$, then $\|z_i + W\| = 0$.
Comment: @CalvinKhor, oh okay, does that mean $||x+W|| = \text{inf}\{||x+w||, w \in W$?.. so that if $z_i \in W$, there is a sequence $z_1,z_2,z_3$ s.t. $||z_i + W|| \rightarrow 0$?
Comment: okay thanks, if you put that as an answer i'll accept it
Answer: $x + M$ is a coset, belonging to the quotient vector spacce $X/M$. This is well defined as long as $M$ is a closed linear subspace of $X$. This is usually given the norm
$$ \|w + M\|_{X/M} := \inf_{m\in M} \|w+m\|_X$$
As part of checking that this is a norm, you'd see that $\|w+M\|=0$ iff $w\in M$. Since $x\notin M$, $\|x+M\|>0$.
Comment: And check that $\phi$ is well-defined. That is, if $a,a'\in M$ and $\lambda x+a=\lambda' x +a'$ then $\lambda=\lambda'$ (and $a=a'$).


Displaying streams in DIV

Question: I am running some terminal(or command prompt) commands through my servlet as below
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
    String[] command =
        {
      "zsh"
          };
                Process p = Runtime.getRuntime().exec(command);
                new Thread(new SyncPipe(p.getErrorStream(), response.getOutputStream())).start();
                new Thread(new SyncPipe(p.getInputStream(), response.getOutputStream())).start();
                PrintWriter stdin = new PrintWriter(p.getOutputStream());
                stdin.println("source ./taxenv/bin/activate");
                stdin.println("python runner.py");
                stdin.close();
                int returnCode = 0;
                try {
                    returnCode = p.waitFor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } System.out.println("Return code = " + returnCode);
    }
    class SyncPipe implements Runnable
    {
    public SyncPipe(InputStream istrm, OutputStream ostrm) {
          istrm_ = istrm;
          ostrm_ = ostrm;
      }
      public void run() {
          try
          {
              final byte[] buffer = new byte[1024];
              for (int length = 0; (length = istrm_.read(buffer)) != -1; )
              {
                  ostrm_.write(buffer, 0, length);
              }
          }
          catch (Exception e)
          {
              e.printStackTrace();
          }
      }
      private final OutputStream ostrm_;
      private final InputStream istrm_;
    }

This is displaying the result after executing terminal commands in a new window, I want to avoid that and pass these stream values back to JSP page and display the same in a div.
How to do that?
Comment: Instead of `void`, pass back values and read them in with JSP?
Comment: Instead of 'ostrm_.write(buffer, 0, length);' I want to send them back to JSP
Comment: So you advice me to put up all this stuff into <% %> and import things ?? I'll try this out and will update you.
Comment: It depends on your application. Please refer to my answer below.
Answer: Static import
First of all, you can define a scriplet with <%= and %> like explained here and here.
Instead of copying the whole code, you can statically import the .jsp page like so:
<%@ include file="YourPage.jsp" %>

Link.

To call the page at runtime instead of at the server-side you do:
<jsp:include page="YourPage.jsp"/>

But this doesn't yield a huge advantage over static importing.

Link

You can also declare your function and then use it throughout your webpage by using <%! and %> like shown here.
If you do any of the methods above, your function will (can) be imported  only when the page initially loads (server-side). (To be absolutely correct, <jsp:include is called at runtime in theory but in practice it simulates a request without actually making a complete round-trip: server > browser > server > browser).
Dynamic import
For dynamic importing or loading, you have to resort to jQuery (JavaScript) to load your JSP page client-side.
Please refer to this question: How do I inject another JSP page into a
 when clicking a link?
You could simply do:
function changeContent() {
    $('#content').load('YourPage.jsp');
}

You can find other examples here:

Display another jsp content in current jsp page upon a hyperlink click
CodeRanch

To quote the answer from the last link:
That's something to do with Ajax, Jquery can do that. You can use javascript getElementByID or use Jquery's build_in $("sub_banner") syntax to change the div's content.
Comment: Thanks a lot! Your answer was very helpful and en-lighting. Thank you!
Comment: @Zedai: Sure no problem. I hope it helps you out.

Displaying streams in DIV


Having problems clearing an arrayList

Question: I m having a 2d arraylist and inside a loop i want to parse every 1d list of the 2d list to a temporary list. Also I want at the end of every iteration i want to clear this temporary list so to the next step to parse the i-est list of my initial 2d.
The code its the following:
 List<List<Integer>> conVert = new ArrayList<List<Integer>>();
 List<Integer> temp = new ArrayList<Integer>();
 for (int i = 0; i<conVert.size(); i++){
    temp.addAll(conVert.get(i));
    Collections.sort(temp);
    System.out.println(temp);

    for(int j = 0; j<temp.size(); j++){
        // several commands
    }
    temp.clear();
 }

I have several commands which is not function well due to that temp doesnt clear properly. Any idea? When i put in clear in the beggining i m having problems with conVert,
Comment: I suggest you try running your code in a debugger. I can assure you that List.clear() does work and has been tested/used for many years now. ;) What happens when you create a new `temp` on every iteration? Does the problem go away?
Comment: the problem is that in every iteration this codes add a new list in temp so if the conVert.get(0)=[1,2] then in the first iter temp = [1,2] conVert.get(1)= [3,4] in the second iter temp = [1,2,3,4].
Comment: @zenitis Is the above code not the actual code?
Comment: @zenitis the above code attempt to clear the list after each itereation, this is not what you said in the comment
Comment: What are those several commands? if they don't alter temp, then it's your 2d list that is malformed.
Comment: The code is 400 lines :) is not efficiency possible to post it. But this code is not the problem. I have the same if I remove it and try just to clear temp list after every iteration,
Answer: You could use a brand-new List instead of clearing the "old" one. Why would you need an empty List after the for-loop? There is nothing to be gained by reusing such basic data structures and may even have a reverse effect.
When your List runs out of scope, it will be garbage collected at virtually no cost, while explicitly emptying it requires some resources.
EDIT : I guess in this case it is better to let the code speak for itself:
 List<List<Integer>> conVert = new ArrayList<List<Integer>>();

 for (int i = 0; i<conVert.size(); i++){
    List<Integer> temp = new ArrayList<Integer>();
    temp.addAll(conVert.get(i));
    Collections.sort(temp);
    System.out.println(temp);

    for(int j = 0; j<temp.size(); j++){
        // several commands
    }
}

Comment: What i gained is to parse in temp list the second list of conVert(which as already said is a 2darrayList). In the first step i want to parse the first conVert.get(0) int temp list in the second iteration the second list conVert.get(1) e.c.t
Comment: @zenitis I guess, it is better to illustrate my point wiht code (as always :) ) Please try the adapted code in my edit and see if it works for you.

Having problems clearing an arrayList


How to setup multisite to multisite rsync with drush?

Question: I try to rsync between a multisite setup (local) and a multisite setup (stage). If I run a sync it will copy all sites from dev to stage but I just want the current site to be synced.
<code>$drush rsync @dev @stage
</code>
My drush alias file is located in ~/.drush/example.aliases.drushrc.php
<code>$aliases['local'] = array(
  'root'           => '/Users/admin/Sites/drupal',
  'uri'            => 'example.local',
  'shell-aliases'  => array(
    'dump' => '!drush sql-dump --gzip --ordered-dump'
  ),
  'path-aliases' => array(
    '%dump'          => '/Users/admin/dev-' . date('Ymdhis') . '.sql',
    '%drush'         => '/Users/admin/drush',
    '%site'          => 'sites/example/',
  ),
);

// REMOTE: STAGING
$aliases['stage']  = array(
  'remote-user'      => 'xyz',
  'remote-host'      => 'stage.example.com',
  'root'             => '/home/xyz/www/stage.example.com',
  'uri'              => 'stage.example.com',
  'path-aliases' => array(
    '%drush'         => '/home/xyz/drush',
    '%drush-script'  => '/home/xyz/drush/drush',
    '%dump-dir'      => '/Users/admin/.drush-backups/example.stage',
    '%site'          => 'sites/example/',
  ),
  'command-specific' => array(
    'sql-sync'       => array(
      'no-cache'     => TRUE,
    )
  ),
  'shell-aliases'    => array(
    'dump' => '!drush sql-dump --gzip --ordered-dump'
  ),

  // DB
  'databases' =>
  array(
    'default' =>
    array(
      'default' =>
      array(
        'database'   => 'xyz',
        'username'   => 'xyz',
        'password'   => 'xyz',
        'host'       => 'xyz',
        'port'       => 'xyz',
        'driver'     => 'mysql',
        'prefix'     => '',
      ),
    ),
  ),
);
</code>
Questions:

%site: My project folder in sites/ is called example on the local side and has the same name on the staging side. Do they need to be different?
Do i need to put all domains in site.php on my staging server? At the moment I am using just the actual setup ($sites['stage.example.com'] = 'stage.example.com';) on my staging server.
My local sites.php file:
<code>$sites['example.local'] = 'example.local';
$sites['stage.example.com'] = 'stage.example.com';
$sites['example.com'] = 'live.example.com';
</code>
Are the directories all/ and default/ always needed?

My local Setup:

Drush 7.x dev
PHP 5.5.x
MAMP

My Server Setup:

Drush 7.x dev
PHP 5.5.x

Edit: Removed opinion based questions ;)
Answer:
On Drupal 6, your sites folders must be the same.  Since you are using Drupal 7, they can be different, but it is more convenient if they are the same.
You do not need to copy all of your multisites to your dev server.  The drush rsync option you are looking for is <code>--exclude-other-sites</code>.  This will cause rsync to skip everything in the sites folder except for sites/all, and the site you are syncing from.
sites/all is where sites/all/modules and sites/all/themes go, so you typically need these.  With some effort it might be possible to move your contrib modules elsewhere (if everything was in a profile, or if you hand-modified your registry), but this would be an unusual setup.  sites/default is not needed.
Comment: Thank you very much! I wonder why --exclude-other-sites did not cross my 4h+ search marathon :)
Comment: You are very welcome.  Always try `drush help rsync` (substitute command of choice), and also look at `drush topic` to see if anything is listed there; might save you some time next time!


How to get a value outside its brackets in java

Question: System.out.println("Which horse do you want to win, enter in 1-5");

String horsechoice = Input.next();

int randomhorse = (int)(Math.random()*5+1);

int horsechoice1 = Integer.parseInt(horsechoice);

System.out.println(randomhorse);

if (horsechoice1 == randomhorse){
    System.out.println("You win");
    int money = x + i;
    System.out.println("You have $"+money+ " remaining.");
}else if(horsechoice1 != randomhorse){
    System.out.println("You Loose");
    int money = x - i;
    System.out.println("You have $"+money+ " remaining.");
}

My goal is to get the int money outside of its brackets and to another part of my code further on. I feel like it should be a lot easier then I am making it.
Comment: If you declare `money` before the braces, you can use it _after_ the braces.
Answer: Declare the variable before the braces , then set the value inside the braces. You can give it an initial value of 0 if you like (sometimes the compiler will force you to give an initial value .)  This is the only way.
Comment: Thank you! I knew it would be something simple!
Answer: The brackets define the outer limits of a scope block. When the program moves past the end of the scope block then all the variables declared within go 'out-of-scope' and are destroyed. So that's what's happening with your money variable. So if you declare it outside of your brackets it won't go out of scope when you leave the scope block. You can then give it a value inside the brackets.
Answer: I would change it like this (after String horsechoice = Input.next();)
int money = 0; // The money
int randomhorse = (int) (Math.random() * 5 + 1);
int bet = 50; // A bet
int horsechoice1 = Integer.parseInt(horsechoice);
System.out.println(randomhorse);

if (horsechoice1 == randomhorse) {
  System.out.println("You win");
  money += bet; // Add the bet to money
} else { // if (horsechoice1 != randomhorse) { // <-- why retest?
  System.out.println("You Lose"); // Not Loose
  money -= bet; // Subtract the bet from money
}
System.out.println("You have $" + money
    + " remaining."); // <-- Print once.

Answer: You can just declare the variable outside of "its brackets", but set the value inside of them.
Like so:
int money = 0; // declare here

if (horsechoice1 == randomhorse){
    System.out.println("You win");
    money = x + i; // set here
    System.out.println("You have $"+money+ " remaining.");
}else if(horsechoice1 != randomhorse){
    System.out.println("You Loose");
    money = x - i; // set here
    System.out.println("You have $"+money+ " remaining.");
}


What's the difference between Maximizing Conditional (Log) Likelihood or Joint (Log) Likelihood while estimating parameters of a model?

Question: Consider a response y and data matrix X. Suppose I'm creating a model of the form -
y ~ g(X,$\theta$)
(g() could be any function of X and $\theta$)
Now, for estimating $\theta$ using Maximum Likelihood (ML) method, I could go ahead either with Conditional ML (assuming I know the form of conditional density f(y|X) ) or with Joint ML (assuming I know the form of joint density f(y,X) or equivalently, f(X|y) * f(y) )
I was wondering if there are any considerations in going ahead with either of the above two methods apart from the assumption about the densities. Also, are there any instances (specific types of data) where one method overpowers other most of the time?
Comment: If you have lots of data I think joint densities are more powerful.
Answer: It depends what you want to do with your model later.
Joint models attempt to predict the whole distribution over $X$ and $y$. It has some useful properties:

Outlier detection. Samples very unlike your training samples can be identified as they'll have a low marginal probability. A conditional model won't necessarily be bale to tell you this.
Sometimes it's easier to optimise. If your model was a gaussian mixture model, say, there are well documented ways to fit it to the joint density you can just plug in (expectation maximisation, variational bayes), but things get more complicated it you want to train it conditionally.
Depending on the model, training can potentially be parallelised by taking advantages of conditional independences, and you may also avoid the need to retrain it later if new data becomes available. E.G. if every marginal distribution $f(X|y)$ is parameterised separately, and you observe a new sample $(X=x_1,y=y_1)$, then the only marginal distribution you need to retrain is $f(X|y=y_1)$. The other marginal distributions $f(X|y=y_2), f(X|y=y_3), \ldots$ are unaffected. This property is less common with conditional models.
I recall reading a paper which indicated joint models have some other nice properties in cases where there's lots and lots of data, but cannot remember the exact claim, or find it in my big folder of interesting papers. If I find it later I'll put in a reference.

Conditional models however have some interesting properties too

They can work really well.
Some have had a lot of work put in finding sensible optimisation strategies (e.g. support vector machines)
The conditional distribution is very often `simpler' to model than the joint - to model the latter, you have to model the former as well as modelling the marginal distribution. If you're only interested in getting accurate predictions of what value $y$ is for a given $X$, it can be more sensible to concentrate your model's capacity on representing this alone.
Comment: Thanks for the answer. Can you please also provide with links to relevant literature?


jQuery storing files lines to array

Question: I have two .txt files that I am trying to create combinations from. I am trying to take the each file and turn them into an array as each word is separated by a newline. The problem is that when I run the $.get it does not save any information to the array. Here is my code:

        <title>Email Validator</title>

                First Name
                Last Name

Answer: $.get() is an AJAX call and that means it is asynchronous. The data.split() line occurs whenever the $.get completes and not necessarily before the $.each block you have.
Since you need to make two asynchronous calls you can try embedding:
        //pull firstnames and store to array
        var firstnames = new Array();
        var lastnames = new Array();
        $.get('first.txt', function(data){
            firstnames = data.split("\n");

            //pull lastnames and store to array
            $.get('last.txt', function(data){
                  lastnames = data.split("\n");

                  // Process your two arrays here
             });
        });

Answer: There are a few issues with your code.
When you want to depend on the result of multiple ajax calls, you can use $.when. One of the ways could be:
$.when(first, last).then(successCallBackFn, failureCallBackFn);

Where do first and last come from? Well, they can be the result of calling $.get like below:
var first = $.get('first.txt', function(data){
                firstnames = data.split("\n");
            });

Similarly last.
var last = $.get('last.txt', function(data){
                lastnames = data.split("\n");
            });

Finally, use $.when like below:
$.when(first, last).then(successCallBackFn, failureCallBackFn);

            function successCallBackFn(firstNames, lastNames) {
                var fn, ln;
                //firstnames
                $.each(firstnames, function (findex, fvalue) {
                    fn = fvalue;
                    //lastnames

                    $.each(lastnames, function (lindex, lvalue) {
                        ln = lvalue;
                        $("table.results").append("
" + fn + "	" + ln + "
");
                    });
                });
            }

            function failureCallBackFn() {
                console.log('failed');
            }

Also. note that you need to use append instead of appendTo in the line $("table.results").append.

jQuery storing files lines to array


Red Hat 7 reset password asks for for Root password

Question: I am trying to reset the root password on a rhel 7 machine
Following one of the many articles online
I first hit 'e' to get into edit mode
However after I do that is asks for a username and password?
What am I doing wrong?
I have tried putting in random passwords for root, however all it will do is reboot the machine back to the grub menu
Server is running on VMware 6.7
Comment: looks like password protection has been enabled for grub menu: https://help.ubuntu.com/community/Grub2/Passwords
Comment: @TomH anyway around that?
Comment: There is a tutorial here: https://www.cyberciti.biz/tips/howto-recovering-grub-boot-loader-password.html which suggests booting from a liveCD, and then editing the grub config from there
Answer: From the screenshot of the username prompt, it looks like password protection has been enabled for your grub menu: https://help.ubuntu.com/community/Grub2/Passwords
This password protection is set in the grub configuration file. Given you don't have login access to the machine, a work-around for that is to boot off a liveCD, and modify the grub config from there.
Really, any recent linux iso would do, and mount as cd in Vmware
There is a tutorial on doing that here:
https://www.computernetworkingnotes.com/rhce-study-guide/how-to-reset-grub-password-in-linux.html
and here:
https://www.cyberciti.biz/tips/howto-recovering-grub-boot-loader-password.html
you are basically looking for a line like so, and removing it:
<code>password --md5 $1$9sdflksdf/sdf44k
</code>


Is it possible to fetch the image tag from a deployment in EKS using terraform kubernetes provider?

Question: Context:
I'm reusing terraform modules and I deploy microservices using helm provider within terraform.
Problem:
I'm trying to translate this line into terraform code, to get the current image tag live from prod (in the interest of reusing it). I'm already using kubernetes provider's auth and doesn't make sense to pull kubectl in my CI just for this.
k get deploy my-deployment -n staging -o jsonpath='{$.spec.template.spec.containers[:1].image}'
Kubernetes terraform provider doesn't seem to support data blocks nor helm provider outputs blocks.
Does anyone know how could we get (read) the image tag of a deployment using terraform?
EDIT:
My deployment looks like this:
resource "helm_release" "example" {
  name       = "my-redis-release"
  repository = "https://charts.bitnami.com/bitnami"
  chart      = "redis"
  version    = "6.0.1"

  values = [
    "${file("values.yaml")}"
  ]

  set {
    name  = "image.tag"
    value = "latest"
  }

}

The tag will be a hash that will change often and passed on from another repo.
latest in this case should be replaced by the current running tag in the cluster. I can get it using kubectl, using the line above, but not sure how using terraform.
Comment: Are you creating the Deployment with terraform? If so, you can define the output based on the resource. But I would need to see that part of the code. :)
Comment: yeah, I'm deploying using terraform via helm provider, but it doesn't look like helm provider supports outputs https://registry.terraform.io/providers/hashicorp/helm/latest/docs/resources/release

my deployment code's similar to the one from the example link ^
Comment: Outputs can be created with the arguments or attributes from the provider. Which example from that URL? It's pretty hard to reproduce what you want to achieve without any code.
Comment: You're right, I've updated post with an example.
Comment: In this case, I think there is no deployment specification in the chart.
Answer: It turns out there are multiple ways of doing it, where the easiest one for me is to reference the set argument of the helm_release resource:
output "helm_image_tag" {
  value = [ for setting in helm_release.example.set : setting.value if setting.name == "image.tag" ]
}

The output will then be a list where you can reference it in a shell script (or another scripting language):
  + helm_image_tag = [
      + "latest",
    ]

If the list format does not suit you, you can create a map output:
output "helm_image_tag" {
value = { for setting in helm_release.example.set : setting.name => setting.value if setting.name == "image.tag" }
}

This produces the following output:
  + helm_image_tag = {
      + "image.tag" = "latest"
    }

By using terraform output helm_image_tag you can access this output value and decide what to do with it in the CI.
Comment: I feel it is worth adding that the third block of code relies on the semi-obscure fact that nested blocks in resources are technically `list(object)` despite not appearing that way intuitively in the DSL.
Comment: Yup, it's worth adding that, but please feel free to edit if you'd like.
Comment: This is great, thank you. Did not know you could use loops in outputs
Comment: If this answers your question, acceptance would be much appreciated.


LocalReport Receipt Printing

Question: I am printing a 3 inch receipt using a LocalReport with code from "Walkthrough: Printing a Local Report without Preview"
Some printers require the DeviceInfo PageWidth to be 8.5in to work correctly and some require 3.0in.  Its appears that the report is being stretched to fill a wrong sized page.  I have tried to adjust both the Report Paper Size and the Printer Paper size but can't seem to get the right combination.
Has anybody experienced this?
Answer: I figured this out.  You need to account for the printer dpi.
Get the Printer Default Page Settings:
<code>        PrinterSettings ps = new PrinterSettings();
        ps.PrinterName = printerName;
        this.defaultPageSettings = ps.DefaultPageSettings;
</code>
The Build the DeviceInfo Xml with that info:
<code>    private string BuildDeviceInfo()
    {
        StringBuilder returnValue;
        System.Xml.XmlWriter writer;

        returnValue = new StringBuilder(1024);
        writer = System.Xml.XmlWriter.Create(returnValue);

        writer.WriteStartElement("DeviceInfo");
        writer.WriteElementString("OutputFormat", "EMF");

        if (defaultPageSettings != null)
        {
            // DPI will keep the output from scaling in weird ways
            writer.WriteElementString("PrintDpiX", defaultPageSettings.PrinterResolution.X.ToString());
            writer.WriteElementString("PrintDpiY", defaultPageSettings.PrinterResolution.Y.ToString());

            writer.WriteElementString("PageWidth", (defaultPageSettings.PaperSize.Width / 100m).ToString("F2") + "in");
            writer.WriteElementString("PageHeight", (defaultPageSettings.PaperSize.Height / 100m).ToString("F2") + "in");
       }
        writer.Close();

        return returnValue.ToString();
    }
</code>
Answer: This worked for me.  I'm printing from a WPF app to a STAR TSP100 receipt printer.  When I set the margins & page size myself it came out huge, but when I calculated the minimum margins and page size as well as set the dpi from default printer settings the receipts printed correctly.
I used this to figure out the minimum margins: (H/T http://www.dreamincode.net/forums/topic/135864-printing-with-minimum-margins-specified-by-the-printer/)
<code>Dim minimumMarginLeft, minimumMarginRight, minimumMarginTop,
 minimumMarginBottom As Single

minimumMarginLeft = PrintDialog1.PrinterSettings.DefaultPageSettings.PrintableArea.Left

minimumMarginRight = PrintDialog1.PrinterSettings.DefaultPageSettings.PaperSize.Width - _
                                  PrintDialog1.PrinterSettings.DefaultPageSettings.PrintableArea.Right

minimumMarginTop = PrintDialog1.PrinterSettings.DefaultPageSettings.PrintableArea.Top

minimumMarginBottom =  PrintDialog1.PrinterSettings.DefaultPageSettings.PaperSize.Height - _
                                      PrintDialog1.PrinterSettings.DefaultPageSettings.PrintableArea.Bottom

-I figured this out. You need to account for the printer dpi.

-Get the Printer Default Page Settings:

        PrinterSettings ps = new PrinterSettings();
        ps.PrinterName = printerName;
        this.defaultPageSettings = ps.DefaultPageSettings; The Build the DeviceInfo Xml with that info:

    private string BuildDeviceInfo()
    {
        StringBuilder returnValue;
        System.Xml.XmlWriter writer;

        returnValue = new StringBuilder(1024);
        writer = System.Xml.XmlWriter.Create(returnValue);

        writer.WriteStartElement("DeviceInfo");
        writer.WriteElementString("OutputFormat", "EMF");

        if (defaultPageSettings != null)
        {
            // DPI will keep the output from scaling in weird ways
            writer.WriteElementString("PrintDpiX", defaultPageSettings.PrinterResolution.X.ToString());
            writer.WriteElementString("PrintDpiY", defaultPageSettings.PrinterResolution.Y.ToString());

            writer.WriteElementString("PageWidth", (defaultPageSettings.PaperSize.Width / 100m).ToString("F2") + "in");
            writer.WriteElementString("PageHeight", (defaultPageSettings.PaperSize.Height / 100m).ToString("F2") + "in");
       }
        writer.Close();

        return returnValue.ToString();
    }
</code>

LocalReport Receipt Printing


High server load with no processes using CPU?

Question: I'm new to managing servers, and I've run into something that's stumped me. I received a warning from my VPS provider informing me that my load usage was very high. I hadn't run into this problem before, so I attempted to look into it. Unfortunately I haven't been able to figure out why this is the case after quite a bit of research.
The server is, I believe, OpenVZ, with plenty of RAM to spare (2 GB) and a decent processor with a SSD. I've shut down nearly every process that I could imagine that might be an issue besides apache. I've inspected my top/htop output very carefully and I can't detect anything unusual. But notice the load average. It should be around 0 with this level of CPU usage, right?

I was wondering if it was maybe something to do with disk usage, but since this is OpenVZ apparently I can't use a tool like atop to determine more information about disk activity.
How can I debug this further? Thanks!
Comment: You can show IO with htop as well fish around the settings, also show advanced CPU usage, see if shows a core or two on full grey bars but no process using that much (as it is now in your screen), I've found it usually is something flushing stuff to disk and having a very high IO latency on the virtual host
Comment: Use `iotop` or similar to look at disk usage - did you review crontab and the /etc/cron.* to ensure something in there isn't hitting IO hard?
Comment: @albal: Thanks for your comment. There's nothing abnormal in any user's crontab; I checked them all. I will try to look further into IO.
Comment: `iotop` shows really nothing at all is using much of the disk, which is really quite unfortunate since I was hoping I would find the solution to my problem right there. Now I'm not sure what could be causing this.
Answer: As you're in a VPS environment:
Did you ever consider that the load is coming from the host? Maybe you have only 2 virtual CPU cores assigned and the host system is overcommitted or completely exhausted. Therefore your load is rising because any small request is taking a long time. This would explain the sluggish behaviour.
You should talk to your VPS Provider about this.
Answer: There are situations where you observe a high load average combined with low CPU usage, see this discussion for some possible reasons. The Wikipedia article on load is also pretty informative.
The problem is, some of these situations are harmless (I used to manage an Informix server on HPUX where the load average was equal to the number of configured Informix VPs, even when idle), when it's some kind of IO related it may slow processing down quite a lot - see the example in the linked article.
If the system "feels" responsive I wouldn't worry too much, but  as you have  server metrics available (I see you have sealion installed), I'd have a look at IO related values, it may help you understand your system better and avoid surprises later on.
Comment: Thanks for your response! Unfortunately the server does not feel responsive like it used to. In fact, it's quite sluggish. That's why I'm suspecting something is not right.


On the numbers of maximal subgroups of a $p$-group

Question: Let $G$ be a $p$-group, i.e. $|G|=p^n$. Call $\Phi(G)$ the Frattini group of $G$.
Then we have that $G/\Phi(G)\simeq(C_p)^d$ ($d$ copies of the cyclic group of order $p$, i.e. $\overbrace{C_p\times\cdots\times C_p}^{d-times}$), for some $d\in\mathbb N$. And till here it's all right.
Then my teacher said that the numbers of maximal subgroup of $G$ is
$$
\frac{p^d-1}{p-1}.
$$
What I can't understand is:

Why the numbers of maximal subgroups of a $p$-groups are of the form $$
\frac{p^m-1}{p-1}=1+p+p^2+\cdots+p^{m-1}
$$ for some $n\in\mathbb N$.
Why $m=d$, hence in which way $d$ is related to the numbers of maximal subgroup of $G$.

Any help would be appreciated so much. Thank you all.
Answer: Let $G=C_p\times C_p\times...\times C_p=(C_p)^d$ Since $C_p$ is a field, we can think $G$ as a vector space over $C_p$ with dimension $d$.
Notice that any $d-1$ dimensional subspace of  a vector space can be uniquely defined by a orthogonal complement of a $1$ dimensional subspace. Thus, it is enough to find number of the $1$ dimensional vector space.
We have $p^d-1$ nontrivial elements and  $\langle v\rangle=\langle cv\rangle$ where $c\in\{1,2,..,p-1\}$ which means we have $$\dfrac{p^d-1}{p-1}$$ one dimensional vector space, so we are done.
If $G$ is any $p$ group then there is one to coresspondence between maximal subgroups of $G$ and maximal subgroups of $G/\Phi(G)$ as $\Phi(G)\leq M$ for any $M$ which conclude the result.
Note: Above argument shows also that number of the subgroups of index $p$ is equal to number of the subgroups of order $p$ in elementary abelian groups.
Comment: Thank you! I noticed too the corrispondence between maximal subgroup of $G$ and maximal subgroups of $C_p^d$... but the maximal subgroups of $C_p^d$ are of the form $C_p^r\times1\times C_p^s$ where $r+s=d-1$ (obviously $r,s\in\mathbb Z_{\ge0}$), but this yelds to $d-1$ as the number of maximal subgroups of $G$. Where is my mistake?
Comment: @Joe: A subgroup of $H\times K$ need not be in the form $M\times N$ where $M\leq H$ and $N\leq K$ and to see this notice that $Z_p\times Z_p$ has $p+1$ maximal subgroup, (take $p$=2 and examine $Z_2\times Z_2$ you will find $3$ maximal subgroup not $2$)
Comment: @Joe: I guess you do not like my answers :)
Comment: You're right. His answer was more direct... however I must acknowledge that yours is smarter. Hence, sorry spin, seriously, but I have to change.
Comment: @mesel Sorry sir, i have a question. how we can conclude that number of the subgroups of index $p$ is equal to number of the subgroups of order $p$ in elementary abelian groups?
Comment: @Littlegirl: Let $V$ be a vector space over a finite field $F$ with dimension $n$. Notice that every one-dimensional subspace has a unique orthogonal complement, which is of dimension $n-1$. As an example, the space  $<(1,1,0)>$ has an orthogonal complement $W=\{(x,y,z) \mid x+y=0\}$. In our case, the subgroups of order $p$ is one dimensional space and maximal subgroups are of dimension $n-1$. Thus their cardinality are equal.
Comment: @ mesel Thank so much for your answer. Is it a Theorem in Linear Algebra, that every one-dimensional subspace has a unique orthogonal complement, which is of dimension $n−1$?
Comment: @Littlegirl: Yes, it is.
Comment: @mesel Thank you so much
Comment: @Littlegirl: you are welcome.
Comment: @mesel How is orthogonality even defined over finite fields? As far as I know, orthogonality only makes sense over $\mathbb{R}$ and $\mathbb{C}$.
Comment: whenever the inner product is zero.
Answer: Let $V = (C_p)^n$, which is a $n$-dimensional vector space over $C_p$. Then the number of $d$-tuples $(x_1, \ldots, x_d)$ of linearly independent vectors is $$f(n,d) = (p^n - 1)(p^n - p) \cdots (p^n -p^{d-1})$$
Now if $K$ is the number of $d$-dimensional subspaces, we have $K \cdot f(d,d) = f(n,d)$.
Hence
$$K = \frac{p^n -1}{p^d -1} \cdot \frac{p^{n-1}-1}{p^{d-1} -1} \cdots \frac{p^{n-d+1} -1}{p -1}$$
So when $d = n-1$, you get $K = \frac{p^n - 1}{p-1}$.
Since $\Phi(G)$ is contained in every maximal subgroup of $G$, you have a bijection between the maximal subgroups of $G$ and $G/\Phi(G)$. Combining this with the above result you have what you need.


Time Series anomalous local sequence detection

Question: What is the go to algorithm for finding an anomalous discord (sequence) in a time series given only the time series itself rather than being able to compare to other time series?
(I have access to Python and R.)
Comment: I would refer to the [paper](http://onlinelibrary.wiley.com/doi/10.1002/for.3980070102/abstract) by Tsay in 1989.
Answer: tsoutlier can be a reasonable attempt to detect anomalies. Unfortunately it assumes that an ARIMA model be prespecified prior to detection and does not work when stochastic causals are in play. In other words memory is more important / dominant. To identify an ARIMA model using freely available solutions requires that there are no outliers, constant error process and constant parameters over time which is flawed if there are anomalies present. Thus one needs to simultaneously identify anomalies and ARIMA model form (along with variance / parameter stability remedies) via a more comprehensive search process.


Question about my t-distribution

Question: I've been learning about the t-distribution for my stats class and while running some simulations in R to explore the concept, I've run into an issue. I don't know whether it arises from my code, or whether I have seriously misunderstood how t-distributions arise.
Below I've pasted my code and the graph it gives me. The dataset it works on  is heights from the dslabs package. It's a dataframe that contains two normally distributed recordings of heights, one for men and one for women. In total there are 1050 observations. I ran a Monte Carlo simulation 1000 times, each time sampling 10 observations randomly from the data, got the sample mean $\bar{x}$ and sample standard deviation $s$. The t-value is then
$t=\frac{\bar{x}-\mu}{\frac{s}{\sqrt{n}}}$ and it should have a t-distribution about 0. $\mu$ is the population mean of heights. I made a density plot of these t-values and also 1000 randomly generated normally distributed numbers with $sd= \frac{\sigma}{\sqrt{n}}$. This is the standard deviation of the distribution of sample means of samples of size n. It should be normally distributed.
Here's my code:
<code>n <- 5
tvalues <- replicate(10000,{
    X <- heights[sample(1:1050,size=n),] %>% pull(height)
    Xbar <- mean(X)
    s <- sd(X)
    tvalue <- (Xbar-mu)/(s/sqrt(n))
})
df1 <- data.frame(values=tvalues,category="tvalues")
normal_values <- rnorm(1000,mean=0,sd=sigma/sqrt(n))
df2 <- data.frame(values=normal_values,category="normal sample mean distribution")
df <- rbind(df1,df2)
df$category <- as.factor(df$category)
df %>% ggplot(mapping=aes(values,color=category)) + geom_density(bw=1)
</code>
and the graph I get

Shouldn't the t-distribution have fatter tails than the normal?
Answer: Yes, the t-distribution has heavier tails than the standard normal distribution. But, in your figure, you are comparing it with a normal distribution with standard deviation $\frac{\sigma}{\sqrt(n)} \ne 1$. If you change that to 1 and re-draw you should see what you expect.
Comment: Thanks, this makes sense, I was calculating t-values, and they need to be compared to the standard normal. t-values vs z-values.

Question about my t-distribution


Enterprise application framework supporting DDD

Question: I spent short time studing Habanero and i found it good approach for making Enterprise Application in a really short period of time.
The pattern witch Habanero use is "Active Record" as it's developers say.
My questions are:

There any similar application like Habanero witch fully support Domain
Driven Design by determining aggregate roots, entities and value objects
Is it right decision to use such tools in big organizations
Does it worth training our team on such a tool

thank you
Answer: Framework support for Domain Driven Design is quite different from frameworks supporting data driven applications. Such framework should increase the productivity of developers that works with an ubiquitous language that evolves with the business and that is learned by a domain-expert.
They should not face concepts like aggregates, root, value objects because they are just modelling concepts, conceptual tools, but ways to ease the development process. Thus a framework exposing abstract classes or interfaces named AggregateRoot, Entity or ValueObject is fundamentally broken. It doesn't provides any real value to an application, just useless indirections.
However:

There are a few frameworks designed to support domain driven design, listed here. Moreover, I'm developing one by myself based on previous experiences that worked very well
It depends, obviosly. For example we used all of the Epic's modeling patterns with success.
We used some "home made" framewoks too, and some of them proved to really increase productivity. However, such frameworks (if useful) always have steep learning curves and it depends very much on how much reliable the software have to be and what are the developers skills.
It depends on the framework, on the complexity of the business (if you don't need a domain expert to understand it, you don't need DDD) and on the developers, too. I faced successful stories and huge failures with different frameworks in different contexts. I've also had a conference that faced the topic (you can see the slides here).
Comment: A developer should be able to understand the code from the code itself or from its unit tests, not from "well written documentation" which is always out of date. I believe there should be no code documentation. If it's not clear from the code or its tests, refactor it so it's clear. That's why seeing that something is an aggregate root (implementing IAggregateRoot) or an entity (inheriting from Entity base class) immediately helps understanding the code.
Comment: "Thus a framework exposing abstract classes or interfaces named AggregateRoot, Entity or ValueObject is fundamentally broken. It doesn't provides any real value to an application, just useless indirections" - I don't agree with this, I'm successfully using similar framework ([CoreDdd](https://nuget.org/packages/CoreDdd)) to model domains on couple of projects. I think it helps a lot to be able to inherit from Entity or mark an entity as IAggregateRoot, my 2c
Comment: @xhafan I don't see much value in using DDD to send emails. A nice object model is not a domain model. If you don't need a domain expert to understand the business, you don't need DDD. If you have to understand one or more domain experts, handling aggregate roots is the last of your problem. You will have to learn his language and business deeply and you will have to model a complex, well documented, codebase that everybody else must be able understand quickly. If you know what an aggregate root is, you know that an interface cannot enforce invariants. Thus is needless.
Comment: @xhafan in most object oriented projects, you are right. In those 5% that require DDD, believe me: documentation is as important as code. Sometimes even more. In particular it's important in C# where we miss checked exceptions and the only way for a client to know what can go wrong with a call is to read up-to-date documentation. If the business rules are complex enough to require the hire of a domain expert and you have more that ten people that need to grasp it rapidly to be able to do their job, the code documentation (and vision statements) is really a must.
Comment: And note that this does not means that the code itself is not readable (on the contrary, domain models of mine often form internal DSLs), just that the ubiquitous language has to be explained, since you can find the same concept with slightly (or completely) different meaning and rules in different bounded contexts.
Comment: Example why comments are not needed: a very accepted answer which suggest "why" comments are good: http://stackoverflow.com/a/209089/379279 and a even better "no comment" solution for it: http://stackoverflow.com/a/210414/379279 I just believe that almost every comment can be transformed into a method name (even long) or baked into a code.
Comment: @xhafan I'm glad it works for you and your team. To me, I've read ton of (almost) undocumented C code and I had no problems with that. Still, in a DDD project I won't hire any modeler that refuses to document what he learn from the domain expert. Self documenting code is often fine for technological problems (like sending emails, tcp connections, device drivers and so on), but not in domain models.


$\int\limits_{-\infty}^{+\infty}f(x)\delta(dx)=f(0)$ proof

Question: $\int\limits_{-\infty}^{+\infty}f(x)\delta(dx)=f(0)$, where the delta stands for the Dirac measure. I encountered it, and I am not aware of the level of mathematical sophistication to understand this equality.
Anyway, I would like to know how this result is proven.
Thanks in advance!
Comment: Do you know what the Lebesgue integral is? Do you know what the Dirac measure is? It follows directly from the definition.
Comment: Well the definition of the Dirac measure is a good place to start. The equality is trivial after that.
Comment: @SangchulLee No this is not the definition of the Dirac measure. A measure is something that takes in sets and gives out a number. This is an integral
Comment: I am not the downvoter (although I am a prolific downvoter) but please read this: https://math.meta.stackexchange.com/questions/23486/can-we-be-nicer-to-downvoters
Comment: I know the Lebesgue integral, however I am not aware of the Dirac measure.
Comment: @ZacharySelk                 $\int_\mathbb{R}f d\delta=f\delta(\mathbb{R})=?$
Comment: What is your definition of the Dirac measure? The property in question is often taken as the definition of it.
Comment: @ZacharySelk                 $\delta(\mathbb{R})=0$, right?
Comment: $\delta(dx)$ is meaningless. Fix the typo.
Comment: @YvesDaoust                I quoted it from Wikipedia.
Comment: @YvesDaoust That is a perfectly acceptable notation for the Lebesgue integral
Comment: I guess you can write it in a more general way despite the fact it was not done with all the mathematical precision it should have.
Comment: Isn't that the definition of the Dirac $\delta$?
Comment: @avs not the Dirac measure though
Comment: @ZacharySelk Technically you are right. I was thinking about distributional definition of Dirac mass which is then identified as a measure via representation theorem.
Comment: @SangchulLee Yup, that's right.
Answer: Note:
$$\delta(A)=\begin{cases} 1 \text{ if } 0 \in A\\0 \text{ else}\end{cases}$$
So $$\int_{-\infty}^{\infty} f(x) \delta(dx)=f(0) \delta(\{0\})=f(0)$$
Comment: @zacharyselk Wow!  Thank you.  That made my week.  And may I return the compliment.
Comment: How do you get the $f(0)$?
Comment: @PedroGomes Define the Lebesgue integral
Comment: I got it! Thanks! So it means the dirac measue operates only on {0}, right?
Comment: $\delta(A)=\delta(0)=1$ if $0\in A$?
Comment: @PedroGomes Its support is just $0$, if that's what you mean
Comment: @PedroGomes If $\delta$ is a measure, $\delta(0)$ means no sense. But $\delta(A)=\delta(\{0\})=1$ if $0\in A$
Comment: @zacharyselk Zack, just curious ... What was your former user name?  Avid?
Comment: @Mark yeah avid19
Comment: Good to see you're back.
Comment: @Mark and you too Dr MV :) Your answers are always wonderful. I've had nothing but pleasant interactions with you. Thanks for all you do for this site.
Answer: Dirac measure $\delta_{x}$ at $x$ is a Borel measure defined by
$$
\delta_x(E)=\begin{cases}
1, & \mbox{ if }x\in E\\
0, & \mbox{ if }x\notin E
\end{cases},
$$
where $E\subseteq\mathbb{R}$ is a Borel set.
Given a Borel function $f:\mathbb{R}\rightarrow\mathbb{R}$, we have
$$
\int f\,d\delta_{x}=\int_{\{x\}}f\,d\delta_{x}+\int_{\{x\}^{c}}f\,d\delta_{x}=f(x)\delta_{x}(\{x\})+0=f(x).
$$


Android date and time

Question: I want to display current date and time using calendar.my code is
<code>    LinearLayout lview=new LinearLayout(this);
    myText=new TextView(this);
    strText=new TextView(this);

    Calendar c=Calendar.getInstance();
    int seconds=c.get(Calendar.SECOND);

    myText.setText("Your current seconds are:");
    strText.setText(seconds);

     lview.addView(strText);
     lview.addView(myText);

    setContentView(lview);
</code>
but it shows the app unfortunately stops working without displaying date..
Comment: You should get into the habit of posting Logcat output when you have an error or crash that you cannot solve.
Answer: Setting Layout Paramaters for each view will solve your problem
<code>lview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));\\Linear Layout
strText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); \\TextView
myText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));\\TextView
</code>

Android date and time


Proving equivalence of inverse trigonometric functions

Question: From integrating $\int\frac{1}{\sqrt{(t-a)(b-t)}} dt$ in two different ways, I have found two different functions:

$-\sin^{-1}\left (\frac{2t-a-b}{a-b} \right )$
$2 \tan^{-1}\left (\sqrt{\frac{t-a}{b-t}} \right )$

The question asks me to prove using trigonometry that these are equal results. I've plotted both of these in Desmos and they are the same except that 1 is always $\frac{\pi}{2}$ less than 2 (which the additive constant from the integral could account for), but I'm having difficulty proving that they are equal by trigonometry. I know I could show that they have the same derivative, and so they must be the same up to an additive constant, but I'm wondering how to prove it purely through trigonometry.
I've tried using the inverse tangent addition formula on 2, but it's still not leading anywhere - I think the $\pm \frac{\pi}{2}$ difference is causing the problem, and I don't know how to include it.
Any ideas on how to show the equality of 1) and 2)?
Answer: Well, 1) and 2) are equal up to an additive constant, i.e.
\begin{align}
2\arctan\left(\sqrt{\frac{t-a}{b-t}}\right)= C-\arcsin\left(\frac{b+a-2t}{b-a}\right).  \ \ \ (*)
\end{align}
Let us assume $a<t<b$ for convenience. Set
\begin{align}
\theta = \arctan\left(\sqrt{\frac{t-a}{b-a}}\right) \ \ \Rightarrow \ \ \tan^2\theta =\frac{t-a}{b-t}.
\end{align}
In particular, it follows
\begin{align}
\sec^2\theta = \tan^2\theta +1 = \frac{b-a}{b-t} \ \ \Rightarrow& \ \ \cos^2\theta = \frac{b-t}{b-a} \ \ \text{ and }\ \ \sin^2\theta = \frac{t-a}{b-a}\\
\Rightarrow&\ \ \ \cos(2\theta)= \cos^2\theta - \sin^2\theta = \frac{b+a-2t}{b-a}.
\end{align}
Substitute $\theta$ back into $(\ast)$ yields the equation
\begin{align}
2\theta = C - \arcsin\left( \cos(2\theta)\right) \ \ \Rightarrow \ \ \cos(2\theta) = \sin\left(C-2\theta\right) = \sin(C)\cos(2\theta) - \cos(C)\sin(2\theta).
\end{align}
Hence $\sin(C) = 1$ and $\cos(C) = 0$, which means $C = \frac{\pi}{2}$. Thus, we have the identity
\begin{align}
2\arctan\left(\sqrt{\frac{t-a}{b-t}}\right)= \frac{\pi}{2}-\arcsin\left(\frac{b+a-2t}{b-a}\right).
\end{align}
Answer: $-\sin^{-1}\left (\frac{2t-a-b}{a-b} \right ) = 2\tan^{-1}\left (\sqrt{\frac{t-a}{b-t}} \right )-\frac {\pi}{2}$
$\sin^{-1}\left (\frac{2t-a-b}{a-b} \right ) = \frac {\pi}{2} - 2\tan^{-1}\left (\sqrt{\frac{t-a}{b-t}} \right )$
take sin of both sides
$\left(\frac{2t-a-b}{a-b} \right ) = \sin \left(\frac {\pi}{2} - 2\tan^{-1}\left (\sqrt{\frac{t-a}{b-t}} \right )\right)$
$\sin (\frac \pi2 - x) = \cos x$
$\left(\frac{2t-a-b}{a-b} \right ) = \cos \left(2\tan^{-1}\left (\sqrt{\frac{t-a}{b-t}} \right )\right)$
$\cos 2x = 2\cos^2 x - 1$
$\left(\frac{2t-a-b}{a-b} \right ) = 2\cos^2 \left(\tan^{-1}\left (\sqrt{\frac{t-a}{b-t}} \right )\right)-1$
$\sec^2 x = \tan^2 x + 1\\
\cos^2 x = \frac 1{\tan^2 x + 1}$
$\left(\frac{2t-a-b}{a-b} \right ) = \frac 2{\tan^2 \left(\tan^{-1}\left (\sqrt{\frac{t-a}{b-t}} \right )\right)}-1$
$\tan (\tan^{-1} x) = x$
$\left(\frac{2t-a-b}{a-b} \right ) = $$\frac 2{\left (\frac{t-a}{b-t} \right )+1}-1\\
 \frac {2(b-t)}{b-a}-1\\
 \frac {2b-2t-b+a}{b-a}\\
 \frac {2t + b - a}{a-b}$


How to prove a derivative exists in terms of $\varepsilon$ and $\delta$

Question: If f'(a) exists, show that $f'(a) = \lim_{h\to 0} \frac {f(a+h) - f(a-h)}{2h}$
I have proven it in terms of a, by using $1/2 \lim_{h\to 0} \frac {f(a+h)-f(a)}{h} + 1/2 \lim_{h\to 0} \frac {f(a-h)-f(a)}{-h} = f'(a)$.
How do you prove this in terms of $\varepsilon$ and $\delta$.
Comment: Thanks for the edit... I'm new to the site
Answer: Given $\epsilon>0$, we have some $\delta>0$ such that $\left|\dfrac{f(a+u)-f(a)}{u}-f'(a)\right|<\epsilon$ for all $0<|u|<\delta$.
For $0<|h|<\delta$, then $0<|-h|<\delta$ of course, so
\begin{align*}
\left|\dfrac{f(a-h)-f(a)}{-h}-f'(a)\right|<\epsilon,
\end{align*}
and
\begin{align*}
\left|\dfrac{f(a+h)-f(a)}{h}-f'(a)\right|<\epsilon,
\end{align*}
so
\begin{align*}
&\left|\dfrac{f(a+h)-f(a-h)}{2h}-f'(a)\right|\\
&=\dfrac{1}{2}\left|\dfrac{f(a+h)-f(a)}{h}-f'(a)+\left(\dfrac{f(a-h)-f(a)}{-h}-f'(a)\right)\right|\\
&\leq\dfrac{1}{2}\left[\left|\dfrac{f(a+h)-f(a)}{h}-f'(a)\right|+\left|\dfrac{f(a-h)-f(a)}{-h}-f'(a)\right|\right]\\
&<\dfrac{1}{2}(\epsilon+\epsilon)\\
&=\epsilon.
\end{align*}
Comment: Thank you! Seems kinda trivial now
Answer: You can just sum and subtract $f(a)$ in the numerator and solve the limit directly. But I'll indulge you: let $\epsilon > 0$. Since you know that the derivative exists, there is $\delta>0$ such that $$0<|h|<\delta\implies\left|\frac{f(a+h)-f(a)}{h}-f'(a)\right|<\epsilon. $$Now, assume $0 <|h|<\delta$. Then  $$\begin{align} \bigg|\frac{f(a+h)-f(a-h)}{2h}&- f'(a)\bigg| = \left|\frac{f(a+h)-f(a)+f(a)-f(a-h)}{2h} - f'(a)\right| \\ &=  \left|\frac{f(a+h)-f(a)}{2h} - \frac{f'(a)}{2} +\frac{f(a)-f(a-h)}{2h} - \frac{f'(a)}{2}\right| \\ &\leq \frac{1}{2} \left|\frac{f(a+h)-f(a)}{h}-f'(a)\right|+\frac{1}{2}\left|\frac{f (a)-f (a-h)}{h}-f'(a)\right| \\ &=\frac{\epsilon}{2} +\frac{\epsilon}{2} = \epsilon,\end{align} $$as wanted.


centOs : system time getting reset back to UTC after changing it using timedatectl

Question: I have a Centos machine with version 7.  I am trying to change the system time using the timedatectl command. The time gets changed but after a few seconds it gets reset back to it's original time.
[root@abcd ~]# timedatectl
  Local time: Tue 2018-10-16 05:51:30 UTC
  Universal time: Tue 2018-10-16 05:51:30 UTC
  RTC time: Wed 2019-10-16 03:40:38
  Time zone: UTC (UTC, +0000)
  NTP enabled: no
  NTP synchronized: no
  RTC in local TZ: no
  DST active: n/a
[root@abcd ~]#
[root@abcd ~]# timedatectl set-time "2019-10-16 05:51:30"
[root@abcd ~]# timedatectl
  Local time: Wed 2019-10-16 05:51:32 UTC
  Universal time: Wed 2019-10-16 05:51:32 UTC
  RTC time: Wed 2019-10-16 05:51:33
  Time zone: UTC (UTC, +0000)
  NTP enabled: no
  NTP synchronized: no
  RTC in local TZ: no
  DST active: n/a
[root@abcd ~]# timedatectl
    Local time: Tue 2018-10-16 05:54:38 UTC
    Universal time: Tue 2018-10-16 05:54:38 UTC
    RTC time: Wed 2019-10-16 05:52:35
    Time zone: UTC (UTC, +0000)
    NTP enabled: no
    NTP synchronized: no
    RTC in local TZ: no
    DST active: n/a
[root@abcd ~]#

When I check the systemd logs using journalctl -f command, I notice that there is a process which is changing the system time to UTC after 80 sec approximately. I have no clue what this process is. Those logs are
Oct 16 06:01:39 abcd systemd[1]: Time has been changed
Oct 16 06:02:58  abcd systemd[1]: Time has been changed

How do I debug this ?
Comment: What is there to debug? Looks like it works as intended to me.
Comment: It doesn't. If I change the timezone, it still goes back and sets it to UTC. The question is, what is the process/daemon which is doing this change.
Comment: Try to check using ps -ef  | grep time*
Comment: @user1851006 Did you ever figure this out?  I'm seeing a similar behavior on another version of Linux.
Answer: just try setting timezone.
# timedatectl set-timezone *your timezone*

Comment: You are setting the time.  You need to set the timeZONE as @aroN indicates.  Alternatively, you can change the timezone by deleting `/etc/localtime` and creating it as a new symlink as here:  `~ 0$ ls -l /etc/localtime`

`lrwxrwxrwx. 1 root root 27 Sep  7 12:57 /etc/localtime -> /usr/share/zoneinfo/MST7MDT`
Comment: Changing timezone doesn't work either. If I change the timezone to say, CDT, it sets it back to UTC after 80 sec. I want to know which process/daemon is doing this
Answer: If this is a virtual guest, some guest integrations sync the time of the host to the guest. Check that the hypervisor is syncing time with NTP, so this time is at least correct.
If you want to run in the wrong time for some reason, please edit your question to add why, and which virtual platform you use.
Comment: This isn't a virtual guest.
Comment: You can trace system calls to find out what is doing this.  On Linux, try using auditd to  log stime() and  settimeofday().