Prediction of continuous variable using "bnlearn" package in R

Question: I use bnlearn package in R to learn the structure of my Bayesian Network and its parameters. What I want to do is to "predict" the value of a node given the value of other nodes as evidence (obviously, with the exception of the node whose values we are predicting).
I have continuous variables.
library(bnlearn)                       # Load the package in R
data(gaussian.test)
training.set = gaussian.test[1:4000, ] # This is training set to learn the parameters
test.set = gaussian.test[4001:4010, ]  # This is test set to give as evidence
res = hc(training.set)                 # learn BN structure on training set data
fitted = bn.fit(res, training.set)     # learning of parameters
pred = predict(fitted$C, test.set)     # predicts the value of node C given test set
table(pred, test.set[, "C"])           # compares the predicted value as original

Now, this code works well and gives a table in which you can see that predicted values for node C are exactly same as the original value of node C in test set.
I do not understand the reason for that, could someone please explain it?
I know, I am providing entire df of test set that already has the value of node C in it. But if I give the data of other columns, it gives an error. So, I tried an alternative of putting other values to 0.
test.set$C = 0                     # To not give the original value of node C as evidence
pred = predict(fitted$C, test.set) # predicts the value of node C given test set
table(pred, test.set[, "C"])       # compares the predicted value as original

Is this approach wrong? (Using "NA" is not allowed.)
Answer: Why are you using table to compare the output? Using cbind to put the actual and predicted values side by side shows that the predictions are not the same as the actual, and you can compute standard accuracy metrics to quantify the degree to which they diverge.
library(bnlearn)                       # Load the package in R
library(forecast)

data(gaussian.test)
training.set = gaussian.test[1:4000, ] # This is training set to learn the parameters
test.set = gaussian.test[4001:4010, ]  # This is test set to give as evidence
res = hc(training.set)                 # learn BN structure on training set data
fitted = bn.fit(res, training.set)     # learning of parameters
pred = predict(fitted, "C", test.set)  # predicts the value of node C given test set
cbind(pred, test.set[, "C"])           # compare the actual and predicted
accuracy(f = pred, x = test.set[, "C"])

Comparing the actual and predicted:
> cbind(predicted = pred, actual = test.set[, "C"])
       predicted    actual
 [1,]  3.5749952  3.952410
 [2,]  0.7434548  1.443177
 [3,]  5.1731669  5.924198
 [4,] 10.0840800 10.296560
 [5,] 12.3966908 12.268170
 [6,]  9.1834888  9.725431
 [7,]  6.8067145  5.625797
 [8,]  9.9246630  9.597326
 [9,]  5.9426798  6.503896
[10,] 16.0056136 16.037176

Measuring accuracy of prediction:
> accuracy(f = pred, x = test.set[, "C"])
                ME      RMSE       MAE      MPE     MAPE
Test set 0.1538594 0.5804431 0.4812143 6.172352 11.26223

Comment: @lovedynasty The interface of `bnlearn:::predict.bn.fit` appears to have changed. I have updated my code to account for that change.
Comment: I get an error
Error in is.constant(y) :
  (list) object cannot be coerced to type 'double'

In
pred = predict(fitted$C, test.set)
Any idea, why?
Comment: @lovedynasty What line do you get that error on?
Comment: In line,

predict(fitted$C, test.set)
Comment: @lovedynasty You will have to post a complete reproducbile example with your data to diagnose. I am assuming that the above example runs fine.
Comment: The problem is with the above example. It doesn't run. I get an error at predict.
Answer: For both the predicted sets you proposed (with both the Original values and zeros) I found the same output in R.
[1]  3.5749952  0.7434548  5.1731669 10.0840800 12.3966908  9.1834888  6.8067145
[8]  9.9246630  5.9426798 16.0056136

This shows that the values of C are irrelevant. Furthermore, test.set$c provides you with:
[1]  3.952410  1.443177  5.924198 10.296560 12.268170  9.725431  5.625797  9.597326
[9]  6.503896 16.037176

which is inherently different from the predicted output. This leads me to believe that your code is in fact correct.
Answer: The equivalent for the discrete case occurs (inability to set the target variable to zero).
In this case do the following:
test.set\$TARGET<-as.factor(0)
levels(test.set\$TARGET) <- c(level1,level2,level3...)


Comparing log likelihood & AIC for two spatial error regression models with the same dependent but different independent variables

Question: I have two spatial lag models using the same dependent variable (average income) and different independent variables (1- living environment deprivation; 2- education deprivation) for towns in the UK.
I would like to see which model accounts for greatest variation, hence should I compare r squared or log likelihood and AIC values to determine this?
I have read on forums that the log likelihood can only be compared for models with the same data, so does this mean I cannot compare them if the independent variables are different?
Thank you.
Answer: What purpose does a model comparison serve if your independent variables are identical?
You can use either measure to compare your models. One limitation of $R^2$ is that you should not compare models with different numbers of independent variables. In that case you need the adjusted $R^2$.


Unlock SATA SSD locked with Dell's HDD password option in BIOS

Question: Latest problem is a locked SATA disk. It is a Samsung 870 QVO SSD. It has been locked a long time ago with the Dell BIOS password utility. But because an admin password was set, the system never prompted the disk password. The admin password is deleted now, however the SATA password is still set. The password is unknown. The data is gone for good and I got a backup, just want to be able to format & use the drive again.
On my way to a solution I've tried multiple suggested fixes. With a bootstick I tried to use SEDutil for unlocking - but the SSD is not locked with the "new" Opal algorithm, so SEDutil was not able to help with a PSID revert. Later I tried to use UBCD, but the password tool there was unable to detect the disk.
There seem to be a few other people having this issue. Some RMA'd their drive, others went ahead with hdparm. sudo hdparm -I /dev/sda finally recognized the SSD and even printed out basic information about the SSD. The next step - unlocking the drive - failed. I've tried both a random user password and the Samsung master password, which seems to be 32 t's. Both times I've got an Illegal Request Error. I doubt this is hdparams way of telling me the password is wrong. The drive is not frozen.
Here is a copy of the hdparm output.
Dell has a Data Wipe option included in the BIOS, it did not do anything to the locked drive. Inserting the 32 t's in the password field did not wipe the drive, neither did using the previous admin password.
Hopefully someone of you has an idea. In the meantime I'll keep on debugging this and report back.
Comment: That is exactly how hdparm tells you that the password is wrong.
Answer: Well, let me report back quickly. The system in question has a Dell ProSupport contract attached to it and as I was able to research the Dell BIOS automatically generates a master password when setting a user SATA-password in the BIOS. To get the master password I had to confirm the system belongs to me and the Dell technican then supplied the master (recovery) password. Typed it in the Dell unlock prompt, it seemingly unlocked and told me "secure erase completed successfully". But after a reboot the drive was still locked.
After the call with Dell I tried to unlock the drive using the hdparm program mentioned earlier. But I still got the Illegal Request Error. Both the Dell technican and I are of the opinion it is a hardware fault. Looks like I'll have to get it RMA'd. Closing here, as I'll no longer be able to try other things out. At least for me the question is solved, hopefully others have better luck with the Dell master password.
Thank you!


What's the meaning of bits in '/usr/include/c++/4.4/bits/'

Question: What's the meaning of bits in '/usr/include/c++/4.4/bits/'
Linux, gcc of course.
Answer: The official designation of that folder according to the libstdc++ documentation is:

"Files included by standard headers
  and by other files in the bits
  directory"

Where "bits" probably just means something trivial as "the bits that make up the implementation of what you include via the standard headers".
For example, if you include the standard <algorithm> header, you really include bits/c++config.h, bits/stl_relops.h, bits/stl_pair.h bits/stl_algobase.h and bits/stl_algo.h under the hood, each of which defines the odd bits that alltogether give you what someone including <algorithm> would expect to get.
Boost calls the conceptually same folder "detail".
Comment: "detail" seems more intuitive.
Answer: It means that the file is internal to gcc's implementation of the standard library, and you shouldn't include it directly. Where the name "bits" came from, I don't know.
Comment: I think the meaning is that it includes values (bits) that are platform-dependant.


Scald: themable atom reference – where to find image path etc.?

Question: I can't find a way how to get an atom reference's values (image path etc.) into my theme template. When printing the node array I do get the SID for the referenced image, but I just don't know how to load the actual details.
Or is it possible by simply using node_load or entity_load or the like? Any pointers gladly appreciated.
Answer: Found the answer to my question one of scald's issue pages – and it's not really complicated. Either it's just not well documented, or I just didn't see it:
This gets the SID from the node's array:
$img = $vars['node']->field_teaser_image['und'][0]['sid'];

And this fetches the atom reference's object:
$atom = scald_atom_load($img);

This is how I then load the title of the atom reference image inside template.php:
$vars['img_title'] = $atom->title;

And the actual filename is inside another object base_entity:
$vars['img_filename'] = $atom->base_entity->filename;

Hope this may help somebody some day.


Mongo utf-8 exception handling

Question: I have a problem with inserting data to mongodb.
$name = $_REQUEST['name']; // "Iñtërnâtiônàlizætiøn";
$db->table->insert(
   array('name' => $name)
);

This gives mongo exception "Fatal error: Uncaught exception 'MongoException' with message 'non-utf8 string:...."
$name = mb_convert_encoding($_REQUEST['name'], 'ISO-8859-1', 'UTF-8');
Helps to fix the issue. But is there a way to force php to set all incoming data to utf-8, so I won't need to use mb_convert_encoding for each data?
I tried
mb_internal_encoding('UTF-8');
iconv_set_encoding('input_encoding', 'UTF-8');
iconv_set_encoding('internal_encoding', 'UTF-8');

None of those helped.
Even
mb_detect_encoding($_REQUEST['title']);

