DL180 G6 server suddenly loses access to SSD datastore on ESXi 6.0

Question: I've currently got a HP ProLiant DL180 G6 server. It originally came with a Smart Array P410i raid card, which I used to create a bunch of RAID0 disks (one SSD for my ESXi datastore and a couple of HDDs for my FreeNAS virtual machine). All the disks were connected to the raid card through the server's backplane, and everything seemed to work perfectly back then.
Some months later, as I read that it is common knowledge that you shouldn't run FreeNAS with a raid card, I decided to buy a HPE H220 Host Bus Adapter which I would configure to work in IT mode. Then, I connected the HDDs which would be pass through to the FreeNAS VM to the HBA (through the backplane) and the SSD to one of the SATA ports on the server's mainboard.
In order to provide power to the SSD, I use a SATA power to 4 pin floppy adapter to connect my SSD to the only spare cable that comes out of the power supply (which bears the word "CD"), as you can see in the following pictures:
Picture 1
Picture 2
However, although the SSD seems to work, when put under heavy load, it suddenly disconnects and my ESXi instance reports errors such as "Lost access to volume" and "All paths down". As a consequence, all my VMs crash as they are located on the datastore hosted on the SSD, and I need to reboot the whole machine.
I supect that the issue is caused by the SSD not receiving enough power from the CD cable that comes out of the PSU. If that is so, then how can I correctly provide power to my SSD?
Answer: This is all a bad idea ;)
You're better off going back to the original configuration or changing the SSD setup.
For the SSD, please either use a real drive bay connected to the backplane or use a PCIe or NVMe connection.
Edit:
You can mount your existing SSD to a PCIe adapter.
Comment: Could you please explain why it is a bad idea? Anyway, I can neither go back to the original configuration, because using a raid card is **highly** discouraged with FreeNAS, nor attach the SSD to the backplace, because I have to passthrough the HBA to the FreeNAS VM and I would still need a drive for my ESXi datastore. Considering this scenario, would ditching the current SSD and buying a new PCIe/NVMe drive the only solution then?
Comment: Would you mind recommending me an adapter for my Samsung 860 Pro SSD?


Help with regression and GPA

Question: I'm currently analyzing some data to establish if school performance for particular subjects makes for good predictors of university performance at first year level across all faculties and degrees. In essence we want to know which specific school subjects are the best predictors of university performance so those can be used for admission purposes alongside admission tests. This has obviously been done a million times before.
The problem is that, due to recent curriculum overhauls, I only have access to one cohort's data for now. For various reason, some discussed below, regression the way I was taught might not be the way to go.
My first instinct was to do some hierarchical regression for each Faculty by entering the compulsory school subjects needed for admission (for example, math and science for engineering) first and then entering some other subjects of interest second (history and economics for engineering). The outcome variable would be 1st year GPA. This is probably a bad idea though for a number of reasons.
1) GPA, as a construct, will vary from degree to degree within faculties. For example, it would be very misleading to equate the GPA for a Human Resource Management degree and an Actuarial Science degree with one another, though they are both in the same faculty.
Theoretically this is a problem but practically as well. For example, despite very similar mean 1st year GPA scores, the mean school math and science mark for Actuarial Science is about 25% higher than the HR Management means. Regression won't like this very much. As far as I can see there's no real way to quantify how much more difficult certain clusters of university subjects are than other clusters making GPA sort of useless as an outcome variable at faculty level.
2) Ideally I'd like to do this at the level of individual degrees where there is some stability in terms of degree difficulty, but if I do this I end up chopping the student numbers severely. With all said and done I have around 5 degrees out of about a 100 yielding sufficient student numbers to run regression. I played around with some power calculations and with 5 or 6 predictors I'll need somewhere in the vicinity of 100+ students. However, due to the selectivity of some of these degrees, school marks tend to cluster at the higher end with very little variance between students and makes for less than ideal predictors. University GPA scores tend to be more dispersed though.
I'm hesitant to run regression on degrees with 80 students or less for example, especially given the real risk of collinearity issues with regards to school subjects. There is a pretty  robust correlation between math and science marks in the data for instance and all degrees that require one also require the other for admission.
Any ideas? Help would be greatly appreciated as I'd hate to construct 100's of regressions with only a small number being usable.
Comment: Now that you solved your own problem, can you answer in the **anser box** so that it not lingers on as unresolved?
Answer: For anyone interested, I found a way around this. I decomposed each degree by clustering the specific subjects they have to take and used those subjects as outcome variables. So instead of taking a general GPA as outcome variable, I ran Hierarchical Regression on specific subjects

Help with regression and GPA


How to allocate memory of a struct?

Question: I am trying to allocate memory and zero it out for the sender struct but I'm not sure if I am doing this correctly. I'm trying to learn how to manage memory in C while I am doing this project. How can I test it to see what I set the memory to?  And will what I am trying to do work, or is there a better way of doing this?
typedef unsigned char uchar;

typedef struct {
    uchar Seq;
    uchar Ack;
    uchar Flags;
} Header;

#define FRAME_PAYLOAD_SIZE 50
struct Frame_t
{
    Header header;
    char data[FRAME_PAYLOAD_SIZE];
    uchar CRC;
};
typedef struct Frame_t Frame;

struct Sender
{
    uchar winSize;

    struct sendSlot {
        struct timeval timeout;
        Frame msg;
    } sendQ[5];
};

    initSend(Sender* sender) {
        sender->winSize = -1;

        char* send_buf = (char*) malloc(5 * sizeof(sender->sendQ[0]));
        memset(send_buf, 0, 5 * sizeof(sender->sendQ[0]));
        int i;
        for (i=0; i<sizeof(sender->sendQ)/sizeof(sender->sendQ[0]); i++) {
             memset(sender->sendQ[i].timeout, 0, sizeof(struct timeval));
            sender->sendQ = NULL;
         }
    }