gives: 'UTF-8' but mongo exception still occures.
Comment: Watch out [the order for the parameters of `mb_convert_encoding`](http://php.net/manual/fr/function.mb-convert-encoding.php), you are converting *from* UTF-8 *to* ISO.
Answer: If the data is coming from a browser, the browser will send data in same encoding that your page is declared as. But to a public server arbitrary data can come from anywhere, so you should always validate that the incoming data is all well-formed UTF-8 before doing anything. Frameworks like Codeigniter do this.
To declare page encoding, you can use the Content-Type http header:
header("Content-Type: text/html; charset=UTF-8");

Note that this only declares encoding, it doesn't convert anything to UTF-8 by itself. To ensure your PHP string literals are UTF-8, you need to save your PHP source files in UTF-8 encoding.
Do not use mb_detect_encoding. To see if something is UTF-8:
if( !mb_check_encoding($str, "UTF-8"))
{
    header("HTTP/1.1 400 Bad Request");
    die("Malformed UTF-8");
}

However according to comments, mb_check_encoding is bugged in PHP <5.3:

The issue whereby mb_check_encoding($string,'UTF-8') falsely returns
  true for invalid UTF8 byte sequences was resolved somewhere between
  PHP 5.2.0 and 5.2.6

Mongo utf-8 exception handling


Auto Close Alert após consulta no Banco de Dados

Question: estou tentando fechar um alerta automaticamente após o usuário realizar cadastro/login.
O alerta está funcionando numa boa, assim que a consulta no Banco de Dados é realizada o alerta aparece na tela.
Porém eu gostaria que o alerta sumisse mesmo que o usuário não o feche.
Meu código está assim:

<link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" />

  <?php
  if($_SESSION['status_cadastro']):
  ?>

      Cadastro efetuado! Faça login informando seu e-mail e senha.
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

  <?php
  endif;
  unset($_SESSION[status_cadastro]);
  ?>

  <?php
  if($_SESSION['usuario_existe']):
  ?>

      Este e-mail já está em uso. Utilize-o para login ou informe outro.
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

  <?php
  endif;
  unset($_SESSION[usuario_existe]);
  ?>

Eu tentei utilizar o seguinte JavaScript:
$(document).ready(function() {
  // show the alert
  setTimeout(function() {
    $(".modalBanner").alert('close');
  }, 2000);

});

Porém ainda não obtive sucesso. O alerta só é mostrado após o php consultar os e-mails no banco de dados.
Answer: Opa, então, não tem como fazer isso que você quer, fechar esse alert que estaria no browser. Como referência peguei esse link no SO da gringa: https://stackoverflow.com/questions/463368/javascript-close-alert-box
O que você pode fazer, e na minha opinião é ate melhor, por ser mais moderno e ter uma usabilidade melhor é criar um alerta no html mesmo e manipulá-lo, daí você fechar ele automaticamente quando bem entender.

    $('#cadastro').click(function() {
        $('#alert').fadeIn(300)

        setTimeout(function() {
            close()
        }, 2000)
    })

    $("#close").click(() => close())

    function close() {
        $('#alert').fadeOut(200)
    }
    #alert {
        display: none;
        position: absolute;
        left: 35%;
        width: 20%;
        border: 1px solid black;
        border-radius: 5px;
        padding: 10px;
        text-align: center;
    }

    #alert .footer {
        margin-top: 10px;
        padding-top: 10px;
        border-top: 1px solid #aaa;
    }

    <button id="cadastro">
        Cadastrar
    </button>

        Cadastro efetuado com sucesso :)

            <button id="close">OK</button>

Taí um exemplo bem feio mas funcional, espero ter ajudado!!
Comment: ok, vou marcar aqui
Comment: Cara, desculpa a demora. Marquei a sua resposta como aceita. Alguém me deu markdown, se puder me dar uma moral e der um útil te agradeço. Valeu!!


Java generics with inheritance

Question: I have this structure of classes :
public class NFAddress

public class NFAddresses<T extends NFAddress> extends ArrayList<NFAddress>

public class NFMutableAddress extends NFAddress

public class NFMutableAddresses<T extends NFMutableAddress> extends NFAddresses<NFMutableAddress>

When I try to access objects in NFMutableAddresses
for (NFMutableAddress nucleusAddress : this)
        {
           object are defined as NFAddress and not NFMutableAddress
        }
Thanks for your help.
Comment: What is your question?
Comment: What are you trying to do?
Comment: there is almost never a reason to extend ArrayList
Comment: I need to add a save method for dirty and new objects...
Answer: Try these class definitions instead:
public class NFAdressess<T extends NFAddress> extends ArrayList<T>
public class NFMutableAddresses<T extends NFMutableAddress> extends NFAddresses<T>

What is changed in comparison to your classes is that the generic parameter T is forwarded to the class being extended. This parameter T can be anything that (in the first case) extends the NFAddress (so it can be NFMutableAddress or anything else that extends any of those two).
Comment: When using this.add() I can  actually only pass T beaucause it extends ArrayList. See code there http://pastebin.com/THEfzACV
Comment: Actually I've found how to do it : `this.add((T) new NFAddress());`

Java generics with inheritance


Setting Apache to run multiple django apps on the same domain with virtual hosts

Question: I want to have two different django apps on the same host. This is my default virtual hosts configuration file (this works).
WSGIPythonHome /home/user/.virtualenvs/project1
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        WSGIDaemonProcess project1 processes=4 threads=10 display-name=%{GROUP}
        WSGIProcessGroup project1
        WSGIScriptAlias /project1 /home/user/project1/project1/wsgi.py
        Alias /project1/static/ /home/user/project1/project1/staticfiles/
</VirtualHost>

The problem is WSGIPythonHome directive which cannot be inside the VirtualHost tag. So, I can't have different projects in the same default configuration file. It has to be somewhere else.
I tried to disable WSGIPythonHome and use home=/home/user/.virtualenves/project1 parameter in WSGIDaemonProcess, instead, as described in the documentation, but my application didn't work (I get an import error while trying to load wsgi.py file. Strangely, my project works fine if I only use WSGIPythonHome).
What I want is to have my other django project:
WSGIPythonHome /home/user/.virtualenvs/project2
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        WSGIDaemonProcess project2 processes=4 threads=10 display-name=%{GROUP}
        WSGIProcessGroup project2
        WSGIScriptAlias /project2 /home/user/project2/project2/wsgi.py
        Alias /project2/static/ /home/user/project2/project2/staticfiles/
</VirtualHost>

But I can't put this in the same default file (in /etc/apaches2/sites-available). I tried adding a default-001 file in there and restarted Apache but it didn't work.
So, where should I put my second django project configuration?
UPDATE. This is my wsgi.py file
import os, sys, site
site.addsitedir('/home/user/.virtualenvs/project1/lib/python2.7/site-packages')
activate_this = os.path.expanduser("/home/user/.virtualenvs/project1/bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project1.settings")
project = '/home/user/project1/'
workspace = os.path.dirname(project)
sys.path.append(workspace)
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Comment: You can create multiple sites in `sites-available`, each having a different file name. But you also need to enable them, not only restart the server.
Comment: Can you explain why you are trying to do this via WSGIPythonHome? Usually you set up the virtualenv in the wsgi file itself, as described in both Django and mod_wsgi documentation.
Comment: I tried this, and it is not working. I have set up correctly the virtualenv in wsgi.py and it works. I am using the same wsgi.py for all my applications and it is working. I have updated my answer to include it. If I don't add the WSGIPythonHome directive, my app is not working.
Comment: instead of `*:80`, have you tried `_default_:80` (without the WSGIPythonHome)
Comment: @dan-klasson. Yes, I tried that but I don't know how to make Apache load all vhost configuration files in `sites-available/` directory. I assume I cannot apply `a2ensite`, or can I?
Comment: You sure can. That's what it's for. Then they should show up in `sites-enabled`
Comment: @dan-klasson Great. I thought that `a2ensite` was only for config files regarding different subdomains, only (i.e. sub1.example.com, sub2.example.com, etc). I think it works, now. Can you make it an answer so I can accept it?
Comment: Glad it worked out for you.
Answer: You can create multiple virtual host configs in Apache. Create a new config file in the folder sites-available. Enable that site by running a2ensite and then restart Apache.


Loading file to neo4j using JS

Question: I'm doing a project on Neo4j.
The project is an HTML page were I receive information and I'm exporting the data to a file in a local directory using JS and then I need to load the file into Neo4j.
How can I load the file to Neo4j using JS?
Thanks.
Answer: Try creating a CSV of the data you are receiving. Then you can insert it using cypher.
Example:
<code>USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:/specify_your_path/customers.csv" AS row
CREATE (:Node_lable{properties});
</code>
to access the correct location of CSV you've to put your CSV in
OR
You can go through neo4j-driver npm library. Using this you can embed the database connection in your code and directly insert your data into neo4j.
Hope this helps!
Comment: Thank you for your response.
Comment: was it useful?.
Comment: I'm not doing that way anymore, I'm trying to connect directly to Neo4j using JavaScript.

Loading file to neo4j using JS


ERPTable columns being truncated

Question: I've generated some proxy ERPTables to query SAP tables. The columns are generated as type string. Since ERPConnect Linq doesn't seem to support join, like or basically any query in the where clause more complex than equality comparisons, I had to split the join in several individual queries and do the joins in C#. The problem is that some of the GUID key columns are coming truncated to 16 characters.
I've been trying to investigate this but the ERPTable doesn't seem to have any adjustable parameter for this. I highly suspect that is some shanenigan in the SAP side but I don't know what checks to do in order to constrain the source of the problem.
Has anyone experienced this problem with ERPConnect?
Comment: +1 for the question, i feel your pain as I have to deal with this sort of stuff all the time due to the nature of the business and the extreme use of SAP to run our business.
Comment: Could you please list the tables and the exact type (data element) of the GUID fields?
Answer: you need to use the custom function "Z_XTRACT_IS_TABLE" like described in the Help in the lower part (Table Access Restrictions):
http://help.theobald-software.com/ERPConnect-EN/default.aspx?pageid=reading-sap-tables-directly-with-readtable
If you are using Linq you can find it here:
http://help.theobald-software.com/ERPConnect-EN/default.aspx?pageid=linq-to-sap-table-access-restrictions
This is an SAP Restriction, and when using the default function module, only the first 16 chars are sent.
Best Regards,
Ali

ERPTable columns being truncated


What is the format of specifying 'http' repositories in /etc/apt/sources.list?

Question: After specifying the url of the repository, what do the tags like 'stable','non-free' mean in the entries of /etc/apt/sources.list ? If we know the url of a repository, how do we decide about these additional attributes while adding an entry in /etc/apt/sources.list ?
Answer: Section 2.1 of the following page (reproduced below for ease of use) is what you want.
2.1 The /etc/apt/sources.list file
As part of its operation, APT uses a file that lists the 'sources' from which packages can be obtained. This file is /etc/apt/sources.list.
The entries in this file normally follow this format:
 deb http://host/debian distribution section1 section2 section3
 deb-src http://host/debian distribution section1 section2 section3

Of course, the above entries are fictitious and should not be used. The first word on each line, deb or deb-src, indicates the type of archive: whether it contains binary packages (deb), that is, the pre-compiled packages that we normally use, or source packages (deb-src), which are the original program sources plus the Debian control file (.dsc) and the diff.gz containing the changes needed for `debianizing' the program.
We usually find the following in the default Debian sources.list:
 # See sources.list(5) for more information, especially
 # Remember that you can only use http, ftp or file URIs
 # CDROMs are managed through the apt-cdrom tool.
 deb http://http.us.debian.org/debian stable main contrib non-free
 deb http://non-us.debian.org/debian-non-US stable/non-US main contrib non-free
 deb http://security.debian.org stable/updates main contrib non-free

 # Uncomment if you want the apt-get source function to work
 #deb-src http://http.us.debian.org/debian stable main contrib non-free
 #deb-src http://non-us.debian.org/debian-non-US stable/non-US main contrib non-free

These are the lines needed by a basic Debian install. The first deb line points to the official archive, the second to the non-US archive and the third to the archive of Debian security updates.
The two last lines are commented out (with a `#' in front), so apt-get will ignore them. These are deb-src lines, that is, they point to Debian source packages. If you often download program sources for testing or recompiling, uncomment them.
The /etc/apt/sources.list file can contain several types of lines. APT knows how to deal with archives of types http, ftp, file (local files, e.g., a directory containing a mounted ISO9660 filesystem) and ssh, that I know of.
Do not forget to run apt-get update after modifying the /etc/apt/sources.list file. You must do this to let APT obtain the package lists from the sources you specified.
Answer: Each repository can decide how they wish to structure their packages.
Some provide "standard" naming, such as stable, unstable and non-free, but each can differ - adding sarge, potato and more.
One such provider can be seen on Opera's site, here. As you browse the directory strcuture, you can see how the deb directives match with the actual URL being used.
Answer: If you know the URL of a repository you can lookup the dists sub-directory to find out all the distributions that are available in that repository. If you enter those directories you can find out a Release file that lists the available sections in a Component field.
Example with the official Debian repository: http://ftp.debian.org/debian/
The distributions available can be seen at: http://ftp.debian.org/debian/dists/
If you take the lenny distributione you can grab the Release file here: http://ftp.debian.org/debian/dists/lenny/Release
Inside that file you can find the list of sections:
Components: main contrib non-free

And like people have already explained, in /etc/apt/sources.lists you have lines in the following format:
deb repository-url distribution section1 section2 section3

Now you can explore any well-maintained Debian repository !


calling javascript function on click of button in JSP

Question: I have a javascript function in jsp page like this:
function shutDownall(){
  alert(document.forms[0].Name.value);
  var app_nm=document.forms[0].Name.value;
  alert(app_nm);
  document.forms[0].action="<%=request.getContextPath()%>/controller?eventName=shutDownall&appname=" +app_nm;
  document.forms[0].submit();
  return true;

}

and a button like this which calls javascript function:
<button type="button" onclick="javascript:shutDownall();">shutdown servers</button>

where the javascript function is calling a method declared in action class. And button calls the javascript function calling java method. But when i click the shutdown server button nothing happens, not able to debug it. please help.
Comment: cleared Temp files??
Comment: yes i cleared temp files
Comment: check web browser error console
Answer: if you are using the script in separate page be sure that the script file is included in the head of the page , but if the script in the same page you have to put this script before that button.
Comment: i am using script in same page which script we should put before button?
Comment: this script put it in the head

function shutDownall(){
  alert(document.forms[0].Name.value);
  var app_nm=document.forms[0].Name.value;
  alert(app_nm);
  document.forms[0].action="<%=request.getContextPath()%>/controller?eventName=shutDownall&appname=" +app_nm;
  document.forms[0].submit();
  return true;

}

and the button but it like this

shutdown servers


How can I dynamically read a classes XmlTypeAttribute to get the Namespace?

Question: I need to read the XmlTypeAttribute from the following class, to get the Namespace value:
<System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42"),  _
System.SerializableAttribute(),  _
System.Diagnostics.DebuggerStepThroughAttribute(),  _
System.ComponentModel.DesignerCategoryAttribute("code"),  _
System.Xml.Serialization.XmlTypeAttribute([Namespace]:="http://webservices.micros.com/ows/5.1/Availability.wsdl")>  _
Partial Public Class AvailabilityRequest
Inherits AvailRequestSegmentList

Private summaryOnlyField As Boolean

Private xsnField As System.Xml.Serialization.XmlSerializerNamespaces