Comment: Just use [`calloc`](http://linux.die.net/man/3/calloc) instead of `malloc`, and you'll start with zeroed-out memory. Problem solved!
Comment: Are you trying to define a function inside `main()`? If so, stop right there.
Comment: Don't cast `malloc`.
Comment: @EOF no, main is not important here, initSend() could be within any other file.
Comment: @Urler: Well, your code is not c. Why did you tag this as c if you want to define a function inside of a function?
Comment: @EOF sorry I was using ideone.com so I will edit the post. Thanks.
Comment: `typedef uchar unsigned char` is not a valid `typedef` for what you likely want to achieve, and it's missing the semicolon. Please post real code.
Comment: @melpomene - If you offer advice like this, you should be clear. In C, you should not cast *the result of `malloc`*—or any other `void*` value—when assigning to another pointer type, because the compiler does the conversion for you.
Comment: @unwind fixed, thanks.
Comment: As pointed out, `calloc` will give you zeroed memory. But just for your learning, if you `memset` a structure then that sets all fields within the struct including nested structs. So in your case you don't need to `memset` the `timeout` field again.
Comment: Maybe you want to say :  typedef struct Frame Frame_t;  instead of : typedef struct Frame_t Frame;
Comment: @BobRun fixed, thanks
Answer: sendQ is an array member of Sender, it is not a pointer.
There is no need for allocating memory using malloc. You can use:
initSend(Sender* sender) {
   sender->winSize = -1;
   memset(sender->sendQ, 0, sizeof(sender->sendQ));
}

Comment: Why not just `void initSend(Sender *sender){Sender s = {.winSize = -1}; *sender = s; return;}`?

How to allocate memory of a struct?


Are affine linear subspaces linear subspaces?

Question: Basically the question is in the title but, I've been told to think of affine subspaces are spaces parallel to each other.
So, say we're talking about: $$F_2^2.$$
Wouldn't that mean that only one contains $(0,0)$, because if any other subspace contained $(0,0)$, they wouldn't be parallel?
And I thought a subspace needed to contain $(0,0)$ (if we define addition of $(a, b) + (c d) = (ac, bd)$), so wouldn't that mean that only one affine subspace is a linear subspace? Thanks!
Comment: In general, affine subspaces are not linear subspaces. They only are linear subspaces when they contain $0$, just as you observed.
Comment: Since an "affine subspace" is not a subspace, some people might prefer the term "affine manifold" or simply "affine set".
Answer: No, not in general. In the usual plane, the line $L$ through $(-1,0)$ and $(0,1)$ is an affine subspace within the real vector space $\mathbb{R}^2$. A (proper) linear subspace needs to contain the origin.
Note $L$ is parallel to $W$, the span of $(1,1)$. There are many affine subspaces parallel to $W$. Actually all of these can be written $(0,t) + W$ as $t$ runs through all reals.
Only one contains the origin: the one such that $t=0$.
In this example, only when $t=0$ is $(0,t) + W$ a (proper) linear subspace.
A linear subspace is a special affine subspace.
Nevertheless, you should be prepared for authors to simply say "subspace". Whether the general affine sense is meant, or if the narrower (linear algebra) sense is meant you might need to judge from the context or the introductory remarks.


php week interval from date ("W")

Question: Hy, I have in database number of the week date ("W") and I want to display week interval like 28 Jan -> 3 Feb in this format, and I don't know if it's possible. Can you help?
Thanks!
Comment: Yes, it is possible. What have you tried so far?
Comment: not much, I was thinking how to introduce direct current week interval instead of week number
Answer: Try this
$year = 2013;
$week_no = 6;

$week_start = new DateTime();
$week_start->setISODate($year,$week_no);
$week_end = clone $week_start;
$week_end = $week_end->add(new DateInterval("P1W"));

echo $week_start->format('d-M-Y') . " - ".$week_end->format('d-M-Y');

Comment: DateTime->__construct()\n#1 {main}\n  thrown in /var/www/html/week.php on line 5
Comment: PHP Fatal error:  Uncaught exception 'Exception' with message 'DateTime::__construct()
Comment: sorry, wrote it down without testing it. now it works (php 5.3+)
Comment: PHP Fatal error:  Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function.
Comment: date_default_timezone_set('Europe/XXXXXX');
no it works, thank you for your help
Comment: @Cipi; As a portal rule, "if an answer helped you so worked for you, so you need to accept it pushing accept button"..
Comment: @Cipi; No, you said "it works" at prev comment (http://stackoverflow.com/questions/14608747/php-week-interval-from-date-w/14609023#comment20401320_14609023).
Comment: I really do not see one, I may have eye problems :)
Answer: Transform your intervals into timestamps.
If its not the first day of the week get the first day of that week with strtotime "last sunday" (or monday) for the first date.
Do the same for the second date this time geting the last day of the week with "next saturday" (or sunday);
Get both dates W and make a mysql comparison between the weeks.

php week interval from date ("W")


Encoding Data in JSON

Question: My new code with the updated changes. Clicking the button after inserting a number has no effect on the form.
Front-End
 $(document).ready(function(){
$("#go").click(function() {
    var id=$("#myid").val();
    $.getJSON('find.php',{num:id},function(obj){
       alert(obj.toSource());
       $("input.fname").val(obj.FirstName);
       $("input.sname").val(obj.Surname);
       $("input.age").val(obj.Age);

     });
 });
});

Form
 ID: <input type="text" name="id" class="myid">
 <input type="button" value="Go" id="go" />

 First Name: <input type="text" name="FirstName" class="fname">

 Surname: <input type="text" name="Surname" class="sname">

 Age: <input type="text" name="Age" class="age">

Back-End
 $id = $_GET['num'];

 $result = array('FirstName' => 1, 'Surname' => 2, 'Age' => 3);

 echo json_encode($result);

Comment: Hi, I want the code to take the data found in the selected record and use it to populate the elements in the form i.e. elements named 'fname'/'sname'/'age'. Currently there is no response when an id is entered and no reason in the browsers developer tools.
Comment: @Matt The output from that is the array I specified in the back end php file --> {"FirstName":1,"Surname":2,"Age":3}
Comment: @Matt: It's find.php, held in the same directory as the html file. The developer tools don't give me anything on either the front page, or the php back page. I tried your alert and got this message -> Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'alert'. Perhaps I used it wrongly? I'm unfamiliar with 'alert'. Any Ideas?
Comment: @Kamal: Here's an example of one of my form fields -> First Name:
Comment: @Matt: When I just run find.php through the browser, (i.e. without num=whatever) I get an undefined index error -> Notice: Undefined index: num in *:\****\*********\*********\website\find.php on line 10 {"FirstName":1,"Surname":2,"Age":3}
Comment: @William231: [`alert()` is a function](https://developer.mozilla.org/en/Code_snippets/Alerts_and_Notifications#Basic_modal_alert). It looks like you were calling `$.alert(...)`; all you need to have in your console is `alert($('input.fsname,input.sname,input.age').length)`. Also check the JavaScript to launch the JSON request is actually being executed (stick an alert() in before).
Comment: Thanks for your patience. The alert outputs [object Object]. However the other alert(with fname etc) doesnt seem to produce anything?
Comment: @William231: your updated code should work fine. Try navigating to `find.php?num=whatever` yourself and seeing what output the server provides.
Comment: @William231: Can you check you're getting the same response in your developer tools in the browser you're using? (are you sure it's `find.php` and not `/find.php`?). Check the elements exist on your page with the name you expect; try `alert($('input.fsname,input.sname,input.age').length)` to make sure that gives you 3. Check the JavaScript to launch the JSON request is actually being executed (stick an `alert()` in before).
Comment: Make sure that you have included class name in your html cause your selectors are ("input.fname") that means you have to provide html like this . I have checked above updated code and its working perfectly filling up my form.
Comment: You have not even explained whether there is a problem. What is your current code doing and what do you want it to do?
Answer: I think it's here
$id = $_GET['num'];

instead of
$id = $_GET['id'];

because your querystring should be something like
find.php?num=3

end then looking better at your code the error should be
   jQuery("input.fname").val(obj.FirstName);
   jQuery("input.sname").val(obj.Surname);
   jQuery("input.age").val(obj.Age);

without obj.length as stated correctly in anothe ranswer
Answer: obj.length will be undefined and you're calling the response object obj not data. What you'll get back from PHP is this;
{
    "FirstName": 1,
    "Surname": 2,
    "Age": 3
}

To cater for this, update your JS to:
// if (obj.length>0){   remove this
   jQuery("input.fname").val(obj.FirstName);
   jQuery("input.sname").val(obj.Surname);
   jQuery("input.age").val(obj.Age);
// }  and this...

Note the case-sensitivity of JavaScript.
Additionally, as pointed out by Nicola Peluchetti, you should be checking for $_GET['num'] rather than $_GET['id'].
You should also have more protection against SQL injection attacks. Escape your input with mysql_real_escape_string at least:
$query = "SELECT * FROM Customers WHERE ID = '" . mysql_real_escape_string($id) . '"';

Answer: Replace {num:id} with {id:id}
Answer: Checkout below code with your code.

<input type="hidden" name="myid" id="myid" value="2" />
<input type="button" value="Go" id="go" />
<input type="text" class="fname" />
<input type="text" class="sname" />
<input type="text" class="age" />

json_action.php
$result = array('FirstName' => 1, 'Surname' => 2, 'Age' => 3);

echo json_encode($result);

Above is almost same as your code and i can fill up value by clicking go button. And you are getting this error ' an undefined index error -> Notice: Undefined index: num in :***********\website\find.php on line 10 ' cause your are not passing id in your query. By the way i cant see any use of query so i have eliminated in my json_action.php file. Hope this will help you.
Comment: I will edit my question with the new code, still not working unfortunately
Comment: also included alert for your reference.

Encoding Data in JSON


Make JWindow of swing to appear full screen and components inside it also should adjust accordingly

Question: I have a panel which comes on top of another panel which is made using JWindow. I want to set this top panel go fullscreen when a button is clicked. I searched in for long time but couldn't find a solution.
Comment: *"..and components inside it also should adjust accordingly"* [Layout managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html).
Answer: This solution takes the current screen dimensions and sets the frame size to it. The setSize() call also exists for JWindow.
<code>frame = new JFrame("Test");
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
frame.setSize(xSize,ySize);
</code>
source: http://www.coderanch.com/t/341780/GUI/java/set-Jframe-full-screen
Comment: I don't understand why this answer is downvoted. It works.


Display subscribe to group on access denied page

Question: I am using Drupal 7.25 (I need to update to 7.26) and organic groups 7.x-2.4.  I currently have public and private groups working.  I have two users (admin and a normal user).  I have a menu tab that opens the og list (/og-list) view which lists all groups (public and private).
When logged in as a normal user if I click on a public group it shows a subscribe to group link.  That's great.  However, if I click on a private group it gives me the Access denied page without a subscribe link.
I would like to have any normal user be able to click a private group and have it display a link to subscribe.  Any help would be greatly appreciated!
Answer: You have a couple of options.
Not sure how you have your group node page setup but what I have done is use a node view panel.  In that panel I added the Field: Group (group_group) in a region then set the formatter to "OG subscribe link".  That will display the "Subscribe to group" link when a user clicks on the group they are not a member of.  Since you are getting access denied I'm guessing your group node page is not setup that way.
Another option is to modify the og-list view and add the field "Content: Group".  Then change its Formatter to "OG subscribe link".  That will create a new column in the view that will display a link called "Subscribe to group" for groups you are not a member of and "Unsubscribe to group" for groups you are a member of.
Comment: I have the Field: Group(group_group) in my panel and the "subscribe to group" link shows up when a normal user views a public group.  However it is still missing when they click on a private group.  I also tried option 2 with the same outcome.

The outcome still shows the Access denied page and a Navigation panel
Comment: On a second note.  On my show all groups page I have two fields.  Content: Title and Field:Group(Subscribe).

This shows the group (public and private) as well as the ability to subscribe to it.


Comparing skin temperature to environment

Question: I have recorded animal skin temperatures (animals kept in fairly constant conditions) over a time period, and also the ambient humidity and temperature at the same time. What test(s) would I use to see if  ambient temp. and humidity may have affected the animals skin temp, and why?
And yes, Im very new to statistics :-(
Many thanks :-)
Answer: Linear regression is good for you. The animal skin temperatures will be response variable (dependent variable)and ambient humidity and temperature will be covariates (independent variables).
If you get the animal skin temperatures, the ambient humidity and temperature more than one time from the same animal (repeated measurement), you need to consider the correlation between measures. Maybe you can use AR(1) structure to deal with this correlation.
If your animals were in the different cages and one cage had multiple animals, maybe you need to treat the effect of cage as random.


Saber se existem espaços em branco

Question: Boa comunidade!
Tenho a seguinte duvida. Como poderei alertar o utilizador de que existem espaços em branco no campo username?
Assim é como estou a validar o username agora:
if (empty($_POST["username"])) {
 $nameErr = "Escolha um username.";
   } else {
 $uname = test_input($_POST["username"]);
 $v1='ok';

 if (!preg_match("/^[a-zA-Z-0-9-_]*$/",$uname)) {
   $nameErr = "Somente letras e números.";
 }
}

A solução foi esta:
 if ($_SERVER["REQUEST_METHOD"] == "POST") {
 if (empty($_POST["username"])) {
  $nameErr = "Escolha um username.";
   } else {
 $uname = test_input($_POST["username"]);

 // check if name only contains letters and whitespace

 // aqui
 if (!ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$", $_POST["username"]) ) {

   $nameErr = "Somente letras e números.";
 }

}
Comment: @Diego Felipe, A validação server-side sempre deve ser executada independente de existir validação client-side.
Comment: @DiegoFelipe validação só é do lado do servidor. Do lado do cliente você só consegue fazer uma mera checagem preliminar, mas não tem como evitar o envio de dados inadequados.
Comment: Validação de form? Já cogitou usar javascript? Esse tipo de validação do lado do servidor só desperdiça requisição e processamento.
Comment: @DiegoFelipe Eu nao concordo com a parte que você disse que "essa validação só desperdiça requisição e processamento", pois ela fundamental para integridade de dados é sempre a do servidor. Como economia de banda e requisição, eu concordo que pré-validação é bom (essa parte eu nem questionei, aliás).
Comment: Obrigado por responder @DiegoFelipe. Sim é validação de formulário de registo. Neste caso, o campo "username". eu não quero espaços no username... Estou pelo php mesmo
Comment: Modifique a sua pergunta, @David Concha, pois da forma como está diferente do que comentou. Um campo em branco é muito diferente de remover espaços num campo específico.
Comment: @DanielOmine sim, mas tendo a validação do lado do cliente, já evita muitas requisições simplesmente porque um campo ou outro não foi preenchido. Vejo o php mais para confirmar a validação(o usuario pode desativar o javascript) ou como segurança de que os dados estão realmente sendo passados corretamente.
Comment: @Bacco mas você não concorda que reduz bastante o número de requisições desperdiçadas por causa de validação que poderiam ser alertas ao user antes de se submeter?
Answer: Tente
<?php
$username = trim($_POST["username"]);

if(empty($username) || is_null($username)){
echo 'Preencha o seu username!';
}else{
echo 'Tudo OK';
}
?>

A função trim limpa os espaços da esquerda e direita.
A função empty verifica se o campo é vazio.
A função is_null verifica se o campo é do tipo NULL
Caso queira remover espaços de um campo você pode fazer assim:
<?php
$username = str_replace(" ", "", trim($_POST["username"]));
//Removerá todos os espaços do username
?>

Para ficar melhor, use sempre required nas tags HTML (dos inputs) que você quer que seja obrigatórios, exemplo:
<input type="text" name="username" required>

Assim quando o usuário submeter o formulário e o campo estiver vazio ele automaticamente exibe uma mensagem para o usuário preencher o campo, sendo assim, não deixa submeter o form antes de preencher aquele campo.
Para aceitar somente caracteres "normais":
<?php
if (!ereg("^([A-Za-z0-9_-])", $_POST["username"]) ) {
    echo "Não use caracteres especiais nem espaços!";
}
?>

Comment: @DiegoFelipe vai disparar um _warning_ na verdade.
Comment: ereg_ foi depreciada no php5.3 e removida no 7.
Comment: Eu não queria remover os espaços, e sim alertar o utilizador q existem espaços em branco no campo `username`
Comment: Verifique o último exemplo que dei com `ereg`
Comment: Se o indice do post não existir, isso vai disparar um erro.
Comment: usei o seu `ereg` e continua não mostrando o erro de que existem espaços. vou analisar melhor o meu código.
Answer: Numa expressão regular o \s significa espaço em branco. Pode trocar o [a-zA-Z-0-9-_] por \s, isso capturará.
if(preg_match("/\s*/",$uname)){
   echo 'espaço em branco';
}else{
    echo 'nome válido.';
}

Conforme o comentário Guilherme Lautert, o \s além do espaço em branco significa outros caracteres como  \t\r\n\f\v
Comment: `\s = [ \t\r\n\f\v]`, acho que dever ser só `' '` mesmo :D
Comment: @GuilhermeLautert, haha depende do caso, tem gente que não gosta de espaços entre linhas ou remove eles dos parenteses `funcao ( $param );` aí o cara ve um espaço na regex e acha que está atoa e remove ele :P.
Comment: Compreendo, mas sempre saliento isso, pois o pessoal sempre divulga `\s` como sendo `' '`, mas na verdade é muito mais, ate "tab vertical" (`\v`), que nem sei o que é isso :P
Comment: @GuilhermeLautert [What is a vertical tab?](http://stackoverflow.com/q/3380538/1342547) a dois minutos atrás eu também não sabia haha xD
Answer: if (isset($_POST['username'])) {
    /**
    Aqui remove não somente o caracter de espaço ansi, como também o caracter de espaço multibyte, do idioma japonês.
    */
    $str = mbstr_replace(array(' ', ' '), '', $_POST['username']);

    /**
    Aqui comparamos a string original com a string sanitizada. Se forem diferentes, quer dizer que existia espaços.
    */
    if ($_POST['username'] != $str) {
        echo 'digitou o nome com espaços';
    }
}

O exemplo é meramente didático. Esteja ciente, por favor.
Adapte o exemplo conforme a sua necessidade.
Para entender melhor veja esse tópico que fala sobre sanitização, filtragem e validação: Como saber se o form é enviado
Answer: Tente isso:
<?php
    //Tira os espaços em branco do começo e do fim
    $username = trim($_POST["username"]);

    if(empty($username) || is_null($username)) {
        echo 'O username não pode ser vazio';
    } else if (strrpos($username, " ") !== false) { //Procura a última ocorrência de espaço
        echo 'Não pode haver espaços no meio do username';
    } else {
        echo 'Username válido';
    }
?>

Saber se existem espaços em branco


How to memorize multiple pieces in only 20 days?

Question: Just recently I have begun to learn the tuba. For a band I am in, I am required to memorize 5 pieces. Each piece has a length of about 1/2 to 1 full page. However, I only have 20 days to memorize all 5. As I have never had to memorize music before, how do you suggest I go about it? Should I focus on one piece until I have it down pat and then move on to the next, or bounce around between songs each day?
Thanks!
Comment: One technique that can help is to look for structures in the music. Don't just learn the notes, be aware of what scales are used, the harmonies, sequences, patterns, repeated sections. You can do a lot of this work at times when you can't play, just by looking at the music.
Answer: I've had to memorize several different pieces in short amounts of time before, and I've tried different things.
Definitely do not wait to start on the second one until you finished the first one. If you do that, you have to memorize each piece in only four days. If you work on all of them every day, then you have 20 days for each piece.
Do start by playing all of them at least once a day. If you can have two separate practice sessions a day where you play through all five in each session, that's best. So if you really want to do this ASAP, get up earlier and play all five first thing in the morning, twice if you have time, then also play all five once or twice again before you go to bed.
After a few days of that, you should start to have parts of each piece memorized and other parts that aren't sticking as well. Keep playing each piece all the way through and then go back and repeat the parts that aren't sticking a few more times.
Also make notes in pencil on the pages about things that you keep forgetting or that trip you up. Actually write those notes - the process of writing helps you remember because it has to be processed by your brain differently.
If you have to play 100% without the sheet music after 20 days, then at least five days beforehand or as soon as you think you can, start playing through all five without the music. When you get stuck, look at the music and then close it again and play what you got stuck on. If you have time, go back a second time and try to get through the part you forgot.
Absolutely do not miss a day of practice and absolutely play every piece at least once a day. If you can't practice morning and night all days, that's ok, just make sure you get at least one run through of everything every day.
Comment: Nice answer. I just want to add that it's not enough to just have the sheet in front of you and not look at it. You have to turn it around or put the sheet away so you have to move more than just your eyes. After having looked put it away again. Everything else will give you a false sense of knowing the sheet.
Comment: The poor neighbours, with tuba practice first thing in the morning!
Answer: I'm also an almost newbie tenor sax player, an amateur choir singer, and a complete newcomer to this forum.
I think a good way to memorize songs is (exporting and) playing them with a mobile app, then listen to them all day trying to sing on top. This way you make the songs yours.
There are some good mobile apps that let you import standard MusicXml files (which you can export/convert from desktop programs). I personally use Android's PhonicScore for choir songs (no advertisement, I have nothing with them). Or use MuseScore player.
When you sing each song it's easy for you to find the parts you sing wrong or those where you have any doubts. From that point you can read the music sheet or listen to that measure in the app. DON'T corrupt the song in your mind, always listen to the real one when you face the smallest doubt!
Usually, the less intuitive parts of a song are precisely the ones which make it special.  But also are the parts one uses to reinvent BAD. The strange notes you'll have doubts about when singing or playing, surely will be the most relevant in the song.
This way, singing the songs all day, next time you play them on your instrument you'll have half of the work already done: you know the song! You know its rhythm, you know where the hardest parts are, etc. You can free your mind to concentrate almost exclusively on fingering.
Playing tuba the rhythm is very important, (imho) you could miss a note but never the beat or cadence! :D
Imagine how easy for you will be to (learn to) play a song you know well, say 'Happy Birthday to you' :)
Comment: singing wont help you know the fingerings
Comment: I agree, but if you have the song in your mind you'll be able to focus exclusively on fingering when you try to play it. It works for me. I cannot practice with the instrument the whole day, but I can advance my knowledge of the song by singing it everywhere.
Comment: Lots of music is not singable
Comment: perhaps. May be decreasing BPMs could help
Comment: Also tenor saxophone player. Remembering and being able to sing the Pink Panther theme has not helped me play it from memory :) I think your strategy only works for simpler pieces.
Comment: at least for jazz playing I think the goal is to play what you sing in your mind. The fingers should jump the intervals and find the right notes without you having to think about it. I use to play by ear, so knowing first how to sing a song really helps me to play it. ;)
Answer: If you're quite limited for practice time, you should focus on how your practice can make you most useful to the band. If there's parts where you are prominent (there aren't may tuba solos, but there are plenty of times where you'll walk the bass down with a big ol "bum bum bum bum".) Make sure you have these down pat.
Identify any patterns in the music that make it easier. If it's beginner level, or marching band, you're very often going to have simple hi-low-hi-low style beats which you can rather easily memorize.
And most importantly, don't sweat it. You'd be amazed how good your brain can be at remembering once you start playing, even without the music. Make sure you try it without the music at least a few times before your big show, and you should be just fine.
Comment: "focus on how your practice can make you most useful to the band."  Best advice in the entire thread, IMO.
Answer: Definitely bounce around between songs. Reliable memorizing works... a bit like painting: put on a layer, let it sink/dry, repeat. If you try to slosh on all the paint at once on a spot, it'll just get smeared over irregularly. You'll end up mixing that piece up with the others. Whereas if you practice from the start switching between the songs, you'll properly memorize what's different about each of them.
(For technically difficult stuff, it can be a different story, but that doesn't seem to be the issue here.)
Answer: That's a very broad question, and I might not be the best person to answer it, as I never deliberately memorise any pieces and always take the sheets with me (so does my teacher).
It depends on how your memory works to begin with. The majority of people are strongly visual and find it easier to memorise what the notes look like on paper as an image instead of remembering how they sound or what progressions they follow. If you are one of those people, try to memorise what you see on paper. For me personally that method wouldn't work. I am audial/kinaesthetic when it comes to memory. The majority of sources online say there is no such thing as muscle memory, but I know the difference and stick to instruments with keys and frets, because the sense of touching the instrument affects how well I can play it. So you should first identify what memorisation technique works best for you.
The rest depends on repetition and atomisation. You should study the pieces, identify the techniques the composer used (and why he did it), find repeating sections and try to recall each identified section from memory after playing it once. This works for practising music too, not just for memorising it: breaking it up into logical parts eases learning.
Playing all pieces together (in the order you are going to play them with the orchestra) seems to be very helpful as well. I find it easier to recall scales if I play them in the succession I have learnt them in, for example. I know, because I basically had to learn them from scratch after I started playing them chromatically as opposed to following the circle of fifths.
Last but not least, it is important that you sleep well, rest and do not "overpractise". According to modern research, there is no benefit in practising for more than 25 minutes in succession - it's just a waste of time that can damage you physically as well.
Comment: I have a hard time believing that 25 minute figure. I know from my own life that I can learn faster by having longer practice sessions. Tom Morello practiced 8 hours every day when he was in college and he said in a year he went from being a beginner to being better than all his friends. I've had students who play their instruments for hours every day and they progress much faster than my other students.
Comment: @topomorto, oh, sorry, I took it the wrong way completely. I apologise. A lot of musicians, especially successful ones, rely strongly on photographic memory and reflexes. Then there's a reasonably large group that "plays by ear" but can't even read sheet music. I was surprised too, the more I got into the musical world. Not "listening" to music is sometimes helpful in a band environment, because you don't get distracted by the sounds other people are making that much. It took me personally a very long time to get used to having others play with me, and it still puts me off occasionally.
Comment: I'd wonder if a *musician* who can't remember how things sound had really chosen the right hobby!
Comment: @ToddWilcox If you want to be really good there's nothing wrong with practising 8 hours a day. But research shows that you can learn even more in those 8 hours if you take a 5 minute break every half hour.
Comment: @ToddWilcox I wonder if it's not so much long long one's practice session is, but instead how long one practices any one thing.  For me, one hour of practicing the same scale is 40 minutes of wasted time.  But 20 minutes of working on a scale followed by 20 minutes of practicing a piece followed by 20 minutes of practicing chords (for example) works great.  But people aren't all the same; there are probably some who can focus and improve when spending hours on the same thing.
Comment: Interesting point that *not* thinking of the sound might help... I hadn't considered that!
Comment: @ToddWilcox, that figure comes from my teacher, I haven't read any research to back it up. What I do know is that in my first year of playing saxophone I went from being a beginner to being better than high school graduates by only doing 2 25-minute-long sessions a day. Maybe it depends on the person in question.
Comment: @PiedPiper, that's what I was referring to. Could you please edit my post to reflect that idea? With longer practice times, a lot of concerns arise though... Even with my little time investment, I still got a numb left little finger 6 months after starting to play. Thankfully, the issue hasn't been present for years, but I had to visit a chiropractor regularly when it was still there.
Comment: @topomorto, I am assuming you are addressing me, but I'm not sure if I should even honour you with an answer. Music has never been a "hobby" for me. And if you read my answer, you will see that I mention audial and kinaesthetic memory. I easily memorise the sound and finger progressions for a piece (also because I am familiar with compositional techniques for a variety of genres and know my scales by heart), but I would never be able to recall a note sheet (the visuals) from memory like some of my fellow musicians do, because I do not have a _photographic_ memory.
Comment: You said "The majority of people are strongly visual". I'm just wondering that if would necessarily be true of musicians. I'd expect musicians to have a better memory for sounds than the general population.
Answer: One more thing: Getting the rhythm rock solid is your top priority. When asked, every accomplished musician I know will say something like "I'd much rather play a wrong note at the right time than play the right note at the wrong time."
It's especially true for bass instruments.


Ajuda com consulta SQL com COUNT em multiplas linhas

Question: Olá, estou fazendo a seguinte consulta
SELECT p.id, c.nome, v.titulo, count(v.titulo)
FROM passageiros   AS p
LEFT JOIN clientes AS c ON c.id = p.id_cliente
LEFT JOIN viagens  AS v ON v.id = p.id_viagem
GROUP BY v.titulo;

E ela esta me retornando o seguinte resultado:

id| nome       | titulo                  |  count(v.titulo)
1 | 'bruno'    | 'gramado'               |  5
6 | 'alea vang'| 'gramado - mundo magico'|  5
11| 'bruno'    | 'beto carrero'          |  3
14| 'bruno'    | 'caminhos rurais'       |  6

Porém o que eu gostaria é que ela retornasse a lista de cada um dos nomes de cada titulo junto com o count total daquele titulo:

id| nome               | titulo                   | count(v.titulo)
1 | 'bruno'            | 'gramado'                | 5
2 | 'tamires'          | 'gramado'                | 5
3 | 'christen wiggins' | 'gramado'                | 5
4 | 'justine howard'   | 'gramado'                | 5
5 | 'anika hammond'    | 'gramado'                | 5
6 | 'alea vang'        | 'gramado - mundo magico' | 5
7 | 'fredericka jensen'| 'gramado - mundo magico' | 5
8 | 'alexa duncan'     | 'gramado - mundo magico' | 5
9 | 'lynn mclean'      | 'gramado - mundo magico' | 5
10| 'allegra cantrell' | 'gramado - mundo magico' | 5
11| 'bruno'            | 'beto carrero'           | 3
12| 'tamires'          | 'beto carrero'           | 3
13| 'christen wiggins' | 'beto carrero'           | 3
14| 'bruno'            | 'caminhos rurais'        | 6
15| 'tamires'          | 'caminhos rurais'        | 6
16| 'christen wiggins' | 'caminhos rurais'        | 6
17| 'alexa duncan'     | 'caminhos rurais'        | 6
18| 'lynn mclean'      | 'caminhos rurais'        | 6
19| 'allegra cantrell' | 'caminhos rurais'        | 6

EDIT:
Ao fazer a consulta utilizando GROUP BY v.titulo, p.id; eu tenho o retorno da lista completa dos nomes, porém o count retorna apenas 1 em todos as linhas.
Tentei criar o count dentro de uma subquery, mas por ele retornar vários resultados, a pesquisa não teve sucesso.
Answer: A forma mais simples de fazer isso é com uma subconsulta; você cria um select pra retornar o total de registros da viagem da linha pesquisada:
SELECT p.id, c.nome, v.titulo, (select count(*) from passageiros p2 where p2.id_viagem = p.id_viagem) as total
FROM passageiros AS p
LEFT JOIN clientes AS c ON c.id = p.id_cliente
LEFT JOIN viagens AS v ON v.id = p.id_viagem

Dá uma olhada nesse fiddle que tá funcionando como deseja.
Comment: Estava quase no caminho certo, em meus testes acabei fazendo uma consulta parecida com esta, porém estava fazendo a comparação errada no `where`, muito obrigado.
Comment: massa, mete bronca =]
Answer: Uma solução, como indicou na pergunta, passa por calcular o total de passageiros para cada viagem numa subquery. Fica aqui um exemplo que deve devolver o resultado esperado.
SELECT p.id, c.nome, v.titulo, t.num_total_passageiros
  FROM passageiros p
  LEFT JOIN clientes c
    ON c.id = p.id_cliente
  LEFT JOIN viagens v
    ON v.id = p.id_viagem
  LEFT JOIN
 (
    SELECT ip.id_viagem, COUNT(DISTINCT ip.id) as num_total_passageiros
      FROM viagens iv
     GROUP BY ip.id_viagem
 ) t
   ON t.id_viagem = v.id
ORDER BY p.id

Comment: Gostaria de agradecer a disposição, foi de muita ajuda e também retornou o resultado esperado, porém escolhi a outra solução pela simplicidade dela, mas quero deixar registrado que esta também funcionou perfeitamente bem, muito obrigado.
Comment: @bruno101. Não tem que agradecer!
Answer: Opa. Pelo que consegui entender de sua dúvida, queres que a coluna "nome" não se repita na sua consulta. Portanto, o que quer seria basicamente saber quantas vezes que o cliente 'x' fez a viagen 'y', isso?
Nesse caso, bastaria adicionar ao seu group by o nome do cliente. Segue exemplo:
SELECT p.id, c.nome, v.titulo, count(v.titulo)
FROM passageiros   AS p
LEFT JOIN clientes AS c ON c.id = p.id_cliente
LEFT JOIN viagens  AS v ON v.id = p.id_viagem
GROUP BY c.nome, v.titulo;

Espero ter ajudado! Caso não seja isto, espero que outros consigam sanar sua dúvida!
Valeu!
Comment: Com esta consulta ele retorna todos os nomes, porém o `count` fica com `1`, eu gostaria que ele retornasse o  `count` correto para cada titulo de lugar em cada registro, tentei fazer com uma `subquery`, porém sem sucesso, visto que para alguns resultados ele retorna 5, outros 3, outros ainda retorna 6 (como na primeira tabela de exemplo). Mas muito obrigado por tentar ajudar.


files saved as package (with filewrappers) and icloud drive, are they zipped when emailed?

Question: I have an app which uses UIDocument and writes data using filewrappers:
    public override func contents(forType typeName: String) throws -> Any {
    print("******writing the contents******")
    print("**** typeName = \(typeName)")
    let result = FileWrapper(directoryWithFileWrappers: [:])
    ... lots more....
}

This actually works fine. I also have in my plist the uti of the document. The document can be saved, copied to icloud drive, imported back in to the app, so far so good....
But now the hard part: Icloud drive has an email button. If I mail a working file via that button to myself, and save the file on the mac, the right click menu option "show package contents" is gone. (While it is there for the same file in icloud drive).
Also, if i try to open this mail attachment on the iphone, my app is unable to find a subpath into the wrapped file. (so my file is called bla.myextension, and metadata is supposed to be at bla.myextension/meta.xml but the file which is in Inbox appears to be a "file" rather than a directory.
What is happening. Is the email somehow automatically zipping things up?
Answer: The file indeed is zipped automatically. So in application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) just check if the result is a directory, because opening from icloud drive may give you unzipped results. If it is a directory then you have to unzip it yourself.
            var isDir : ObjCBool = ObjCBool( false)
            if fileManager.fileExists(atPath: url.path, isDirectory: &isDir) {
                if isDir.boolValue {
                    ...copy directory...
                }
                else {
                    ...unzip and copy....
                }

            }


Hit counter: To know the exact number of visits to the website

Question: I have developed a web project in jsp and servlets along with html css and bootstrap 3 as a front end. I am trying to code a hit counter by using servlet but when the server restarts the hit counter initialises to zero. Though I know that in Real world there will be little scenarios when the server will be down. So should i store the hit counter in a database...
Answer: You can store the hit counter in the database.
Override Servlet's destroy() method.
@Override
public void destroy() {
    //super.destroy();
   //Do you Database operations.
}

And get the hit counter again in Servlet's init() method from Database when the application/Server starts.


I've apparently locked myself out of ssh on one of my Google Compute instances

Question: As recently as yesterday, I was able to connect to our development instance via my local ssh client, using one of several ssh keys listed under sshKeys in the instance's custom metadata (the old-fashioned way). ("Block  project-wide ssh keys" is checked). Also that afternoon, while connected, I was doing something where a second ssh session would be convenient. I tried opening a second connection through the local ssh client, and got "Permission denied (publickey)." I tried opening a second connection from the instance console page, and it wouldn't connect, either. Meanwhile, the ssh session I was using continued to work just fine.
This morning I can't get an ssh session on that instance AT ALL.
The only thing I can remember doing yesterday, that was the least bit unusual, was a chmod on my home directory, setting it to "777."
I tried yanking out the sshKeys metadata, and trying the console ssh again. No joy. Then I looked at the serial port 1 log, and noticed this, with timestamps showing GMT for approximately when I tried it:
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.
Nov 28 21:26:49 bitnami-trac-dm-87ea google-accounts: INFO Removing user <redacted>.

I can get to the password prompt on the serial port, but I've never set myself up with password access, to the best of my recollection.
Comment: Make that an "answer," "ceejayoz," and I'll call it solved! I found that I could tell the web-to-ssh on the instance console to sign me on as another user, one to whom I'd given sudo authority, and from that user, I was able to chmod my home directory to 755, and once I did that, I could once again ssh as myself.
Comment: "The only thing I can remember doing yesterday, that was the least bit unusual, was a chmod on my home directory, setting it to '777.'" That'll have done it. If your SSH keys are writable by other users, SSH will refuse to use them.
Answer:
The only thing I can remember doing yesterday, that was the least bit unusual, was a chmod on my home directory, setting it to "777."

This is probably what locked you out.
The SSH daemon is pretty paranoid (for good reason), and it'll check various permissions before it allows a connection. If your .ssh/authorized_keys file is writable by other users on the server, SSH won't allow incoming connections for the public keys listed in there.
(It'll also do the same for outbound connections if it detects your private keys are too readable/writeable.)
Comment: Thanks for the additional information. Unfortunately, I don't have enough reputation points for my up-vote to actually show, but I did mark the answer as accepted. Sometimes, I forget that compared to OS/400, where the microcode will usually stop you from doing something stupid, *nix can be like walking on mined eggshells.

I've written down the specifics of how I undid the damage, and stuck it in a secured disk image on my work Mac, with a special icon superimposing the international "no" symbol over the number 777.


What virtual machine software for fail-over and snapshots?

Question: We're looking to virtualize a few machines with the hope that we can:
a) Take "snapshots" of a machine to use as backups
b) Implement a system where if the software/hardware fails, we can quickly and easily load up an recent snapshot on new hardware and replace the failed machine with a new one.
As always, cost is a concern- there's only 3 or 4 servers we're going to do this with, so we don't want to drop $50,000 on this.
I'm confused by all of the different virtual machine offerings. Which one is does what I want, and does it easily?
Comment: I'm not sure about vmware, but I can speak for Hyper-V when i say snapshots are NOT for backups.
http://systemcentercentral.com/BlogDetails/tabid/143/IndexId/12747/Default.aspx
Comment: Care to elaborate why not?
Comment: I've elaborated a small amount why in my answer. I'll update it with more now.
Answer: Hyper-V core is free, but to get what you want you need to purchase System Centre Virtual Machine Manager to do it.
VMWare ESXi is free, but to get what you want you need to purchase vSphere.
Xen is free, but the free version is always one generation behind the paid I believe.
To do what you want with VMWare and ESXi you'll also need shared storage. To do this with Xen you can use DRDB to replicate, but we've done that in the past and performance can suffer vastly.
As DanBig said, as far as the term "snapshots" goes, in the virtual world a snapshot is linked to the VM and if seperated is totally useless, so they're no good for backups. But all of the solutions have their own backup procedures.
To go into more detail, a "snapshot" is simply a point-in-time frozen version of the HDD, where (in layments terms) all changed bytes are linked to seperate sectors, so that both versions can co-exist. If you seperate one from the other, they're useless on their own, they both need to be kept together to be useful. So you can't just copy a snapshot and expect it to work as a backup. However, all hypervisors have their own backup techniques.
A fairly global one is cloning the VM, as they CAN be seperated from their original (unless you create a "linked" clone), but cloning is an IO-expensive operating, whereas snapshots require almost no IO do. Also, depending on the guest OS and if it supports the various hypervisor "tools" you may not be able to clone a machine while it's booted up (Hyper-V is a good example of this).
Comment: I'm pretty sure if you replace "shapshot" with "backup" then Hyper-V will do it without SCVMM.
Comment: @Ernie, can you still do failover without SCVMM? I've never tried it.
Comment: I totally agree to you in case of Xen the free version is always one step behind the paid one.
Answer: I will go out and suggest Ganeti. Superb open source that does exactly what you want, has strong support behind it (it's a Google project) and works wonders. I have 100+ being managed by it, some of those with DRBD (disk mirroring) failover/migration.
The interface is command line based but there's a ganeti-web project walking big steps.
Comment: Hey that looks cool. I'll pass it on to our Xen guy... he was looking for a similar tool the other week.
Answer: From my standpoint there are three real players in the virtualization space:
Microsoft with Hyper-V
VMware with a few different product offerings
Citrix with XEN Server
They all do the same basic things and have the same basic features. Performance is usually pretty comparable in basic setups. Until you start getting into the really high end features theres not a lot of difference.
Other people will probably point you to a lot of different 'nix based options, and those are all probably fine, these three seem to be the leaders in the virtualization space.
Answer: openvz can do what you need it to do pretty well and proxmox VE (free) or solusvm (paid) are good options for this and can do snapshots (backups) which are recoverable to other servers as they are basically templates in which you can create fresh servers
proxmox i believe can hot migrate vps's to different hypervisors or possibly even do it automatically in event of failure if you use some sort of shared storage backend too


Under what conditions can a PLS regression model be expressed by single linear equation?

Question: I am confused by two, yet inconsistent for me, facts: Since the PLS regression is expressed by  matrices of scores and loadings as
$$X=TP^T+E\\Y=UQ^T+F$$
how it can be translated into linear equation like $Y=a+b_1X_1+b_2X_2+...+b_nX_n$?
(I have found this in several papers).
Answer: There is a good summary of PLS regression in

Rosipal, R and Krämer, N (2006). Overview and recent advances in
  Partial Least
  Squares.
  In Saunder, C, Grobelnik, M, Gunn, S, and Shawe-Taylors (Eds.),
  Subspace, Latent Structure and Feature Selection, pp. 34-51, Springer.

Using your notation, where $P$ and $Q$ are matrices of loadings, of dimensions $(N\times p)$ and $(M\times p)$, and $T$ and $U$ are $(n\times p)$ matrices of $p$ scores for $n$ individuals ($p\le\min(n,N)$), component scores are constructed as $t=Xw$ and $u=Yc$, and we find orthogonal weight vectors, $w$ and $c$, by maximizing covariance between $t$ and $u$, with appropriate constraints on $w$ and $c$ ($\|w\|=\|c\|=1$).
This is usually done iteratively using the popular NIPALS algorithm, but other methods have been proposed (SVD, SIMPLS), and different models of PLS lead to different deflation strategies. A good overview is available in

Wegelin, JA (200). A Survey of Partial Least Squares (PLS) Methods, with Emphasis on the Two-Block Case. Technical Report, Department of Statistics, Univeristy of Washington, Seattle.
Höskuldsson, A (1988). PLS regression methods. Journal of Chemometrics, 2, 211-228.

(The chemometrics R vignette gives a short overview as well.)
In PLS regression (with a single or multiple outcomes, aka PLS-2), we further assume a linear (inner) relation between the components scores, $U=TD+H$, where $D$ is a $(p\times p)$ diagonal matrix of weights, and $H$ is the matrix of residuals. Therefore, following Rosipal and Krämer's notation, the $Y$ matrix can be decomposed as follows:
$$Y=TDQ^T+\underbrace{(HQ^T+F)}_{residuals}$$
which is roughly an OLS decomposition considering the orthogonal predictors $T$, and where $C^T=DQ^T$ is the $(p\times M)$ matrix of regression coefficients. Its estimate can be computed as $\hat C=(T^TT)^{-1}T^TY$.
It is also possible to express the PLS regression model using the observed block $X$ directly, as $Y=XB+(HQ^T+F)$. Using the fact that $T=XW(P^TW)^{-1}$ ($T^TT=\mathbb I_p$), Rosipal and Krämer shows that the regression coefficients are then estimated as $\hat B=X^TU(T^TXX^TU)^{-1}T^TY$. This allows to express separate $\hat y$ (in case of PLS-2) as a linear combination of the $x_i$ ($i=1,\dots,N$).


Are these equations derivations of the other?

Question: It is stated   P(A|B) = {P(A and B)}{P(B)}
I would like to know if this is a derived from the Bayes' theorem P(A|B) = { P(A)* P(B|A) }/{P(B) }
Comment: No, it is the definition of conditional probability.
Answer: No, it is the converse.  Bayes' Theorem may be derived from the definition of conditional probability.  $$\mathsf P(A\mid B)=\dfrac{\mathsf P(A\cap B)}{\mathsf P(B)}\qquad\text{and}\qquad\mathsf P(B\mid A)=\dfrac{\mathsf P(A\cap B)}{\mathsf P(A)}\\\text{therefore}\\~\\\mathsf P(A\mid B)=\dfrac{\mathsf P(A)\,\mathsf P(B\mid A)}{\mathsf P(B)}$$
However, the factor of $\mathsf P(A\cap B)$ cannot be deduced from Bayes' Theorem.


Proving Theorem on Sub-Group

Question: Consider the below theorem on Sub-Groups

Theorem : Let $(G, \circ)$ be a group and $H$ be a non-empty finite subset of $G$. Then $(H, \circ)$ is a subgroup of $(G, \circ)$ if and only if $a \in H, b \in H \implies a \circ b \in H$

Proving Forward : If $(H, \circ)$ is a subgroup of $(G, \circ)$, then $a \in H, b \in H \implies a \circ b \in H$ using Closure Property.
Proving Backward : If $a \in H, b \in H \implies a \circ b \in H$, then $(H, \circ)$ is a subgroup of $(G, \circ)$.
In order to prove this we have to satisfy 4 properties of group i.e.

Closure
Associative
Existence of Identity
Existence of inverse

Property 1: Satisfied
Property 2: Satisfied. Since $H$ is a non-empty subset of $G$ and $\circ$   is associative on $G$, $\circ$ is assoicative on H.
Property 3: ?
Property 4: ?
How can I prove existence of identity and existence of inverse with just information of Closure Property.
Comment: Hint:  it is critical that $H$ be finite.  take $a\in H$ and consider $\{a,a^2,a^3,\dots\}$.
Answer: Since $H$ is non-empty, pick any old $a \in H$. Consider the map; $H \to H$ given by:
$h \mapsto ah$ (left-multiplication by $a$).
This map is injective (since it's injective on all of $G$), and since $H$ is finite, it's also surjective on $H$ (can you think of an example where this fails for some group $G$ and an infinite subgroup $H$?).
So there must be some $h_0 \in H$, with $ah_0 = a$ (it might be $a$ itself).
Similarly, the map $h \to ha$ is also surjective. This means for any $b \in H$, we have some $x \in H$ with $xa = b$.
Thus $bh_0 = (xa)h_0 = x(ah_0) = xa = b$, for any $b \in H$.
A similar argument shows that there is an $h_1 \in H$ with $h_1a = a$, and for any $c \in H$, another element $y \in H$ such that $ay = c$.
Hence $h_1c = h_1(ay) = (h_1a)y = ay = c$, for any $c \in H$.
So we have a left-identity, and a right-identity. Thus:
$h_1 = h_1h_0 = h_0$.
Thus $h_1 = h_0$ is an identity for $H$. Now it is easy to see that any element $H$ has both a left-inverse, and a right-inverse (just consider the pre-image of the element $e$ under the maps $x \to hx$ and $x \to xh$). So if we suppose $x$ is a left inverse for $h$, and $y$ a right-inverse:
$x = xe = x(hy) (xh)y = ey = y$
so two-sided inverses exist for any $h \in H$, and being unique in $G$, must be unique in $H$.
Answer: For any $a\in H$, $\;\{a^n\mid n\in\mathbf N\}\subset H $. Hence this set is finite, so there are exponent $i,j,\enspace i<j$, such that $a^i=a^j$. As we're in a group, the cancellation law gives $a^{i-j}=e\in H$, whence $a^{-1}=a^{i-j-1}\in H\;$ (note $i-j-1\ge 0$).
Comment: here $H$ is not finite
Comment: What I wrote doesn't imply whatever abou finiteness. I don't see what you mean.
Comment: Well in the question $H$ is a finite non empty subset of $G$. So the counter example you have given doesn't work.
Comment: Oh! You mean as a counter-example to this specific case. Yes it was supposed to be agnostic.

Proving Theorem on Sub-Group


Conda custom channel on windows

Question: I've created a custom channel on a windows box following the steps detailed here.
Now I'd like to access it from a different machine but the channel parameter is a URI and I don't know what form it should take with Windows.
Here's the command I tried to execute:
conda search -c file://machine\C\channel --override-channels scipy

which failed with the following error message:

Fetching package metadata: Error: Invalid index file
Answer: I have been trying to do the same thing, and the answer by Paul made me a bit pessimistic.
It turns out that it is possible to use a UNC-path.
After trying a few hundred combinations of slashes and backslashes, I found this combination to work:
conda search -c "file://\\DOMAIN\SERVER\SHARE\conda\channel" --override-channels

Similarly,
conda config --add channels "file://\\DOMAIN\SERVER\SHARE\conda\channel"

Adds the channel to your config file.
Answer: Let's say that your custom channel is located in the following directory:
N:\conda\channel. Then we would expect to see the following in this directory (1) the win-64 directory (2) the index files inside, in this case the directory N:\conda\channel\win-64\, of repodata.json and repodata.json.bz2 (3) any packages that you have added to your channel.  A search on this channel for the scipy package, ignoring all other channels, would look like this conda search -c file://N:\conda\channel --override-channels scipy
Did you add the scipy package into your custom channel? If you did, then did you run conda index on that directory?
I'm a little confused by your directory structure but, if your channel is machine\C\channel, then what happens when you do dir machine\C\channel?
Comment: Unfortunately, no, not that I'm aware of.  Using a UNC didn't work for me either.
Comment: Thanks, is it possible to use a UNC instead of having to map a drive?
Comment: Yes, UNC paths are possible -- see my answer below.
Answer: I had no success with the other answers though @gDexter42 helped me in the right direction.  Perhaps the API has changed.  Testing several different options I was somewhat surprised that

you can use / or \ interchangably
you do not need to escape spaces
you do not need to enclose paths with spaces in quotes

After creating a custom channel in a network accessible directory, you can search for a conda package using the file path, excluding the file:// mentioned in other posts and in the documentation.
For a UNC Path:
$ conda search -c //my_nas/some/path with spaces/channel --override-channels

or
    $ conda search -c \my_nas\some\path with spaces\channel --override-channels
If the folder is local, or you have mounted a network directory to a local path (D:\ in this example), you would use that file path.
$ conda search -c D:/some/path with spaces/channel --override-channels

or
$ conda search -c D:\some\path with spaces\channel --override-channels

I tested these commands using both Git Bash for Windows and Anaconda Prompt (which I think is just cmd.exe with the path modified so base/root is the active environment).
Note that if you then want to add that path to your .condarc file, you can use the same path.

channels:
  - \\my_nas\some\path with spaces\channel  # UNC
  - D:/some/path with spaces/channel  # local drive
  - defaults  # this gives defaults lower priority
ssl_verify: true

Answer: If you are trying to search for a conda package in a local directory (not on UNC), the following two approaches worked for me.

Navigate to the drive containing the package and try

conda search -c file://folder_path/channel --override-channels

the better way is to drop the file flag which allows you to search from any drive. Type

conda search -c Drive://folder_path/channel --override-channels thus if you are searching from D: drive you would type this as
conda search -c D://folder_path/channel --override-channels
Comment: (base) C:\Users\user>conda search -c C://Temp//my-conda--override-channels --override-channels
Loading channels: failed

UnavailableInvalidChannel: The channel is not accessible or is invalid.
  channel name: C://Temp//my-conda--override-channels
  channel url: https://conda.anaconda.org/C://Temp//my-conda--override-channels
  error code: 404
Answer: If your conda channel is at C:\conda-channel then do:
conda search -c file://\conda-channel --override-channels

There is currently a bug in conda 4.6+ where file://C:\conda-channel will not work as it removes the colon when parsing. And downgrading to 4.5 is dangerous and can mess up your installation.

Conda custom channel on windows


Can't see the intuition behind the validity of this formula: $\exists x(\exists yP(x,y) → \forall z \exists wP(z,w))$

Question: I know that
$$\vdash_{\mathcal G}\exists x(\exists yP(x,y) → \forall z \exists wP(z,w))$$
(I have read and done a syntactic proof of this.)
And therefore also
$$\models \exists x(\exists yP(x,y) → \forall z \exists wP(z,w))$$
By soundness of FOL.
But I can't make sense of how this formula can be valid. It looks wrong to me. The way I read it is: if there exists some $x$ and $y$ such that $P(x,y)$, then forall $z$ and some $w$, $P(z,w)$. But how can that be valid?
The order of quantifiers is significant in FOL, so it might be simpler to consider a logically equivalent formula on a simpler form. This formula can be rewritten to a formula in Prenex Normal Form, for example like this:
$$\exists x \forall y \forall z \exists w: P(x,y) → P(z,w)$$
But this formula does not look like it is valid, either. Here is an attempt at a counter-example in the form of an interpretation of the formula (a structure for it): Let $P = \{0\} \times \mathbb{N}$. Then $P(0,x)$ for all $x \in \mathbb{N}$, but there is no $w \in \mathbb N$ s.t. $P(z,w)$ for all $z \in \mathbb N$. In fact, there is only one $z \in \mathbb N$ s.t. $P(z,w)$ holds for some $w$, namely $z = 0$.
Comment: I believe it should be read as "There exists an $x$ such that if there also exists a $y$ such that $P(x,y)$ is true, then for every $z$ there is $x$ such that $P(z,x)$."
Comment: It would help if you could express the formula without using $x$ twice as a bound variable. If not please check if the formula is correctly written
Comment: @ReneSchipperus good point, I've edited
Comment: Also see [Why is this true? (∃x)(P(x)⇒(∀y)P(y))](http://math.stackexchange.com/q/412387/72995).
Answer: This is just the Drinker Paradox in disguise.
Note the following:
$$\exists x(\exists yP(x,y) → \forall z \exists xP(z,x))\iff \exists x(\exists yP(x,y) → \forall y \exists xP(y,x)).$$
Denoting the predicate $\exists x_2P(x_1,x_2)$ by $D(x_1)$ turns the subject statement into
$$\exists x(D(x)\to \forall yD(y)).$$
If you allow me to rewrite this as $\exists x(\neg D(x)\lor \forall yD(y))$, then I think it is intuitive to think of this is as saying "either someone doesn't drink, or everyone does".
Note that this isn't what this formula conveys immediately. The statement
"either someone doesn't drink, or everyone does" should be formalized as $\exists x\neg D(x)\lor \forall yD(y)$, but they are equivalent and since this is a matter of intuition, I think this close enough.
If it is any help, see my comment here.
Comment: In my opinion you hit the bull's-eye.
Comment: This problem was also discussed in [Why is this true? (∃x)(P(x)⇒(∀y)P(y))](http://math.stackexchange.com/q/412387/72995).
Answer: Assuming the universe is non-empty, consider two cases:

$\forall x\ \exists y\ P(x,y)$.
Here your formula is true, because the conclusion of implication is trivially true.
$\exists x\ \forall y\ \neg P(x,y)$.
Here your formula is true, because for that $x$ we have $\neg P(x,x)$ and so the premise of implication is false.

In fact your formula is very similar to reordering quantifiers, namely
$$\exists x\ \forall y\ P(x,y)\ \to\ \forall y\ \exists x\ P(x,y).$$
I hope this helps $\ddot\smile$
Comment: @ReneSchipperus No, this is only a convention. Some consider only non-empty models, others consider the possibility of empty model (e.g. see [free logic](http://en.wikipedia.org/wiki/Free_logic)). Besides, if you already have this assumption, asserting it a second time won't make the statement invalid.
Comment: The universe is always non empty. This is one of the assumptions of mathematical logic.
Comment: It's a convention of classical first-order logic that should be assumed unless otherwise stated.  The interested case where it's relaxed, as mentioned, is free logic.  There's some discussion of this in the comments to the answer to [Why is this true? (∃x)(P(x)⇒(∀y)P(y))](http://math.stackexchange.com/q/412387/72995).
Answer: But the reading :

if there exists some $x$ and $y$ such that $P(x,y)$, then for all $z$ and some $w$, $P(z,w)$

is not correct; the first $\exists$ is "outside" the parentheses.
Try with an "informal" argument, starting rewriting the formula as :

$∃x(\lnot ∃yP(x,y) \lor ∀z∃wP(z,w))$

you immediately see that you cannot "move inside" the first $\exists$ without changing the meaning of the formula.
If we remember that we can "distribute" $\exists$ over $\lor$, because $\exists$ "is like" an "inifinite" disjunction", we have that our formula is "equivalent" to :

$∃x(\lnot ∃yP(x,y)) \lor ∃x∀z∃wP(z,w)$

which is :

$\lnot ∀x∃yP(x,y) \lor ∃x∀z∃wP(z,w)$.

In the second disjunct, the quantifier $\exists x$ does not do any job, because $x$ in not free in it; thus, forget it.
Finally, we have :

$\lnot ∀x∃yP(x,y) \lor ∀z∃wP(z,w)$

which is "clearly" valid.
Answer: The intuition is clear, take $x$ to be an element with no corresponding $y$ such that $P(x,y)$, if that is possible. Then the hypothesis will be false, and the statement true.
On the other have if for every $x$ there is a $y$, $P(x,y)$ then the conclusion is correct and you can take any element for $x$.


Line bundles have flat connections

Question: Let $M$ be a manifold of $L \to M$ a line bundle (say over $\mathbb{C}$, ie complex line bundle).
Is it true & why that for every such line bundle there exist a flat connection $\nabla_L : \Gamma(X,E)\to \Gamma(X, \Omega_X^1\otimes L)$, i.e. a connection which curvature $\nabla_L^2= \Omega_L \in \Omega ^{2}({\mathrm  {End}}\,L)=\Gamma ({\mathrm  {End}}\,L\otimes \Lambda ^{2}T^{*}M)$ is zero. Thus an existence problem. Sure, I not see any reason why all connections on $L$ should be flat, nevertheless I'm asking if on the other hand there always exist a flat one. If yes, is the claim independ of the field (so we can replace $\mathbb{C}$ by any other)?
Comment: By manifold, you mean a smooth manifold?
Answer: No, this is false. Over $\mathbb{C}$ we have the exact sequence of sheaves of abelian groups on $X$ given by
$$
1 \to \mathbb{C}^\times \to \mathcal{O}_X^\times \stackrel{d \log}{\longrightarrow} \Omega_X \to 0.
$$
The group $H^1(X, \mathbb{C}^\times)$ parametrizes line bundles with flat connection, and under this correspondence, the map to $H^1(X, \mathcal{O}_X^\times)$ (which parametrizes line bundles) forgets the connection. The obstruction to the surjectivity is $H^1(X, \Omega_X)$; a line bundle given by a transition function such that $d \log$ of the transition function is non-trivial in $H^1(X, \Omega_X)$ then gives a counterexample.
Comment: Why $H^1(X, \mathbb{C}^x)$ parametrizes line bundles with *flat connection*?
Comment: @TimGrosskreutz given a line bundle with flat connection, pick an open cover of $X$ which is small enough to trivialize the connection (i.e. over each open your bundle + connection should be isomorphic to $\mathcal{O}, d$). Then on each overlap you get an automorphism of the bundle-with-flat-connection $\mathcal{O}, d$, but that's multiplication by a constant.
Comment: Conversely, given a cech one-cocycle representing a cohomology class (say there are just two opens U and V so that this fits in a comment), you get a sheaf $L$ whose value on U is $\mathbb{C}$ and value on V is $\mathbb{C}$ and restriction map to U \cap V is determined by your one-cocycle. You can tensor this up over the constant sheaf $\mathbb{C}$ with $\mathcal{O}_X$ to get a line bundle $\mathcal{L}$, and this line bundle admits the flat connection $\mathcal{L} = L \otimes _\C\mathcal{O}_X \to L \otimes \Omega$ induced by $d$.
Comment: One point confuses me a bit. If we shrink all members $U_i$ of the covering of $X$ small enough then you claim that over every member $U_i$ (say $=U$) the bundle -with-flat-connection has the shape $\mathcal{O}, d$ and an automorphism of such trivial bundle-with-flat-connection is a multiplication by a constant. I not completetly understand it. Firstly, I know that every connection over a trivial bundle $U \times \mathbb{R}^n$ has the shape $d + \omega$, where $d$ extends the common differential to the $End(\Omega^{\bullet})$ and $\omega$ is a $n \times n$-matrix,
Comment: i.e. a linear map, right? Ok, so flatness of the bundle imply $\omega=0$, right? So the connection is the De-Rham operator. The only remaining question is why every automorphism on such trivial bundle-with connection =De Rham-op, coinsides with multiplication by a constant $\neq 0$? Equivalently, is De-Rham-operator determined up to multiplication by a constant?
Comment: @TimGrosskreutz (We are just working with line bundles, so $\omega$ is just a one-form and not a matrix of such things.) I think what's going on is that a bundle automorphism would be multiplication by a non-vanishing function and $d$ does not commute with that unless the function is constant.
Comment: yes, you are right I see. So essentially we conclude that the automorphisms with are allowed (=compatible with additional connection structure) are constant by the observation that they have to be compatible with $d$ in the sense $d \circ \varphi = d$ for $\varphi \in Aut(U \times \mathbb{R}^n)$. And it's only possible if $\varphi$ is a multiplication by a constant. That's the point, right?

Line bundles have flat connections


Constructing a rectangle from smaller rectangles

Question: For the last few hours I've been attempting to construct a rectangle from smaller rectangles on any angle; I imagined doing so like this https://i.stack.imgur.com/Ymakk.png
[ Where the black lines represent the outline of the constructed rectangle and the red lines represent the triangles that construct it. The red rectangles have to be completely straight also. ]
Obviously it wouldn't look very defined unless I have a very small increment when trying to render it but the end product would hopefully look like a rectangle at a predetermined angle.
The screen is set up so that the top, left hand corner is (0, 0) and the bottom, right is (1, 1). How would I do this? Not specifically looking for actual code, pseudo-code or even an explanation, maybe some math.. would be brilliant! Thanks in advance.
Comment: can you put up with your code in a fiddle?
and please explain it in a simpler way so that more people understand.
Comment: Sure, I can try that. Uhm, basically I'm unable to rotate a rectangle so I assumed I could construct a rectangle from smaller long, thin rectangles to form the rectangle at the required angle. To make a defined rectangle, so that you can't see the edges of the smaller rectangles, I was going to make their y-size incredibly small. Hopefully this image will help: http://imgur.com/UrJJtQx

That demonstrates larger rectangles composing it, so large that you could see the edges of them creating some weird stepped-rectangle. The rectangles constructing it can't be rotated either.
Comment: Seeing the 'javascript' tag, are you doing this in a browser?
Comment: No, I'm not. Sorry, meant to mention that
Answer: Here's a bit of geometry for you:
If your rectangle is perfectly aligned, you can just draw one big rectangle and you win.
If it's slighted at any angle at all, you can express the lines as simple equations
y = m * x + c
where you insert x and y of both edges to calculate m and c (a very simple procedure actually), or you can calculate that m = tan(angle)
Then you can "just" walk down the y coordinates and get the corresponding x positions on the left and right lines that belong to the rectangle by inserting the y, c and m values to the equation and solving for x.
If you look at your rectangle picture, you can see that there's basically three parts: the first part goes from the bottom to the lower left edge. It follows the long side to the left and encounters an edge on the left side. After that you follow both short sides to the right and then you encounter the upper right edge and go up to the upper left corner (of course you could do this from the top down, too)
You'll need to carefully check if you've reached the edge between two lines on the left or right side and switch your values for m and c at the appropiate moments.
I think this should get you close to a solution
Comment: So, basically, find the one point on two lines, work my way along their y-axis until I can't reach any higher, then switch to the other two? Rendering rectangles as I go along?
Comment: Yes, sounds like you understood it the way I meant to convey it :)
Comment: Got it working. I forgot to set this as my accepted answer. Thanks


Determining the equation of a line parallel to two planes.

Question: **The task is to find the equation of a line that intersects lines $\textbf{p1}$ and $\textbf{p2}$, and is parallel to the planes $\textbf{T1}$ and $\textbf{T2}$ the equations are:
$$\textbf{p1:} \quad \frac{x+5}{2} = \frac{y-3}{-4} = \frac{z+1}{3} $$
$$\textbf{p2:} \quad \frac{x-3}{-2} = \frac{y+1}{3} = \frac{z+2}{4}$$
$$\textbf{T1:}\quad  3x+12y-3z-5=0$$
$$\textbf{T2:} \quad 3x-4y+9z+7=0$$
If anyone has an idea for this task and similar tasks please share!
**
Comment: This portion of my Real Analysis comprehension has cobwebs.  My **guess** is that the equation of a plane parallel to $T_1$ must have form: $3x + 12y - 3z = k$.
Answer: Ok so we know this line is parallel to both T1 and T2. which means it must be perpendicular to both of their normal vectors, given by
$\begin{bmatrix}
3 & 12 & -3
\end{bmatrix}$
and
$\begin{bmatrix}
3 & -4 & 9
\end{bmatrix}$
if you find the cross product of these two vectors you will get the directional vector of the line and then by using P1 or P2 we can find an initial point.
Comment: How do you find the initial point ?
Comment: Use the equations of $P_1$ and $P_2$ to find their point of intersection, let's call it $p_3$.
The cross product that Deepak has spoken about (the cross product of the two normal vectors) will be the direction vector ($d$). Once you find that, the equation of the line you need is $p_3 + \lambda d$.
Comment: Could I find the equation's by doing this: write parametric equations for the intersection point of the searched line and p1, by this i will get 3 equations with 5 unknown variables, and do the same thing for the searched line and p2 and now I will get additional one unknown parametar of line p2, and also I can write down 2 more equations from the fact that they intersection at some point and I would get a system that could be solve. So is this a valid solution,because this is the first thing that comes to mi mind?
Comment: @TemzaVelickov Try both methods, see what you get :)
Answer: Hint:
The direction of the line is given by the cross-product of the normals to the planes. If you project the two lines parallelly to this direction to some plane, their 2D intersection is the projection of the searched line.


Early Expansion of Variables in Recipes

Question: I know about the distinction between the two kinds of variables in GNU Make.
I am currently writing a build system where certain variables are defined in sub directories (e.g., VERSION). To make the life simpler for authors of subdirectories, I do not want to force them to make their variables globally unique. I also would like to avoid recursive make.
My problem is now that I need a way to provide some simple library targets that expand these common variables when the target is defined. As a simple example:
FOO := Bar
PHONY: $(FOO)
$(FOO):
    @echo $(FOO)

FOO := Definitely not Bar

PHONY: test2
test2: Bar
    @echo $(FOO)

I would need the output of make test2 to be
Bar
Definitely not Bar

I could, of course, use a temporary variable to force the expansion of FOO in the first rule, but then I need a way to reliably define a new temporary variable. Is there a way to expand a target, e.g. using eval?
edit: Made the curious expansion of FOO more clear in the example code.
Comment: Are you aware that also `make Bar`  does yield `Definitely not Bar` ?
Comment: Yes. Because the whole Makefile is read before the variables are subtituted in the recipes.
Answer: It looks as if you simply want target-specific variables,
e.g.
Makefile
.PHONY: Bar test2

Bar: FOO := Bar
Bar:
    @echo $(FOO)

test2: FOO := Definitely not Bar
test2: Bar
    @echo $(FOO)

which runs like:
$ make test2
Bar
Definitely not Bar

(Note that .PHONY, like all special targets, begins with .)
Answer: You can write some nicely functional code (pun intended) using $(eval …). You get to write closures, and decide what gets expanded when.
Consider this variable:
define rule =
PHONY: ${FOO}
${FOO}:
        @echo $$@ ${FOO}
endef

Nothing strange here. But look what happens when we pass it to eval:
FOO := Bar
$(eval ${rule})

We'd better look at that last line in detail.

make expands $(eval ${rule})

First it expands ${rule}

$$ expands to $
All occurences of ${FOO} are replaced by Bar
leaving us with this text:
PHONY: Bar
Bar:
   @echo $@ Bar
Can you see how the current value of ${FOO} has been baked into the recipe?

Now the block of make syntax is passed to $(eval)

Make creates the new rule as a side effect of the eval

The expansion of the eval though is empty.

Nice.
FOO := Dead
$(eval ${rule})

FOO := Beef
$(eval ${rule})

You aren't very far away from eschewing global variables in favour of local parameters:
$(call makerule,Dead)
$(call makerule,Beef)

Gotta be a good thing, hasn't it?
[AFAICR eval didn't work very well in make 3.81, so use at least version 3.82]

Early Expansion of Variables in Recipes


Usar ou não variáveis para definir um objeto?

Question: Recentemente assistindo alguns tutoriais, vejo programadores omitindo as variáveis em bloco de código. Não sei como se chama essa prática, mas gostaria de saber se é recomendada, quais as vantagens e desvantagens em seu uso, e se a forma como coloquei está correta. A questão é que está funcionando...
Exemplo:
<code>$head = new MakeHead("Title");
    $head->_addmenu("180","./insert");
    $head->_addtoggle('190', 'toggle', 'bar');
$head->_printhead();
</code>
Para:
<code>(new MakeHead("Title"))
    ->_addmenu("180","./insert")
    ->_addtoggle('190', 'togglesearch', 'searchbar')
->_printhead();
</code>
Comment: Não vejo vantagens, apenas as desvantagens em que você perde completamente o seu objeto, o que pode dificultar a manutenção do código e operações de depuração, sem contar que, ao meu ver, prejudica a legibilidade do código.
Comment: eu concordo com @Woss, talvez faça sentido usar numa instância que só vai fazer uma operação talvez, mas nesse exemplo faz 3, faria mais sentido ter a variável e ajuda no debug tbm
Comment: Se não está usando variável é quase certo que também não precisava de uma classe.
Comment: Entendi. Apesar de funcionar, o PHPStorm dá um warning dizendo que minha function não é VOID, e mesmo que eu as defina como metodo():void, o PHPStorm remove o warning mas deixa de fornecer os HINTS da classe e dos métodos...
Answer: A resposta como sempre é Depende.
Antes de decidir se você precisa ou não de uma variável você tem que entender para que você quer o objeto. O objetivo de uma variável é armazenar uma referência a um objeto ou valor para que você possa usar posteriormente, neste sentido se não houver necessidade de usar posteriormente você não precisa armazenar ela em uma variável (ou constante).
Nesse exemplo que você deu nós vemos uma interface fluida, damos este nome a classes cujos métodos retornam uma referência dela mesma ou uma nova instância dela, permitindo invocar um método em cima do retorno do método.
Um exemplo disso pode ser encontrado nas especificações da PSR-7, no qual conforme você invoca os métodos para construir uma mensagem http (ex. Request) você recebe uma nova instância daquela classe podendo encadear chamadas.
Esse tipo de comportamento também é comum no padrão de projeto builder, onde um builder retorna a si mesmo até que um método de construção (ex. make, build ou create) seja chamado retornando o que o builder constrói.
Os principais pontos onde você não precisa ter uma referência em uma variável são:

Você irá criar o objeto apenas para chamar um método, ex.

<code>(new Logger("Startup"))->log("mensagem");
</code>
Neste exemplo assumimos que não vamos precisar desta instância de logger após usa-la, se precisássemos poderíamos armazenar a referência dela em uma variável.

Você irá passar um objeto como parâmetro assim que o criar.

<code>$client->send(new User("João"));
</code>
Neste exemplo se o objeto é simples e a leitura não fica comprometida você pode instanciar o objeto direto na chamada do método.

Um ponto importante a lembrar é que você não está programando para o computador entender, você está programando para que humanos (você e quem quer que venha a dar manutenção neste código) entendam o que foi programado, então você deve tentar deixar sempre que possível seu código legível, se isso exigir a criação de variáveis, crie.

Se você estivesse fazendo código para máquinas apenas você poderia nomear todas as suas variáveis com varNumero, ex. var1, var2, var3, var4, etc, visto que a máquina entenderia, dar nomes que significam algo é algo que fazemos para que nós desenvolvedores consigamos entender o que o programa faz com o mínimo de esforço cognitivo possível.
Comment: Entendi. Então, em outras palavras, no exemplo que postei não seria interessante usar. Basicamente essa rotina cria um cabeçalho na minha página usando um template próprio. Embora não haja nenhum tratamento, apenas execução dos métodos solicitados com as informações passadas
Comment: Olá @EvandroPH, na realidade depende, se for legível para você e o seu time e você não precisar chamar mais esta instância do cabeçalho então você não precisa associar a uma variável. É uma questão de intenção, qual a sua intenção com este objeto, só imprimir o cabeçalho e não fazer mais nada? Neste caso talvez dessa forma funcione melhor. Um conselho que posso dar no entanto é não sacrificar leitura para economizar linhas, o php tem um otimizador que verifica o código antes de executar, então não vai ser declarar uma variável que vai acabar com a performance do seu programa.
Comment: Justamente isso que imaginei. Pesquisei um pouco mais e achei algo sobre o chained methods, que é basicamente isso que mencionei. Na prática não vai mudar muito pra mim não. Na verdade seria apenas por questão de indentação do código mesmo. O PHPStorm indenta corretamente se eu uso o Chained Method, se eu não usar ele remove as indentações.


Custom button behaviour in subpanel

Question: In SuiteCRM I have a module connected with module Contacts. And in this module I created custom button in a subpanel of Contacts which is called "Import". And I want to open the page with import of contacts when I click this button.
How can I do it?
<code> array (
    0 =>
    array (
      'widget_class' => 'SubPanelTopButtonQuickCreate',
    ),
    1 =>
    array (
      'widget_class' => 'SubPanelTopSelectButton',
      'mode' => 'MultiSelect',
    ),  2 =>    array (
      'widget_class' => 'SubPanelImportButton',
    ),
</code>
Answer: Sugar load widget class from include/generic/SugarWidgets/.*
for example you can find definition of  SubPanelTopSelectButton in this directory.The code above wont work because you haven't defined any widget class with name SugarWidgetSubPanelImportButton
Follow the below mentioned steps to achieve required behaviour:

Create directory in custom/include/generic/SugarWidgets/SugarWidgetSubPanelImportButton.php
Create a class SugarWidgetSubPanelImportButton
Extend this class with SubPanelTopSelectButton
Override the SubPanelTopSelectButton relevant methods in which you would like to change the default behaviour.

Custom button behaviour in subpanel


Find max value in a column

Question: I created a few databases and now trying to write a request to find events name, their organizers and the number of sold tickets (There are tables "Organizers", "Events", "Tickets"):
SELECT "Organizers".name, "Events".name, COUNT("Tickets".ID) as tickets_count FROM "Events"
INNER JOIN "Organizers" on "Events".organizer_ID = "Organizers".ID
INNER JOIN "Tickets" on "Events".ID = "Tickets".event_ID
GROUP BY "Organizers".name, "Events".name;

I've got this result:

But I don't know how to output only events with max tickets_count. Does somebody know how to do it?
Comment: Have you tried with `HAVING tickets_count = ( SELECT COUNT("Tickets".ID) as tickets_count  ... ORDER BY tickets_count DESC LIMIT 1)`? Maybe a bit messy though.
Comment: Add script for create table, sample data and expected result
Answer: In recent (starting with v13) versions of PostgreSQL, just add to the end
order by tickets_count DESC fetch first 1 row with ties;

Find max value in a column


Integers that satisfy $a^3= b^2 + 4$

Question: Well, here's my question:
Are there any integers, $a$ and $b$ that satisfy the equation $b^2$$+4$=$a^3$, such that $a$ and $b$ are coprime?
I've already found the case where $b=11$ and $a =5$, but other than that?
And if there do exist other cases, how would I find them? And if not how would I prove so?
Thanks in advance. :)
Comment: Well, then you should also remove the part asking for the proof of their non-existence-if-they-don't in your edit. Tricky among other things.
Comment: Oh, yikes. I'm sorry. You're right. It was misleading. I think it's okay now, though.
Answer: Update: This is a Mordell equation and from the ref E_-00004 from this table all the known solutions were provided here :
<code>E_-00004: r = 1   t = 1   #III =  1
          E(Q) = <(2, 2)>
          R =   0.4503206856
           4 integral points
            1. (2, 2) = 1 * (2, 2)
            2. (2, -2) = -(2, 2)
            3. (5, 11) = -2 * (2, 2)
            4. (5, -11) = -(5, 11)
</code>
Fine references about this kind of problems are :

de Jonquières' 1878 paper (french)
Conrad's paper for simple impossibilities proofs but not only since the theorem $3.3$ is the proof that no other solutions in $\mathbb{Z}$ exists for your equation.

In Jonquières' paper one finds "D'autres fois, mais rarement, on démontre qu'il n'existe qu'une seule solution. C'est ce qui a été fait par Fermat, Euler et Legendre pour les équations $x^3-2=y^2$, $x^3-4=y^2$...¨.
This means that no other solution exist and that this was proved by one or more between Fermat, Euler and Legendre (I'll search references).
Answer: $a=5, b=11$ is one satisfying it. I don't think this is the only pair.
Comment: Oh, i very well did. but you seem to have missed the first version of his Q. he added the line starting "Ah well.. " after my answer appeared here-- see my comment up there. he is getting a flag. he is a cheat.
Comment: I think it's important not to write offensive or even "tough" commentaries towards other people since, unfortunately, it is a *very common* practice over here to change the original question, either by the OP or by someone else. Ashley's answer correctly addressed the OP. +1
Comment: You didn't read the question, did you?
Comment: I apologize. I wrongly interpreted the time of your answer. It's odd that a question can be edited for a while without leaving any mark.
Comment: Oh, I never added the line mentioning 5 and 11. That was always a part of the original question. But I concede, my original question was misleadling-ly phrased.
Comment: @DonAntonio i see your point on the offensive language and do agree to it.
i also think that it is an unpleasantness to the user of the language before it is to many others.
however, i despise more
seeing such petty "efforts" finding grounds on the site-- and this time at the cost of showing me as the
one in the wrong. plagiarism is plagiarism. it never is pleasant to deal with but it never should leak in.
thank you for your comment.
Comment: Karolis Juodelė no problem. i probably would have thought the same. thanks for your comment.
Comment: @MWarsi: you must be meaning you never added that line in your __original__ Q. this is my last comment to you on this Q and very probably anywhere else.
Answer: Using Gaussian integers it is easy to show that the general solution of
$$x^2+y^2=z^3$$
is
$$x=m^3-3m n^2$$
$$y=3m^2n-n^3$$
$$z=m^2+n^2$$
If $x=2$ you get $m=\pm 1, \pm2$ and then you can solve the problem.
Comment: The above derivation is incorrect, for example if $x=y=2$ then $x+iy$ and $x-iy$ are not relatively prime.
Comment: Hey, thanks for that. Now, I've never seen it done that way though. How did you derive the expressions for x, y and z?
Comment: You factor $x^2+y^2=(x+iy)(x-iy)$.  The two factors are relatively prime in $Z[i]$. Therefore $$x+iy=(m+ni)^3$$.
Answer: Observe that
if $a=3k,b^2=a^3-4=(3k)^3-4\equiv-1\pmod 3$ but $b^2\equiv1,0\pmod 3$
if $a=3k+1,b^2=a^3-4=(3k+1)^3-4=9(3k^3+3k^2+k)-3$ which is divisible by $3,$ but not by $9$
So, $a$ must be of the from $3k+2$
Consequently, $b^2-4=a^3-8=(3k+2)^3-8$
$(b+2)(b-2)=9k(3k^2+6k+4)$
Also, as $(a,b)=1,$ both $a,b$ must be odd $\implies (b+2,b-2)=(b+2,b+2-(b-2))=1$ and $k$ is odd
As $k$ is odd, $(k,3k^2+6k+4)=(k,4)=1$
If $b-2=9k,b+2=9k+4$ and $b+2=3k^2+6k+4\implies 3k^2-3k=0\implies k=0,1$
$k=0\implies b=2,a=2$ (but both $a,b$ are odd)
$k=1\implies b=11,a^3=125,a=5$
If $b+2=9k,b-2=9k-4$ and $b-2=3k^2+6k+4\implies 3k^2-3k+8=0$ whose discriminant is negative.
If $b+2=9,a^3=b^2+4=53$
If $b-2=9\implies b=11,a^3=b^2+4=125\implies a=5$
If $b-2=k\implies b=k+2,b+2=k+4$ and $b+2=9(3k^2+6k+4),27k^2+53k+32=0$ whose discriminant is negative.
If $b+2=k\implies b=k-2,b-2=k-4$ and $b-2=9(3k^2+6k+4),27k^2+53k+40=0$ whose discriminant is negative.
Comment: But what if each factor on the left-hand side shares a factor with two or more factors on the right-hand side? I don't believe your proof considers that possibility.

Integers that satisfy $a^3= b^2 + 4$


Yii framework and dynamic subdomains

Question: I want to know how the Yii framework send the request to the right controller depending on the subdomain passed in the URL:
www.mysystem.com -> This request is handled by the default controller of a specific module in my system.
But when the user comes to access their store, they will use the URL: storename.mysystem.com. (There are many different store names)
I would like to know where in Yii can I find the config to set which module/controller will handle this request.
Thank you.
Answer: Here is my config for Yii2
main.php
<code>    <?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

$host = (!empty($_SERVER['HTTP_HOST']))?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
$segments = explode('.',$host);
defined('SUBDOMAIN') or define('SUBDOMAIN', strtolower($segments[0]));

return [
    'id' => 'app-backend',
    'basePath' => dirname(__DIR__),
    'controllerNamespace' => 'backend\controllers',
    'bootstrap' => ['log'],
    'modules' => [
        SUBDOMAIN => [
            'class' => 'backend\modules\\'.SUBDOMAIN.'\\'.ucfirst(SUBDOMAIN),
        ],
    ],
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-backend',
        ],
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
            'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
        ],
        'session' => [
            // this is the name of the session cookie used for login on the backend
            'name' => 'advanced-backend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'db' => [
            'tablePrefix' => SUBDOMAIN.'_',
        ],
        'urlManager'=>[
            'rules' => [
                '<controller:[\w-]+>/<id:\d+>' => ''.SUBDOMAIN.'/<controller>/view',
                '<controller:[\w-]+/<action:[\w-]+>' => ''.SUBDOMAIN.'/<controller>/<action>',
                '<controller:[\w-]+>/<action:[\w-]+>/<id:\d+>' => ''.SUBDOMAIN.'/<controller>/<action>',
            ],
        ],

    ],
    'params' => $params,
];
</code>

Yii framework and dynamic subdomains