'''<comentarios/>
<System.Xml.Serialization.XmlAttributeAttribute()>  _
Public Property summaryOnly() As Boolean
    Get
        Return Me.summaryOnlyField
    End Get
    Set
        Me.summaryOnlyField = value
    End Set
End Property

With the following code,  I can get a value for the System.SerializableAttribute but I cannot retrieve information about XmlTypeAttribute.
var ar = typeof (AvailabilityRequest).GetType();
ar.GetCustomAttributes(true);

Update 2011.12.29
The following code now works:
    var xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(
                          typeof(AvailabilityRequest),
                          typeof(XmlTypeAttribute)
                       );
   XNamespace ns = xmlAttribute.Namespace;
   ns.NamespaceName.Should().Be.EqualTo("http://webservices.micros.com/ows/5.1/Availability.wsdl");

Answer: The Attribute class has static method called GetCustomAttribute.
Here's the usage:
XmlTypeAttribute xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(
                                   typeof(theType),
                                   typeof(XmlTypeAttribute)
                                 );
XNamespace ns = xmlAttribute.Namespace;

Comment: thanks Perry that work, just change in theType for typeof that for classes
Comment: @Carlos - method syntax fixed


Are multiple comparisons corrections necessary for informal/visual "multiple comparisons"?

Question: I have a sort of philosophical question about when multiple comparison correction is necessary.
I am measuring a continuous time varying signal (at discrete time points). Separate events take place from time to time and I would like to establish if these events have a significant effect on the measured signal.
So I can take the mean signal that follows an event, and usually I can see some effect there with a certain peak. If I choose the time of that peak and do say a t-test to determine if it is significant vs when the event doesn't occur do I need to do multiple comparison correction?
Although I only ever performed one t-test (calculated 1 value), in my initial visual inspection I selected for the one with the largest potential effect from the (say) 15 different post delay time points I plotted. So do I need to do multiple comparison correction for those 15 tests I never performed?
If I didn't use visual inspection, but just did the test at each event lag and choose the highest one, I surely would need to correct. I am just a little confused as to whether I do need to or not if the 'best delay' selection is made by some other criterion than the test itself (e.g. visual selection, highest mean etc.)
Answer: Technically, when you do a visual preselection of where to do the test, you should already correct for that: your eyes and brain already bypass some uncertainties in the data, that you don't account for if you simply do the test at that point.
Imagine that your 'peak' is really a plateau, and you hand pick the 'peak' difference, then run a test on that and it turns out barely significant. If you were to run the test slightly more to the left or to the right, the result could change. In this way, you have to account for the process of preselection: you don't have quite the certainty that you state! You are using the data to do the selection, so you are effectively using the same information twice.
Of course, in practice, it is very hard to account for something like a handpicking process, but that doesn't mean you shouldn't (or at least take/state the resulting confidence intervals / test results with a grain of salt).
Conclusion: you should always correct for multiple comparisons if you do multiple comparisons, regardless of how you selected those comparisons. If they weren't picked before seeing the data, you should correct for that in addition.
Note: an alternative to correcting for manual preselection (e.g. when it is practically impossible) is probably to state your results so that they obviously contain reference to the manual selection. But that is not 'reproducible research', I guess.
Comment: Always doing corrections though, inflates your type II error rate. If you have all significant results before correction, you may lose them all after correction, not accounting for the low odds of getting all significant results.  This may depend on the cost of a type I or type II error in your context.
Comment: Nick gave the answer I would like to have given if I were first to respond.  However in the initial setup you (mkpitas) said that if you actually performed the 15 tests you wouldn't have to do the multiplicity correction.  I don't see why you would say that.  I think in that case the need for multiplicity correction just becomes more obvious.  @etienne your point applies to FWER correction which is very strict in controlling type I error.  If you use FDR you won't sacrifice as much power.
Answer: Long ago, in one of my first statistics classes, I was reading about this in a text (I think it was an old edition of Cohen's book on regreession) where it said "this is a question about which reasonable people can differ".
It is not clear to me that anyone ever needs to correct for multiple comparisons, nor, if they do, over what period or set of comparisons they should correct. Each article? Each regression or ANOVA? Everything they publish on a subject? What about what OTHER people publish?
As you write in your first line, it's philosophical.
Comment: I get infuriated when people say multiplicity testing doesn't matter.  I see this attitude expressed all too often in medical research.  You can point to many papers that reached incorrect conclusions because multiplicity was ignored.  It is critical to not publish papers with wrong conclusions in medicine because it affects how patients are treated and lives are at stake.  Multiplicity contributes to publication bias (because when an issue is studied many times only the studies with significant results get published) which is a serious issue in meta analysis,
Comment: You're right that there's a question about how many comparisons are being done, but I don't think it implies your conclusion.  Reasonable people can differ *because they have different objectives and different valuations (loss functions) for the possible outcomes.*  If you should be correcting for multiple comparisons, this is because it leads to better expected loss.  As such, this is an intensely practical issue, not mere "philosophy," and there are rational ways to resolve it on which reasonable people can agree.
Comment: Yes I agree with Peter's point we have to use common sense to draw the line.
Comment: @whuber you are surely right in some situations. Sometimes there is a sensible loss function, although it is often hard to get one stated explicitly.  But other times, e.g. in exploratory work, I have trouble seeing how any loss function is possible.
Of course, the whole loss function idea gets us away from the grail-like stature of p = .05, and the typical assumption that power = .8 or .9 is good enough, and onto (to my mind) more sensible idea that we establish these on more substantive grounds.
Comment: @MichaelChernick, I agree - it is very problematic when people ignore multiple testing corrections. However, I think Peter brings up a good point - what should be the scope of the multiple testing? All tests done in a single paper? All tests done with a single data set? All tests done since the beginning of time? There doesn't seem to be a clearly correct answer.
Comment: @Peter Flom.  My point about publication bias was just that the unpublished papers on a ptoblem are likely to show insignificant results while published papers show significant results.  We can't adjust for what we don't know. What problem are you saying goes away when effect sizes are looked at rather than p-values?
Comment: @MichaelChernick The publication bias doesn't go away (although it changes, and may lessen) but problems of similar effect size results being published vs. not published go away. As do medical decisions based on sample size rather than effect size.
Comment: Thank you for clarifying the scope and the spirit of your reply, Peter.
Comment: The FDA is acutely aware that if they don't make sure that type I errors are controlled in clinical studies they risk approving an unexceptable number of ineffective or unsafe drugs.  This ahs been paricularly an issue for them when reviewing proposed adaptive designs.  Their first concern is to make sure the design does not allow inflation of the type I error.
Comment: But @MichaelChernick, I have never seen anyone try to apply multiplicity corrections across articles. Further, if we concentrate on effect sizes rather than p values, the problem goes away. Read Ziliak and McCloskey.
Answer: If you are trying to make one-off decisions about reality and want to control the rate at which you falsely reject the null hypothesis, then you will be using null hypothesis significance testing (NHST) and will want to use correction for multiple comparisons. However, as Peter Flom notes in his answer, it's unclear how to define the set of comparisons over which to apply the correction. The easiest choice is the set of comparisons applied to a given data set, and this is the most common approach.
However, science is arguably best conceived as cumulative system where one-off decisions are not necessary and in fact serve only to reduce the efficiency of evidence accumulation (reducing obtained evidence to a single bit of information). Thus, if one follows a properly scientific approach to statistical analysis, eschewing NHST for tools like likelihood ratios (possibly Bayesian approaches too), then the "problem" of multiple comparisons disappears.
Answer: One very important thing to remember is that multiple testing correction assumes independent tests. If the data your analyzing isn't independent, things get a little more complicated than simply correcting for the number of tests performed, you have to account for the correlation between the data being analyzed or your correction will probably be way too conservative and you will have a high type II error rate. I've found cross-validation, permutation tests, or bootstrapping can be effective ways to deal with multiple comparisons if used properly. Others have mentioned using FDR, but this can give incorrect results if there's a lot of non-independence in your data as it assumes p-values are uniform across all tests under the null. The distribution of p-values across tests under the null can be very skewed if a lot of non-independence exists.
Comment: Welcome to the site, Matt. Regarding your opening sentence: *One very important thing to remember is that multiple testing correction assumes independent tests.* Note that this is true for *some* multiple-testing correction procedures, but certainly not all. For example, the *simplest of all* (Bonferroni) makes no independence assumption, and, indeed is quite inefficient if the tests actually are independent! :-) Also, in a continuous-distribution setting, the (marginal) distribution of a single $p$-value will be uniform under the null; you might consider editing to clarify your remarks.
Answer: A possible alternative to correction, depending on you question, is to test for significance of the sum of p-values.  You can then even penalize yourself for test that are not done by adding high p-values.
Extension's (which don't require independence) of Fisher's method (which require independence of test) could be used.
Eg. Kost's method
Comment: These are examples of procedures used in meta-analysis when the individual studies only provide p-values or the data cannot be combined but each study has a p-value calculated.  Also Fisher's combination method and inverse normal are ways to construct stopping rules in adaptive designs.


Null Pointer Exception with a 2d array

Question:
Possible Duplicate:
objects classes and arrays - why is it returning 'null' ? [java]

The other questions with similar titles all have the answer that their data needs to be initialized which I have done but I'm still getting a null pointer exception. Could anyone tell me why?
    public class grid{
private Node [][] board = new Node [9][9];

public boolean add(int x, int y, char label) {
    boolean valid=true;

    System.out.println("enter add");
    if(label==' '){
        System.out.println("enter if 1");
        board[x][y].setValue('0');
    }
    else if(label<='9'&&label>'0'){
        System.out.println("enter if 2");
        board[x][y].setValue(label);
    }
    else{
        valid=false;
    }
    if(valid)
        System.out.println("valid");
    return valid;
}

I'm getting the error on the setValue Lines (10 and 14)
    public class Node{
public char value;
public char []  possibleValues = {1,2,3,4,5,6,7,8,9};
public boolean correct=false;
    }

Edit: I figured it out, if anyone else has the same problem, this seems to fix it.
    if(label==' '){
        System.out.println("enter if 1");
        board[x][y]= new Node(' ');
    }
    else if(label<='9'&&label>'0'){
        System.out.println("enter if 2");
        board[x][y]= new Node(label);
    }

Comment: @smit - It will compile just fine, it just won't do what he thinks. A `char` in java is simply a 16bit signed integer. Using single quotes gets the value for a given character from the default character map. (e.g. '1' == 49 if you're using UTF-8 )
Comment: Your char array should be `public char []  possibleValues = {'1','2','3','4','5','6','7','8','9'};` Your code might not even complie.
Comment: @BrianRoach +1  Yes you are right..
Answer: An array does not initialize the elements of the array. So, each board[x][y] will be initially null.
Comment: Oh, what is this doing then?

private Node [][] board = new Node [9][9];
Comment: @Iweir - Not what you think. See the duplicate of this question I linked to, or the tutorial on arrays http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Comment: Okay, the thing is for this I'll be using directing input so I don't know the values until a file is given. I'm a bit confused on how I would initialize it then.
Comment: Nevermind I figured it out and I'll update the OP

Null Pointer Exception with a 2d array


Let $X$ be a topological space and $A \subset X$ a subset of $X$. Is $ Fr (Int A ) = Fr(A)$?

Question: Let $X$ be a topological space and $A \subset X$ a subset of $X$.
Is $ Fr (Int A ) = Fr(A)$?
I can't find a counterexample or prove that it's true.
Comment: What is "Fr"???
Comment: @Javi Ok, thanks.
Comment: @amsmath  $ Fr A =Cl (A) \cap Cl(X\A) $
Comment: @amsmath It's the boundary.
Comment: @JoséCarlosSantos Thank you.
Comment: @user15269 I don't know where "Fr" comes from, but the common notation of the boundary of a set $A$ is $\partial A$.
Comment: @amsmath in spanish Fr is common as well, probably in french too.
Comment: @Javi But this is an English site, right?
Comment: @amsmath yes, but the OP might not be aware of the usual notation in english or  (s)he might simply think that Fr is used too. I just wanted to explain where Fr comes from.
Answer: In $\Bbb{R}$ with the usual topology, $Fr(\Bbb{Q})=\Bbb{R}$, but $Int\Bbb{Q}=\emptyset$, so $Fr(Int\Bbb{Q})=\emptyset$.


Ivy maven compatibility issue

Question: I'm trying to add a dependency to an Ivy project. The dependency is like this in maven:
<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-spring3</artifactId>
    <version>2.7</version>
</dependency>

I've add this to the ivy.xml file:

but when running the resolve task, it give me an error like this:
        ::::::::::::::::::::::::::::::::::::::::::::::
    ::          UNRESOLVED DEPENDENCIES         ::

    ::::::::::::::::::::::::::::::::::::::::::::::

    :: org.glassfish.hk2#hk2;${hk2.version}: not found

    :: org.glassfish.hk2#spring-bridge;${hk2.version}: not found

    :: javax.ws.rs#javax.ws.rs-api;working@comp: not found

    ::::::::::::::::::::::::::::::::::::::::::::::

Here is the jersey-spring3 pom file. I think the problem is because of the parent tag in the pom file.It is because the hk2.version is defined in the jar's parent pom.
Doesn't Ivy support this feature in pom files?
Any way to solve this problem without adding the transitive dependencies to the main ivy.xml?
Thanks.
Answer: Cannot reproduce your problem. 40 files downloaded without any issue. I have included my ivy example for reference below.
[ivy:resolve] :: resolution report :: resolve 54551ms :: artifacts dl 25244ms
    ---------------------------------------------------------------------
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    ---------------------------------------------------------------------
    |      compile     |   40  |   40  |   40  |   0   ||   40  |   40  |
    |      runtime     |   40  |   40  |   40  |   0   ||   39  |   39  |
    |       test       |   40  |   40  |   40  |   0   ||   39  |   39  |
    ---------------------------------------------------------------------

Example
ivy.xml
<ivy-module version="2.0">
    <info organisation="com.myspotontheweb" module="demo"/>

    <configurations>
        <conf name="compile" description="Required to compile application"/>
        <conf name="runtime" description="Additional run-time dependencies" extends="compile"/>
        <conf name="test"    description="Required for test only" extends="runtime"/>
    </configurations>

    <dependencies>

        <dependency org="org.glassfish.jersey.ext" name="jersey-spring3" rev="2.7" conf="compile->default"/>

    </dependencies>

</ivy-module>

build.xml
<project name="demo" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">

    <property name="build.dir" location="build"/>

    <available classname="org.apache.ivy.Main" property="ivy.installed"/>

    <target name="install-ivy" description="Install ivy" unless="ivy.installed">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/ivy.jar" src="http://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.3.0/ivy-2.3.0.jar"/>
        <fail message="Ivy has been installed. Run the build again"/>
    </target>

    <target name="resolve" depends="install-ivy" description="Use ivy to resolve classpaths">
        <ivy:resolve/>

        <ivy:report todir='${build.dir}/ivy' graph='false' xml='false'/>

        <ivy:cachepath pathid="compile.path" conf="compile"/>
        <ivy:cachepath pathid="test.path"    conf="test"/>
    </target>

    <target name="clean" description="Cleanup build files">
        <delete dir="${build.dir}"/>
    </target>

    <target name="clean-all" depends="clean" description="Additionally purge ivy cache">
        <ivy:cleancache/>
    </target>

</project>

Ivy maven compatibility issue


Questions about why X is correlated with y

Question: Recent questions like Why are the 10 year German bunds and 10 year US treasury yield highly correlated? and Baht drops and Gas Prices too? belong to a certain class of question that asks why does thing one correlated with thing two when I would expect it to be very/slightly different level of correlation.  These questions are usually low-effort to ask and are essentially unanswerable or answers would often be opinion based. I'd like to see if there is consensus against these sorts of questions.
However, somewhat somewhat similar questions are of good quality:  Correlation between salary level and housing prices in a town and Can econometrics test for correlation or causality between prices and corruption?. I'm not sure how to discard the former without junking the latter.
Do you share my dislike of these questions? Can anyone suggest a limiting principle or good distinguishing feature for these correlation questions?
Answer: As you yourself mentioned, in general these type of questions cannot be discarded. I would say that the criterion rests again with the question's effort:
If the question is "Why X is correlated with Y (in country-A), since they shouldn't, at least according to theory-Z (which summarily argues that...)  (AND/OR) empirical evidence from country-B indicates that they are not?" it shows that the OP has devoted some time and thinking on the matter, and also, it brings potentially useful information in the site.
If the question is "Why X is correlated with Y (in country-A)" /question-mark /end of post, then it is the classic 5-year-old phase, where a child asks unstoppably "why this and why that?" -and although the site's policy does accommodate undergraduate questions, I don't think it can be extended to accommodate primary-education-level questions.
Comment: +1 for the last sentence. Hehe
Answer: Any question that asks "Why does X correlate with Y", could be required to answer "Why shouldn't it".
Comment: Yeah... "this is because this isn't not" or "it is because it is" or "I am because I am, so shut up" ;) I thought that economy is meant to (or at least attempt to) provide scientific like answers.

Well I think some of such questions actually *might* matter. A person asking such a question is probably not interested in a literal or superficial explanation, but about deeper undergoing connections between two or more factors - provided that there are such significant correlations, or at least to read an answer stating sth like "there is no significant correlation between both".
Comment: @forsberg My point has essentially the same motivation as Alecos' explains, so read his answer (which came later) for clarification.


Citrix XenApp slowness on ESX 4

Question: I need some help with a some CPU constraint issues( i think) diagnosis.  I have a client with a Citrix Xenapp farm (5 desktop servers/9 Application servers) spread accross 12 ESX hosts running ESX4.0.  All Citrix servers, desktop and application servers have 2 cCPU's allocated and 54% of the VM's running on the ESX hosts are allocated 2 vCPU's.  The problem we are running into is that the Citrix Application servers are running(crawling) when trying to access the published applications.  I personally think it is a multiple VCPU issue but I would like to get an opinion on if my findings are true.
My questions are what are the best practices for Citrix on ESX?
Is it typical to have multiple VCPU's per server in a Citrix environment?
For ESXTOP readings should I be looking at the %RDY and overall performance of the host?
Answer: Take a look at some of the performance papers at Virtual Reality Check.  They've dome alot of benchmarking and testing of various configs for term servers and VDI.  In general the "old" guidance for citrix for 1 cpu per host is no longer true.  Additionally scheduling in 4.0 is much better than in older versions and scheduling is likely not to be the issue.  %rdy is the metric to monitor to verify CPU contention.  My bet would be on poor network performance or poor disk performance before CPU issues.
Answer: The best practice has been debated for a while, some say 1vCPU some say 2+.  IMO, 2 vCPU is pretty good.  The problem with 1 vCPU, is a logon can hog all CPU which affects everyone else on the server.
What OS are your app servers running?  How over commited (if any) is your ESX hosts resources?  Also, is it the virtual desktops accessing the virtual application servers that are having issues? Try accessing the virtual apps from a physical system and see if they're any better?
If you think it's a CPU schedulign problem, meaning you think you've over provisioned the VM and it's waiting for two cores to free up to execute, then watching the %rdy would be what you'd want to monitor.  I think consistently above 500 is when you have an issue.  Don't forget to monitor your disk latency as well.
Finally, what A/V do you have?  We had a lot of performance problems at first and it all came back to mcafee excessivly swaping (some sort of bug).  We switched to MS forefront (we were going down this route anyway) and a lof of those issues went away.

Citrix XenApp slowness on ESX 4


JobControl and JofConf.setMapperClass() error

Question: I am trying to use JobControl to connect multiple Mappers and Reducers together but encounter the following error when invoking JobConf.setMapperClass:
setMapperClass(java.lang.Class<? extends org.apache.hadoop.mapred.Mapper>) in
    org.apache.hadoop.mapred.JobConf cannot be applied to
    (java.lang.Class<capture#530 of ? extends org.apache.hadoop.mapreduce.Mapper>)

It seems that java complains my implementation of Mapper, which is based on mapreduce.Mapper, while JobControl takes mapred.Mapper. (am I right on this part?)
Now my question is: should I keep using mapreduce.Mapper and give up JobControl and find something else to connect my jobs, or change my implementation to mapred.Mapper and keep using JobControl.  Is one of them considered depreciated?
Comment: @Paul Bellora: No, it seems that hadoop has two versions of Mapper.  One is under `mapred`, and the other from `mapreduce`.
Comment: Related: [hadoop.mapred vs hadoop.mapreduce?](http://stackoverflow.com/questions/16269922/hadoop-mapred-vs-hadoop-mapreduce)
Comment: Well I found this class when searching: [`org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl`](http://hadoop.apache.org/docs/current/api/org/apache/hadoop/mapreduce/lib/jobcontrol/JobControl.html) Is that the answer? I don't quite get the `JobConf` connection (no Hadoop experience).
Comment: Is `org.apache.hadoop.mapred.Mapper` a typo?
Comment: I am still working on this problem, but I am wondering which change makes more sense: either using `JobControl` and re-write my Mapper to implement `mapred.Mapper`, or keep using `mapreduce.Mapper` and give up `JobControl`.
Comment: Thank you, Paul! I am now trying to throw away the `JobControl`, which is based on `mapred` library, and finding better way to connect jobs :~~.
Comment: Wow, that might be the answer! I was using `org.apache.hadoop.mapred.jobcontrol.Jobcontrol` and didn't know the one you found!
Comment: Now I have tons of compile errors to fix.  I will later come back and post after I changed to mapreduce.lib.jobcontrol.JobControl.  Thank you !!
Comment: Glad to help! I'll go ahead and put that in an answer.
Answer: As discussed in the comments, the mapred and mapreduce packages are distinct from each other, with mapreduce being the newer, cleaner one. The differences are further discussed on this post: hadoop.mapred vs hadoop.mapreduce?
So for your particular issue, it seems like you want to use org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl instead of org.apache.hadoop.mapred.jobcontrol.JobControl.
See also: Is it better to use the mapred or the mapreduce package to create a Hadoop Job?


How can I create a user object in a custom form and save it?

Question: Basically, I want to create a user object in a custom form and save it in the database.
This is my custom form and its handlers.
function registerme_newform($form, &$form_state) {
  $form['account details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account Details'),
    '#description' => t('Enter Personal Credentials'),
  );

  $form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#default_value' => t('Be sure of your first name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your first name'}",
    'onfocus' => "if (this.value == 'Be sure of your first name') {this.value = ''}",
    ),
  );

  $form['account details']['last name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#default_value' => t('Be sure of your last name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your last name'}",
    'onfocus' => "if (this.value == 'Be sure of your last name') {this.value = ''}",
    ),
  );

  $form['account details']['email'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Mail'),
    '#required' => TRUE,
    '#default_value' => t('Email acts as username.Do not forget it!'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Email acts as username. Do not forget it!'}",
    'onfocus' => "if (this.value == 'Email acts as username. Do not forget it!') {this.value = ''}",
    ),
  );

  $form['account details']['password'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 60,
    '#size' => 60,
    '#required' => TRUE,
    '#description' => t('Password should be at least 6 characters long.'),
  );

  $form['home'] = array(
    '#type' => 'fieldset',
    '#title' => 'Home Address',
    '#description' => t('Enter Personal Residential Credentials'),
  );

  $form['home']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
  );

  $form['home']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
  );

  $form['work'] = array(
    '#type' => 'fieldset',
    '#title' => 'Work Address',
    '#description' => t('Enter Official Address'),
  );

  $form['work']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
  );

  $form['work']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Register Me'),
  );

  return $form;
}

function registerme_newform_validate(&$form, &$form_state) {
  if ($form_state['values']['account details']['first name'] == 'Be sure of your first name') {
    form_set_error('first name',t('Please enter your first name'));
  }
}

function registerme_newform_submit(&$form, &$form_state) {
  dsm($form_state);
}

Is user_save() the correct function to save a user object?
Answer: The code you should use to create a new user account in the form submission handler is similar to the following one.
$account = new stdClass();
$account->is_new = TRUE;

$edit = array(
  'name' => $username,
  'pass' => $form_state['values']['password'],
  'mail' => $form_state['values']['email'],
  'init' => $form_state['values']['email'],
  'status' => 1,
  'access' => REQUEST_TIME,
  'field_fname' => $form_state['values']['first name'],
  'field_lname' => $form_state['values']['last name'],
);

user_save($account, $edit);

The form shown in the question does not request a username. Replace $username in the code with the correct value.
Setting $account->is_new is important, or Drupal will not create a new account.
As side note, a validation handler does not need to check that a required value has been submitted, since that is done from Drupal core.
Instead of using JavaScript code to set the initial value for a field, you should use that value as placeholder: a value that is shown as guideline before users enter a value in the field. That should be done if it does not repeat information already given in the form element description, for example.
$form['account details']['email'] = array(
  '#type' => 'textfield',
  '#title' => t('E-Mail'),
  '#required' => TRUE,
  '#default_value' => "",
  '#description' => t('Email acts as username. Do not forget it!')
  '#attributes' => array(
    'placeholder' => t("Your email"),
  ),
);

Also, the default value for a form element should be either a value previously entered for the same form, from the same user, or an empty value. It should not be a value like t('Email acts as username. Do not forget it!') which then forces you to check if that is the submitted value and return an error from the validation handler. It could also confuse users who can think the form is prefilling the form element for them, while it is giving a description for the form element, which should instead be shown as #description.


Unable to get output from child process

Question: So, I have a simple app (I have written) which writes to stdout.
When I run it by itself, the output is being printed fine.
Now, when I spawn the process with node... nothing happens (apart from a message saying the process has finished)
Here's my code:
var spawn = require('child_process').spawn;
helper = spawn("myApp", []);
helper.stdout.on('data', function(data) {
    console.log("GOT: " + data);
});
helper.stdout.on('end', function(data) {
    console.log("FINISHED: " + data);
});
helper.on('exit', function(code) {
    console.log("CLOSED!");
});

And here's the output:
FINISHED: undefined
CLOSED!

Yep, just that.
What's going on? Am I missing something?
Comment: The "end" event won't give you any content.
Comment: When I change the `spawn()` to `spawn("sh", ["-c", "echo hello world"])` it works fine for me, though I get the "close" event before the data.
Comment: Well, the `end` even *does* fire. The `stdout.on('data',...)` part isn't...
Comment: Are you sure that your application code properly flushes its output buffers? (Not super-likely to be the case, but the child process stuff is pretty darned close to a raw wrapper around the underlying system calls.)
Comment: Hmm... Am I? That's a good question. It's an Objective-C terminal app, `fprintf`ing to `stdout`... Let me double-check.
Comment: @Pointy Wow.... Well, I just made the `myApp` app `fprint` to `stderr` and then attach the event handlers there. And... it worked!!! Thanks a lot for pointing me to the right direction. Just post it as an answer and I'll accept it. Thanks a lot!
Answer: Make sure your stdio output buffers are being flushed in your application:
  fflush(stdout); // or something like that

Output straight to the tty has less buffering than output to a pipe.
Comment: @Dr.Kameleon no problem - fun opportunity to use some stuff I had forgotten I even knew :)
Comment: The trouble is that I had forgotten too. I guess there are times like this when it all comes back up... haha.

Unable to get output from child process


Can my scale have two whole steps of distance?

Question: I want to create scales. I would like to do that to create the most original music as possible.
Now, as a beginner, I don't see why the scales that I studied are composed just by whole steps (W) and half steps (H). I do know the elementary concept of the study of scales: you can build out of them the chords and melodies.
So, my question is: can I build a scale using whole, half and "double" steps (2W)? For instance,

W W H W 2W W H
Comment: There seems to be a large misapprehension used here - that music is derived from scale notes. That's so inaccurate, that the question itself becomes invalid. Not sure why, but there are many questions that appear to use the premise that scales are used to make music. It's more likely the other way round!! Obviously anyone can make up any group of notes to produce a scale, but it's then purely academic, not to make original music. Vtc.
Comment: "original music" hardly depends on the baseline scale you choose.  Maybe start by learning what the 7 modes are.
Answer: If you're going to build your own scales, then you can define any rules you want.
Just know, just because your scale contains a double whole-step, chances are it will still be equivalent to some other scale with one or more notes skipped.
For example, here is a scale I just "invented": C D E F G B C. It contains a "double whole-step" from G to B. However, my scale is equivalent to a C major scale with the A avoided.
Comment: @user1079505 I hereby accept responsibility for all music.
Comment: ...and if someone questions you, blame Aaron! ;)
Comment: @M.N.Raia That is a very deep questions that would need an extensive answer. But one way would be to invent your own, unique tuning system. You might want to explore "microtonality" which concerns the use of systems other than the standard 12 chromatic pitches.
Comment: @Aaron Then, how can I know that I'm not creating equivalent scales?
Comment: Well,  to be fair,  we don't really map pentatonic music to a "classical" 7-pitch scale.
Answer: While Aaron's answer is obviously correct, let's look at more details.
If we built your scale starting from C we would get the following notes:
C-D-E-F-G-B-C#-(D)
So the span of the scale is not an octave, but a natural 9th. So the next repetition of the scale would start on D:
D-E-F#-G-A-C#-D#-(E)
and then another one on E... only after 6 repetitions, or 7 octaves (which basically covers the typical musical notes range). If you want to be original – you've got it. It might actually work musically very well, but probably you need to invent your own harmony rules for that.
Comment: @M.N.Raia Actually, even the assumption that music is made of "chords and melody" is cultural. If you look across the world, at traditional, non-Western musics, and even if you look back in time at Renaissance Western music and earlier, The vast majority of music cultures have used different assumptions. Most music that humans have made across the globe and across time has been monophonic, "melody" only.
Comment: Clever! Seems related to [Super Ultra Hyper Mega Meta Scales](https://music.stackexchange.com/q/89634/70803).
Comment: @M.N.Raia yes, and more importantly how do you match melody with chords. E.g. imagine you play it on a piano, your right hand is in the part starting from D, your left hand is in the part starting from C. Your right hand plays note F#. What notes would you play with your left hand to match it? It's quite open question, that you can answer only with your ears.
But, as Aaron showed, you can build a scale including a 2W distance while still fitting the regular repetition by an octave.
Comment: Beg your pardon, but by harmonic rules you mean reinvent the way we build the chords (say) from the scale?  Because, eventualy, I would like to build chords and melody.
Comment: That is something very interresting in music. Because, as far as I know, things that sound good to me, my ears; vary through culture, folk, time...
Answer: Your scale consists of a major third(what you call a "double step"). While in scales like harmonic and Hungarian minor, minor thirds are passed as an augmented 2nd, major thirds would only exist in a scale because it's the equivalent of another scale, with a degree removed. For example, your scale example is just a Dorian scale with the 5th degree removed. Do whatever you want, just know that you'll simply be avoiding a scale degree.
Comment: thanks. But, what makes a scale unique? If you want, I could push the question into a more heuristic one: "How can I create a scale that have never been created?"
Comment: @M.N.Raia I believe that the 7 modes and other modes that stem from them cover essentially every possible single-octave combination with 7 tones. But you aren't limited by the tuning system. Microtones are often used in contemporary classical music. You could also disregard scales entirely and utilize atonality or polytonality.
Comment: @M.N.Raia On a different note(no pun intended) the originality of your music has little to do with the scales you use. You could copy paste someone else's piece, transpose it in a weird microtone scale, and it's still far from original. Vice versa is true just as well. You can create a completely original(okay, maybe not completely, but that's the curse of only having 12 tones) piece in C major.


Why isn't there a unique double-flat symbol?

Question: Why isn't there a unique, compact, easy to write, double-flat symbol?
The current double-flat is not easy to write as the "x" symbol is for double sharp.
Comment: What reason could there be for having one?
Comment: @Tim the same reason for having a special double sharp symbol.
Comment: You might as well ask why there  **is** a double-sharp symbol.
Comment: Meanwhile, if you want to edit it into "how did we come to settle on this symbol for the double sharp," that might be easier to get more substantial answers. The answer to "why *isn't* it done X way" is often "I dunno, why not," but the answer to "why *is* it done Y way" can be a matter of history.
Comment: That's just life in a world that develops by fits and starts rather than with a "Grand Total Plan."
Comment: Re your edit: Read closer. Two flats "glued together" *is* still a "unique symbol," from a typesetting perspective. Meanwhile, the problem is one of evolution. As many have pointed out, you might just as well ask why a "significantly distinct" symbol evolved for double sharp. I'm not clear on the answer myself, except that there have been many variations on the symbols for flat and sharp throughout history (there's at least one point at which the "double sharp" symbol was just the sharp symbol), and it all gets a bit mixed up as conventions mutate and ossify.
Comment: There's something telling in the dictionary excerpt in Michael Curtis' answer:  "The sign for the double sharp is abbreviated."  Abbreviations are timesavers.  Each "♯" takes 4 independent strokes, so "" saves 6 strokes (8 - 2).  A "♭" can be written without even lifting the pen. Using the ligature "" just makes it more readable.
Comment: Unfortunately I cannot see there being a definitive answer to this questions. These notation conventions have centuries of development behind them and it is unlikely you are going to get an explanation for the decisions.
Answer: There is.  Unicode: , Usually printed similar to this

Image Source
It sure does look like two flats next to each other, but that's not really a problem (in fact it's probably a good thing.  It makes the meaning easy to figure out).
Comment: @CarlWitthoft I wouldn't call it "kerning".  More like "ligature".
Comment: I think the real question is, why does the double sharp not look like two sharps?  My guess is that it looks messy when you try to conjoin two sharps.  But I don't really know
Comment: @RandyZeitman - Isn't that one of the quarter-tone accidentals for half-sharps?
Comment: @RandyZeitman I believe there are other systems for extending the standard accidental signs into the realm of quarter tones, but the sign corresponding to the sharp with three vertical strokes is two flat signs with one of them flipped around the vertical axis (a single flipped flat sign is for a quarter tone flat, and a symbol like a sharp sign but with only one vertical stroke is a quarter tone sharp).
Comment: You mean like this?  Three vertical and two horz. lines?
http://myeasywebaddress.com/Stage/doble.jpg
Comment: That's different than what I had envisioned.  That looks fine, but might be too similar to a regular sharp.
Comment: @Dekkadeci it's more or less the accidental for 1.5 sharps, that is to say, raised by 3 quarter tones, but before now I've only seen that with heavier cross strokes, similar to the common appearance of the sharp sign in modern engraving.
Comment: Wrong: this is simply someone's kerning of a pair of flat-signs.  It's not a different notation.
Comment: @CarlWitthoft, this is correct. See examples in my answer.
Comment: @MichaelCurtis  Sorry - can't tell which way you meant that.  Your answer seems to agree with me, i.e. that there is not a *single* symbol for double-flat .
Comment: @CarlWitthoft, what you wrote read to me like the overlapped flats symbol was a sort of contrivance not actually used in music printing.
Comment: @phoog. I had no idea. Thank you. How is 1.5 flats signified?
Answer: A double flat is two flats together with varying degrees of spacing between the two depending on font...

It seems silly to have to post something so specific, but in response to @CarlWitthoft's comment, the spacing between the two flats signs of a double flat can vary. I've always understood the sign to be two flats "stuck together", slightly overlapped, but obviously whether that can be printed depends on the font available.
An old version of Grove's Dictionary...

I'm surprised the proposed double flat is reference, but I don't have access to Mus. Assoc. Proceedings 1890, p.101.
Apparently Ross' idea caught on, an example of use in Busoni edition of WTC II, prelude in A flat major...
Comment: I was taught the british standard of using the natural sign to indicate a double going to a single. It seems that ABRSM now accepts both.
Answer: I'll go ahead and answer this question in its current state. Many times, looking at musical practices, verbal languages, and many other topics, we ask questions like "Why do we do it this way? Wouldn't this other way be more efficient?" (Or "easier to understand," or "clearer," etc.) Why does the English language let you make a "k" sound with either "c" or "k"? And an "s" sound with either "c" or "s"? Why don't we just pick one letter for each phoneme? Why do we refer to musical pitches with the letters A-G and then modify them with flats and sharps, instead of just using 12 letters? Why does guitar have intervals of a 4th between all its strings, except for a 3rd between two of them?
Invariably, the short answer is "just because that's how it's done." And the longer answers often become insufferably long, dragging out the history of alphabets from Phoenicians to Greeks and of Germanic and Latinate linguistic influences, or brother Guido and his gamut, or the vihuela and re-entrant tunings.
Because all of these are living practices, evolved and amalgamated over centuries, not invented on the spot by one omniscient engineer who can see these glaring inefficiencies from the outset. We do things the way we do them because that's how they're done—and no, it's not just a matter of hidebound traditionalism, resistant to change. (I mean, it might also be that, but it's not only that.) We do things this way because there is an inertia to symbols and to tools. We use the QWERTY keyboard, even though it was invented specifically to slow us down, because so many people have learned on it that it's hard to create a big market for DVORAK. We write and talk about musical notes the way we do because everyone understands us; if we did otherwise we'd also have to disseminate our new systems along with our meanings or risk being ignored. George Bernard Shaw did his best to reform English phonetic spelling, but it didn't catch on, maybe because we're all too used to deriving the concept of a "circle" from the word "circle," and it's an extra cognitive step to decode the unfamiliar signifier sirkel.
And we use two flats for a double flat because it works perfectly well and everyone knows what it means. No one has felt so cramped by it that they bothered to "invent" another symbol; no winds of change have confused it with some other symbol used in some other way (like the troubled histories of time signatures, rests, and mensural notation). It is unaltered because no force with sufficient societal momentum has altered it.
Comment: Love your writing style.  I also request you add an 'in hindsight' section to your profile about looking before leaping.
Comment: Hehe, you mean "maybe check that there's a job market before getting huge loans for a degree you won't use"? Meh, I wouldn't say that no one should get a DMA; I have friends who have landed professorships. My advice would be "If you have to choose between 'doing what you love' and doing something easily marketable and profitable... if you can also get a lot of joy from the $$ option, maybe invest in that as your hobby, and if you ever need to, you can make it your full-time job and keep making music anyway."


Setting a variable as a class (using set classes) in a region template

Question: I am attempting to set a common class if any preface region in my theme appears. I am trying to render this with a variable using set classes = [] in the region template in my theme.
So far I have set a variable in a preprocess region like this:
function gratis_preprocess_region(&$vars) {
  // Check to see if any of the preface regions have content and if so
  // Set a common var for use as a class in the region template.
  if (!empty($vars['page']['preface_first']) || !empty($vars['page']['preface_second']) || !empty($vars['page']['preface_third'])) {
    $vars['preface_region'] = '';
  }
}

Then in my theme's region template I attempt to render the variable within the set classes area.
  set classes = [
    'region',
    'region-' ~ region|clean_class,
    region == preface_region ? 'region-preface'
  ]

I am pretty sure I am not doing this the correct way though and it does not work.
Comment: Sorry I think that I miss something, where is defined `$vars['page']`? By default there is no `$vars['page']` in `preprocess_region`.  If 'preface_first' is a block, maybe you want `$vars['elements']['preface_first']`.
Comment: I already get that kind of class for any of the preface regions but I am trying to set a common class if it's any of the three preface regions.
Answer: It seems the way to do this was to create a theme hook for all preface regions and then it can have its own template. So first I create an alter preprocess function in my theme's .theme file.
function MYTHEME_theme_suggestions_region_alter(&$suggestions, $vars, $hook) {
  // Print the $vars.
  kint($vars);

  // Define a var for the #region.
  $preface = $vars['elements']['#region'];

  // Now check for any of the three preface regions and create a theme hook.
  if ($preface == 'preface_first' || $preface == 'preface_second' || $preface == 'preface_third') {
    $suggestions[] = 'region' .  '__' . 'preface';
  }
}

Next, voila, when I look at Twig debug, I see a suggestion for my new theme hook.
   * region--preface.html.twig >> **** This is the new template from the alter
   * region--preface-second.html.twig
   x region.html.twig

Now I can create a common template for all three preface regions with region--preface.html.twig.
Then in the new template, I print the classes like so:
 {%
set classes = [
'region',
'region-preface',
'region-' ~ region|clean_class
]
%}

This gives me exactly what I set out to do and prints this HTML:

Now I can use .region-preface for common theming / HTML for any of the three the preface regions.


Describing the set $\{n\in \Bbb N\lvert (n>1)\wedge (\forall x,y\in \Bbb N)[(xy=n)\implies (x=1\lor y=1)]\}$

Question: This set appears in an exercise of the course Introduction to Mathematical Thinking, by Dr.Keith Devlin

$A$=$\{n\in \Bbb N\lvert (n>1)\wedge (\forall x,y\in \Bbb N)[(xy=n)\implies (x=1\lor y=1)]\}$

Although this is the very first question of the exercise on a refresher to Set Theory, I cannot process the logical syntax as it is. I'll break down my approach to understanding this set:

The domain of discourse is the set of natural numbers(the convention followed in the course is to exclude $0$ from $\Bbb N$). The set $A$, first and foremost, requires $n$ to be greater than $1$.
Next, $A$ requires $n$ to satisfy the implication $(xy=n)\implies (x=1\lor y=1)$ for every $x, y$ chosen from $\Bbb N$(this is precisely where I feel I might be wrong).
Clearly, in the event of both $x,y$ being greater than 1 the entire implication will be falsified. Thus, there does not exist any $n\in \Bbb N$ satisfying the conditions required by $A$, which means $A$ is an empty set.

I'd like to know which part of my reasoning is incorrect(if any at all). I believe such case-by-case splitting may not be necessary for trivial examples like this one (at least for math students and professionals), but I'm a layman and would hence appreciate such an approach.
Comment: $A$ is the set of *prime* numbers
Comment: If you were to replace $\implies$ with $\iff$ then it would be an empty set. The thing with $\implies$  is that if we have $False\implies P$, it does not matter if $P$ is true or not, the whole implication is true.
Comment: @MauroALLEGRANZA Please extend your comment as an answer.
Comment: @Graviton Understood. However, I would still like to see how that leads to the set $A$ being the set of primes.
Comment: Some simple tests to check the meaning of the specifying condition: a) $n=4$; it is greater than 1 but there ara pairs, like e.g $x=y=2$ such that $2 \times 2 =4$ but neither $x$ nor $y$ is equal to $1$. Thus, $4 \notin A$.
Comment: Now repeat the same exercise with $n=5$. There are only two possible choices of $x$ and $y$ that satisfy the condition $xy=5$. See [Prime number](https://en.wikipedia.org/wiki/Prime_number).
Comment: @MauroALLEGRANZA With some hindsight, I felt it could be the set of primes but the implication and quantifiers perplex me. I've understood your point now, thankyou!
Answer: Let's break it down step by step.

You're first point is right, for $n \in A$, $n$ must be an natural number greater than $1$.

$n$ must also satify $(xy=n)\implies(x=1\vee y=1)$ for all natural numbers $x$ and $y$, which can be $1$.

Now let's look at the general cases for the form of $A\implies B$

If $A$ is false, then $(A\implies B)$ is true. If $A$ is true, then $(A\implies B)$ is true if an only if $B$ is also true.
So now we know that if
$(xy=n)$ is false for all natural numbers of $x,y$, then $n\in A$. However, it's very easy to see that it's not always false, because if $x=1$ and $y=n$ (which is a perfectly valid possibility!), then $(xy=n)$ is clearly true.
What that means is that for the cases where $(xy=n)$ is true, we must also have that $(x=1\vee y=1)$ to be true. That is the part that restricts $n$ to be a prime number.
I.e; if $n$ is a multiple of two natural numbers $x,y$, it's only prime when for all $x,y$, either $x$ or $y$ is $1$.
Answer: Your third point is false. An implication is not necessarily falsified when the conclusion is false.
For instance, (False) $\implies$ (False) is always true.
It might be appropriate to recall the definition : $A \implies B$ holds if, whenever $A$ holds, $B$ holds as well. If $A$ is false, then the implication $A \implies B$ is true, by definition.


Adding a table to a particular Div in the codebehind?

Question: Just for testing, I made a page with nothing but the form and div tags and, in the codebehind, I created a table, added rows to it, then used the following code to add the table to the page:
Page.Controls.Add(dtStatuses);

What I'd like to do now, though, is add this table to a particular div.  For instance, if I have a div tag with an ID of "testDiv", how can I add the above table (dtStatuses) to that div, with just code in the codebehind?
Answer: Just set runat="server" to the div

and add the control like this
testDiv.Controls.Add(dtStatuses);


Variation on Bellman-Ford Algorithms?

Question: We have a Directed Graph with 100 vertexes. v1 --> v2 --> ... v100 and all edges weights is equal to 1. we want to used bellman-ford for finding all shortest paths from v1 to other vertexes. this algorithm in each step check all edges in arbitrary order. if in each step the shortest distance v1 to all others vertexes is not changed, this algorithm halt. the number of steps is related to checking order of edges. what is the minimum and maximum of steps in this problem?
Solution: 2 and 100.
How this solution will be achieved?
Comment: Cross-posted on CS.SE: http://cs.stackexchange.com/q/53389/755. Please [do not post the same question on multiple sites](http://meta.stackexchange.com/q/64068). Each community should have an honest shot at answering without anybody's time being wasted. If you don't get a satisfying answer after a week or so, feel free to flag for migration.
Answer: The solution is 2 if the edges are like
v1->v2
v1->v3
...

In this case the first iteration will find the distance from source to each edge and second iteration won't change any weight and thus algorithm stops
The solution is 100, if
v1->v2->v3->...->v100

.i.e. all are in a straight line, than we need 99 iterations to update the distance to 100th vertex and the last iteration won't change the distance.
Comment: For solution in 2 case, you can prove that in 2nd iteration no distance will change, so algorithm stops. For 100th you can say that it will require at least 99 iteration to update 100th vertex from inf to correct distance and last iteration doesn't change any distance so algorithm stops. I don't know if there can be any more mathematical approach.
Comment: @coderhacker you answer is wrong ! how you say "v1->v2->v3->...->v100" need 100 steps? it just need 2 step, because each edges weights is 1.

Variation on Bellman-Ford Algorithms?


Given is relation $R$. Create a digraph for equivalence relation

Question:
Given is relation $R =
\left\{(1,1),(1,5),(2,4),(3,3),(4,1),(4,2),(5,4)\right\}$
What's its equivalence relation $h_{\text{equiv}}(R)$? Draw a digraph
  for $h_{\text{equiv}}(R)$.

I check in internet a relation is equivalence relation if it have properties: reflexive, symmetric, transitive.
This means I need change relation $R$ so it have these $3$ properties, right?
Is allowed when I only take $\left\{(1,1)\right\}?$
Because this is reflexive because we only have $1$ and it's relation with $1$, it's symmetric too and also transitive because transitivity need two condition satisfied and this we have only one pair so we don't need second condition of transitivity satisfied. So also transitive relation.
We have $h_{\text{equiv}}(R) = \left\{(1,1)\right\}$
Digraph:
Comment: No, you are required to add as few as possible pairs to R to make it zn equivalence relation.
Answer: Given your description of
$$R = \{ (1,1), (1,5), (2,4), (3,3), (4,1), (5,4) \},$$
I suppose this is a relation on the set
$$\{ 1, 2, 3, 4, 5 \}.$$
If $h_{equiv}(R)$ is the equivalence relation generated by $R$, then you can obtain this relation by following the procedure:

It must be reflexive, so you must add it the pairs $(2,2), (4,4), (5,5)$.
It must be symmetric, so from the existence of pairs $(1,5), (2,4), (4,1), (5,4)$, you also need $(5,1), (4,2), (1,4), (4,5)$.
It must be transitive, so given that $(1,4), (4,2) \in h_{equiv}(R)$ it follows that $(1,2) \in h_{equiv}(R)$ (and also $(2,1)$); from $(5,4), (4,2) \in h_{equiv}(R)$ it follows that $(5,2) \in h_{equiv}(R)$ (and $(2,5)$ too).

So
\begin{align}
h_{equiv}(R) &= \{ (1,1), (1,2), (1,4), (1,5), (2,1), (2,2), (2,4), (2,5), \\
&(3,3), (4,1), (4,2), (4,4), (4,5), (5,1), (5,2), (5,4), (5,5) \}
\end{align}
Its graph is the complete graph on the set $\{1,2,4,5\}$ union with the single element $\{3\}$


Finding a unit tangent vector as a function of t.

Question: If I have the curve $$r(t)=\left\langle \cos t+t\sin t, \sin t-t\cos t,1 \right\rangle$$
How would I find the unit tangent vector as a function of t? Here is a result that I ended up with after taking the derivative of the vector function and finding magnitude.
$$T(t)={{\left\langle -\sin t+t\cos t+\sin t, \cos t+t\sin t+\cos t,0 \right\rangle}\over{\sqrt{(-\sin t+t\cos t+\sin t)^2+(\cos t+t\sin t+\cos t)^2}}}$$
Would that be the correct answer? Is there any way to make it look nicer? As in, simplify it a bit more. I can't see any identities that would work.
Thanks for any help!
Answer: For a start, $-\sin t +t\cos t+\sin t=t\cos t$, which helps. Also
$\cos t+t\sin t-\cos t=t\sin t$. Using these, your final expression
simplifies a lot.
Answer: That would be a correct solution, yes. Generally with these problems the magnitude of the initial vector tends to look very ugly, but can simplify down to something far more workable. In this case, there's a very simple way to reduce the denominator: the first polynomial contains $-\sin{t}$ and $\sin{t}$, and the second contains $-\cos{t}$ and $\cos{t}$. This leaves you with $\sqrt{(t\cos{t})^2+(t\sin{t})^2}$ as the denominator. From there, distribute the powers. You should be able to work out the rest from there.
Answer: The tangent vector simplifies as others mentioned .. I am not repeating the same.
The tangent to the curve and  originating base circle radius ( of the involute curve that these parametrizations describe) are parallel, where the taut string of length $L = a t $ is the common normal. The situation should be grasped comprehensively.
Angular parameter $t$ of circle radius rotation links the generating relation
$$ r^2 = a^2 + L^2 = a^2(1+t^2) $$
The radius of curvature of the involute is simply $a t$.
Involute Relations


AngularJS - How to access directly a $scope's row/value from the controller

Question: I'm newbie in AngularJS but am very eager to master it, so please forget my ignorance. I have two problems making a basic blog:
Problem #1: I have a controller that uses $http and receives a JSON perfectly.
This is the app.js:
angular.module('blogApp', []).config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/home', {
    templateUrl : 'home.html'
}).when('/post/:postId', {
    templateUrl : 'post.html',
    controller : postCtrl
}).otherwise({
    redirectTo : '/home'
});
}]);

This is the controller.js:
function postCtrl($scope, $http, $routeParams) {
$http.get('post.php?id=' + $routeParams.postId).success(function(data) {
    $scope.post = data;
});

$scope.description = $scope.post.meta_description;  /*I can't access this value*/

}
And this is the JSON that $scope.post receives when #/post/123 is used:
[
    {
        'id':'123',
        'title':'title of the post',
        'date':'2013-06-14',
        'content':'This is the content of the post.
She had a yellow house.',
        'meta_description':'description of my first post.'
    }
]

The problem is that in the controller.js, I can't access $scope.post.meta_description. Also I have tried with $scope.post[0].meta_description, with data.post.meta_description and with data.post[0].meta_description without a positive result.

Problem #2: In post.html, I have this code

{{post[0].title}}

Published on {{post[0].date}}

    {{post[0].content}}

I practiced the full AngularJS' tutorial, and should be using {{post.title}} but AngularJS doesn't print anything. To solve it, I use {{post[0].title}}. Why happens this?
Answer: So you would need to do something like
ng-repeat post in posts for your problem 2.
For problem 1, I think you need to make the actual http call.
$scope.post = // your function call to get the data.
Comment: for problem #2: exactly, in that way, it works but I don't understand why in http://docs.angularjs.org/tutorial/step_08, they load a JSON with one record, and access to a field using phone.additionalFeatures without using ng-repeat.

Why didn't they use phone[0].additionalFeatures?
Comment: phone.additionalFeatures is a jsonObject ( not a jsonArray) , while in your case you have an Array. An Array can be looped through using ng-repeat
Comment: Ok, now I understand the difference between JSONObject and JSONArray. The problem #2 is solved. Thank you.
Comment: But still I don't understand how to get data.meta_description from outside of the $http.get function.
Comment: Ok, I think you're talking about using $resource, like in http://docs.angularjs.org/tutorial/step_11
Comment: Ready, I found a better way. Thank you.
Answer: First one
$scope.description = $scope.post[0].meta_description;

Please, pay attention to fact that server returns Array with single item which type is Hash.
I guess it's clue to your trouble.
Answer: Conclusions:
For problem #2. There a two types of JSON.
a)JSONObject like this single row:
{
    'id':'123',
    'title':'my house'
}

b)JSONArray like this single row:
[
    {
       'id':'123',
        'title':'my house'
    }
]

Do you see the brackets? Or like this other JSONArray:
[
    {
       'id':'123',
        'title':'my house'
    },
    {
       'id':'124',
       'title':'my car'
    }
]

With JSONObjects, you must use {{post.title}} in the template.

    {{post.title}}

{{post[0].title}} shall give you an error because data isn't an array. It doesn't use brackets.
And with JSONArrays (with one or more rows), you can use ng-repeat in the template, like:

    {{post.title}}

Or, also you can access directly a specific row:

    {{post[0].title}}

    {{post[1].title}}

For problem #1, you could use something like explained here:
Step #11 in AngularJS' tutorial ($resource)
But, I found easier to do a single change; this is my previous code:
function postCtrl($scope, $http, $routeParams) {
    $http.get('post.php?id=' + $routeParams.postId).success(function(data) {
        $scope.post = data;
    });

    $scope.description = $scope.post.meta_description;  /*I can't access this value*/
}

The problem is $scope.post only exists inside the function inside $http.get; it's like a private variable that can't be access from outside of the function.
So an easier solution than to use $resource, was to move $scope.description inside $http.get.
function postCtrl($scope, $http, $routeParams) {
    $http.get('post.php?id=' + $routeParams.postId).success(function(data) {
        $scope.post = data;
        $scope.description = data.meta_description;
    });
}


What are these slanted surfaces on the bridge saddles of my electric guitar?

Question: I randomly took a closer look at the bridge of my electric guitar and noticed that the brass saddles have some weird, flat, slanted surfaces where the strings run over them.
Interestingly, these surfaces are facing in the opposite direction, so not every string runs over them in the same way - some lie flat on the surface, others run right across the sharp edge. Also, the middle saddle is a completely different part (meaning you can't rotate it to look like the other two). Nothing of this seems random, and I suppose it must have a clear purpose of some kind. Anybody knows what it could be?
Comment: I don't know if someone will find this is a duplicate question, but you might add whether the saddles are actual brass and if that matters in some way.
Comment: @MichaelCurtis Product description says brass, so I guess that's what they'll be. Also, duplicate of what, if I may ask?
Comment: your question may be a duplicate of an existing question. I don't know if it is. Many times people spot dups when they themselves have answered the question before.
Comment: It has to be a dup, might be interesting to look at compensated bridges
Answer: Since the saddles are in three pairs like an old Telecaster bridge it looks like the different angles are there so the lower string will automatically have a longer string length. However, like you said, the middle pair is backwards, the D string is shorter than the G. This is intentional. As @ojs said in comments if you use a wound D and an unwound G this would probably work but if you use heavier strings with a wound G this will give you problems so try to stick with unwound G strings. You probably will have to compromise when intonating each pair. Individual saddles are much better for accurate intonation.
This bridge looks like it was designed to improve intonation of the old Tele bridge while still maintaining the three double saddles the original has. The fact that one string goes over the curved part and the other goes over the straight part has no real bearing, the important thing is the location of the high point where the string crosses.
Comment: The middle one has different orientation than others, because the wound D string needs less compensation than unwound G. With wound G, the orientation would be same as the other two.
Comment: @ojs Noted. I checked my guitars with unwound G's. The D's and G's are either the same length or the G's are slightly longer. I corrected my answer.
Comment: Thanks, great answer, short and to the point and covers every aspect.
Comment: @Tim The G saddle is longer than the B on both of my electrics and in general in my experience. The G saddle can be placed closer than the B if necessary in this case but that would also affect the D string.
Comment: @MaxD my pleasure. It looks to be a well made bridge and the through body stringing is a nice option. I'm sure with a little patience and effort you can get it intonated pretty well.
Comment: I  agree with the answer, but generally speaking, the B string is longer than the E and the G, which means this guitar is out of intonation, no matter what strings are on it. I filed the saddles on my Tele to enable intonation to work, similar to this bridge - a vast improvement.
Comment: What I meant was that the 2nd string is most often longer (open) than the 1st and 3rd. Hence 'compensating bridges' on fixed bridge guitars. Just checked several of my electrics, and that's the case with them all. On my Tele, I have a similar bridge to the OP's, and had to file the 2nd string saddle to get good intonation between 1st and 2nd, otherwise they'd both be the same open length, and one would always be out.
Comment: @Tim are you by any chance using wound G strings? Do you know the difference between wound and plain string?
Comment: @ojs - I've only played and taught guitar for 60yrs! So I do know the difference. And wound 3rds will need to be longer than plain 3rds, BUT it will also depend on the gauge of them. My go to is generally .012" 3rds, and I don't have wounds on any of my guitars - electric or acoustic.
Comment: @Tim I know. 60 years ago wound 3rds were more popular than now, so I was curious if you use those. In general plain strings need more compensation, i.e. to be longer than wound strings so your guitars are probably set up in some unusual way.