Is the difference between key and scales just unordered vs. ordered pitches?

Question: Hi guys I was trying to understand the relationship between keys and scales, from what I understood starting from the basic pitch:
A A# B C C# D D# E F F# G G#
if we start from one and take WWHWWWH
we obtain a major scale if instead we do WHWWHW we obtain a Minor scale.
and so far I understand, now from what I understand a key is simply an unordered set of pitch.
instead a scale is an ordered set of pitches.
so for example
CDEFGABC is the c major scale instead ABCDEFGA is the A minor scale and they contain the same notes, so they shouldn't be in the same key? so should Cmajor key and A minor key be the same?
and in this way I started from the scale and I said since I take the notes of this scale ( for example a C major) i have a C major Key, so to get a key I always have to start from the scale?
Answer: It's more the other way round. Any scale is an ordered set of notes which (usually) goes together. True, start anywhere on the whole set (chromatic), and count TTSTTTS (or WWHWWWH), and you end up with a major scale, in the key of whatever note you started/finished on.
Similarly with a minor scale - but only the natural minor, which, if you didn't realise, is the same order, just starting on the 6th note of any major scale.
A key, however is a slightly different concept, as you suspect. Any key will have (and have to have) a root note - which is the note where any tune in that key feels most at rest - home. Properly know as its tonal centre. Your examples of CDEFGAB could actually have seven different notes as the root, or home note, of a key - or mode. The most common key names will be C major or A minor, but could just as well be D Dorian or F Lydian, for example.
The other aspect of a key is which notes it contains. They're called diatonic, and 'belong' to a particular key. Let's take the scale notes of, say, G A B C D E F♯. They all 'belong' to key G major, and when put together in ascending/descending order, constitute the scale of G major.
You find that any set of notes, such as this, are in a key, and so key and scale are related, but not synonymous.


Using devise form inside Rails custom form

Question: I am using Devise gem for authentication in my current project. I am stuck with an issue to use devise registration and login form inside my custom form and I am not sure how to implementation it in my project.
This custom form has 20-25 fields and if current user is not logged in, I want to include device login and registration forms as well on same view. So when user hit save button of the form, controller will first authenticate or register the user and then later save the form.
<code>class BookController < ApplicationController
    def new
        @book = Shop::Book.new
    end

    def create
        @book = Book.new(params[:book])

        # TODO::
        # validate / register the user if not currently logged-in

        if @book.save
            redirect_to :action => 'list'
        else
            @subjects = Subject.find(:all)
            render :action => 'new'
        end
    end
end
</code>
Comment: You could show both forms in one view, then use an ajax request for the login/registration form so the user doesn't need to leave the page to login.  The only other way I can think of is to set up a relationship between devise and your custom form data and use form_for.
Comment: See if this helps. http://pupeno.com/2010/08/29/show-a-devise-log-in-form-in-another-page/
Comment: I thought about making form_remote_tag for login & registration first but it has some usability issue. This form will have just one button "Save", which will login/register the user first and then proceed to save the model.
Comment: Would it work for you to use the 2 forms on the view, then create a single save submit button to submit both forms ajax style, just specify async: false in the $.ajax options so that it will finish the first request with devise first before doing your custom form?
Answer: check out Digi_Cazter's link then add the form after checking for signed_in?
In your create method something like this should work:
<code>   @user = User.new(:email => 'firstname.lastname@example.com', :password => 'password',    #values from params
   :password_confirmation => 'password')
   @user.save
   sign_in @user  #if you want to do this

       if @book.save
            redirect_to :action => 'list'
        else
            @subjects = Subject.find(:all)
            render :action => 'new'
        end
</code>


Looping through an array using AlpineJS returns no results

Question: I'm attempting to loop through an array using AlpineJS, but for the life of me, I can't get any output.
I'm hoping someone that is more familiar with AlpineJS may be able to assist.
Thanks in advance.
And here's the code:

 response.json())
  .then(data => books = data)">
  <template x-for="(book, index) in books" :key="index">

  </template>

Answer: It looks like you've got the wrong idea of what kind of data this API returns. Copy the URL you're passing to the fetch function and paste it into the browser. Hopefully, you'll see pretty quickly that this endpoint doesn't return an array, it returns an object!

function alpineInstance() {
  return {
    // we'll set our data to hold an object
    bookResponse: {}
  }
}

 response.json())
  .then(data => bookResponse = data)">

    <template x-for="(item, index) in bookResponse.items" :key="index">

  </template>

Comment: Thank you so much Brendan! You're absolutely right in your response and I'm very grateful for your help. Thank you.


Problem with greatest possible value,i know this is right but why?

Question: It is said that greatest possible value of $380$ (2 s.f rounded) is $385$,and least one is $375$. How this is possible? if i try to round $385$ (2 s.f) it should be $390$.
As the least possible value of $390$ is $385$.
How can i resolve these issues?
Answer: Any real number $x$ satisfying $375\leq x<385$ will round to $380$ when being rounded to two significant figures.
Answer: It seems that some people use a different convention for rounding when there is a "5." You seem to be using the "round half up" convention, but some people use the "round half to even" convention, under which you would have both $385$ and $375$ rounding to $380$. See this Wikipedia page.


Hierachical cluster analysis of ordinal variables?

Question: I have a dataset containing 400 variables (chemical compounds, amount classes) with values 0,1,2, or 3 and 50 entries (species).
Can I use hierarchical cluster analysis to get a dendrogram that shows similarities between different entries? There are a lot of 0's, about 80 % or more, in the dataset.
Which package in R you recommend? The one I tried uses only numerical variables.
Answer: HAC needs a dissimilarity matrix.
Compute the matrix as required for your application, e g., using rank correlation.


.htaccess rewrite without www AND redirect to subdirectory

Question: I'd like to redirect

www.example.com/* to example.com/*

And at the same time redirect

example.com/* to example.com/forum/*

But I also have /wiki/ and /blog/ and /style/, so I don't want to redirect

example.com/style/* to example.com/forum/style/*

This is what I have at the moment, which is not working quite correctly:
Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/forum/
RewriteRule ^(.*)$ forum/$1 [R=301,L]

Clarification: my question can be asked in a simpler way.
I'd like to redirect an empty REQUEST_URI or /, or a non-existent file only if it is in the root directory to /forum/.
Comment: This is what I have at the moment, which is not working quite correctly:

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/forum/
RewriteRule ^(.*)$ forum/$1 [R=301,L]
Comment: This was never answered.  Did you ever find a way to redirect to forum without ending up at www.example.com instead of just example.com?
Answer: Try this:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule ^(.*)$ http://example.com/$1 [R=301,QSA,L]

RewriteCond %{REQUEST_URI} !^/(wiki|blog|style|forum)
RewriteRule ^(.*)$ http://www.example.com/forum/$1 [R=301,QSA,L]

Comment: isn't there a way without specifying all the subdirectories?

I currently have only 4, but there will probably be more later...

Thanks for your answer!
Answer: I would use these rules:
# redirect www.example.com to example.com
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301]

# prefix everything but /forum/, /wiki/, /blog/, /style/ with /forum/ and rediret to it
RewriteRule !^(forum|wiki|blog|style)/ /forum%{REQUEST_URI} [L,R=301]

The second rule could additionally be replaced by this one to check the existence of the first path segment for every request.
# check if first segment of requested URI path is either missing
RewriteCond $0 ^$ [OR]
# or cannot be mapped to an existing directory
RewriteCond %{DOCUMENT_ROOT}$0/ !-d
RewriteRule ^[^/]* /forum%{REQUEST_URI} [L,R=301]

Answer: I'd say this should work.
RewriteEngine on
RewriteRule ^forum/(.*)$ forum/$1 [L]
RewriteRule ^wiki/(.*)$ wiki/$1 [L]
RewriteRule ^blog/(.*)$ blog/$1 [L]
RewriteRule ^style/(.*)$ style/$1 [L]

RewriteRule ^(.*)$ forum/$1 [L]

RewriteCond  %{HTTP_HOST}  ^www.example\.com$
RewriteRule ^(.*)$ http://example.com/$1

Answer: I don't have the answer for everything but for your www/no www problem you could try this :
# Enforce www
# If you have subdomains, you can add them to
# the list using the "|" (OR) regex operator
RewriteCond %{HTTP_HOST} !^(www|subdomain) [NC]
RewriteRule ^(.*)$ /exemple/$1 [L,R=301]

# Enforce NO www
RewriteCond %{HTTP_HOST} ^www [NC]
RewriteRule ^(.*)$ http://exemple.com/$1 [L,R=301]


Multiple comparisons when investigating consistency of a device

Question: I am trying to compare the performance of two devices designed to cool anaesthetised patients. This is a substudy analysis and the patient allocation between the groups is not even. Once cooling was started, they were cooled to 33 degrees before being re-warmed. Temperature measurements were taken once every hour. Both devices work on a negative feedback principle and I am investigating the device's ability to maintain patient temperature around the target temperature (33 degrees) for the set time period (28 hours). Below is plotted the mean time course of the groups of patients with the standard deviation. As demonstrated, the standard deviation is less for the IV33 group once cooling is established, although there were fewer patients in this group.

What I am trying to show is that there is a statistically significant difference in the variance once cooling is established. To do that I have applied Levene's Test to the results from each hour which give me the following results:
Hour - p value
00 - 0.8949
01 - 0.8954
02 - 0.2522
03 - 0.01618
04 - 0.03234
05 - 0.004928
06 - 0.000227
07 - 0.0001289
08 - 0.0002498
09 - 0.001403
10 - 0.001158
11 - 0.0001553
12 - 0.01084
13 - 0.0003181
14 - 0.001402
15 - 0.005558
16 - 0.01849
17 - 0.001601
18 - 0.003469
19 - 0.01291
20 - 0.02297
21 - 0.09245
22 - 0.02421
23 - 0.03829
24 - 0.03653
25 - 0.05466
26 - 0.1282
27 - 0.1982
28 - 0.3297

As you can see, these correlate well with the graph, starting to become significant as soon as cooling takes effect. However, I am obviously applying the same test multiple times. Using a standard Bonferroni correction I would need to use a p value of around 0.0014 (36 hours) which I think is overly conservative as Bonferroni aims at some negative correlation-type dependence whereas my results are rather positively correlated.
Is this correct and if so, how can I calculate a more appropriate p value that takes into account the multiple testing?
Comment: This is a cool example where a test for equality of variances is really needed.
Answer: You can take a Westfall-Young type approach. Estimate the correlation matrices R1 and R2 of each group. Then draw some 10000 (normally distributed, if you believe in it) random samples with these correlation matrices similar to your original data; just if they were under $H_0$, so equal variances but estimated covariances.  Calculate each time all the 36 Levene tests. Save the minimum $p$-values of all tests. At the end, take a empirical $\alpha$ quantile of your 10000 minimum $p$-values. This is the local $\alpha$ that controls the FWER. It will be somewhere between $\frac{\alpha}{36}$ and $\alpha$.
Some brief (untested) R-code to illustrate it:

library(mvtnorm)
library(lawstat)
for (i in 1:10000){
  x1 <- rmvnorm(n1,sigma=R1)
  x2 <- rmvnorm(n2,sigma=R2)
  for (j in 1:36){
    pvali[j] <- levene.test(rbind(x1[,j],x2[,j]),
          as.factor(rep(1,n1),rep(2,n2)))$p.value
  }
  minpval[i] <- min(pvali)
}
localalpha <- quantile(minpval,probs=alpha)

Answer: First of all, you actually do achieve your Bonferroni p-value, so this correction won't prevent you from declaring significance.
As an alternative, consider examining your data for time periods 8 - 20 only. It looks like the mean of both devices are essentially the same there, and there appears to be limited skewness, so we an assume that the distribution of body temperatures during this time period are stationary and have approximately the same median temperature value.
Therefore, we can focus a test on the differences in scale. I would recommend applying the Ansari-Bradley test of differences in scale to the data from time periods 8 - 20. You can perform a two-tailed hypothesis test. The R-code I linked to also gives you a confidence interval for the ratio of the variances, so you can see how practically significant things are.


Como obter a data max() e min() no SQL?

Question: Como posso obter a data mínima e máxima de uma tabela?
Estou usando as funções min() e max(), mas não está retornando o valor esperado. Esse é um pequeno exemplo dos dados de data da minha tabela:
CREATE TABLE Dados_Vendas
    ([Data] varchar(29))
;

INSERT INTO Dados_Vendas
    ([Data])
VALUES
    ('2016-12-02 00:00:00'),
    ('2016/07/16 00:00:00.000000000')
;

Se eu tentar puxar o min() e max() de data dessa tabela, usando as conversões:
SELECT
    MIN(CONVERT(DATE, LEFT(Data, 10), 103)) AS Data_Minima
    , MAX(CONVERT(DATE, LEFT(Data, 10), 103)) AS Data_Maxima
FROM Dados_Vendas
;

Obtenho como retorno um erro: "Conversion failed when converting date and/or time from character string."
Comment: Se o campo é varchar, o resultado é ordem alfabética e a solução é consertar a base de dados. Se tiver mais algum complemento além desse, você pode [edit] sua pergunta fornecendo um [mcve] do problema (com descrição das estruturas). Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Comment: Qual o tipo de dado de seu campo `Data`?
Comment: Utilize a função `CONVERT` para converter seu campo para o tipo DATETIME. Provavelmente a string que representa sua maior data tem ou dia menor que 31 ou mês menor que 12. A ordenação de string é diferente da ordenação de um DATETIME.
Comment: Está como varchar.
Comment: @Bacco editei a pergunta com um exemplo pequeno da base. Se estiver errado, deleto a pergunta.
Answer: O resultado vem errado por causa do tipo de campo. Você deveria usar date ou datetime em vez de varchar.
Ele traz o 31/12/2015 como valor máximo pois o 3 é maior valor. Ele ordena o texto assim: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Acredito que isto pode ser algum sistema legado. Para trazer os valores corretos utilize o SQL abaixo, aonde eu transformo o campo para datetime pelo comando convert(datetime, data, 103), aonde o 103 informa o tipo de formatação do campo (Referência do comando convert), e depois converto novamente para texto para apresentar no padrão dd/mm/yyyy.
select
  min(data),
  convert(varchar(10), min(convert(datetime, data, 103)), 103),
  max(data),
  convert(varchar(10), max(convert(datetime, data, 103)), 103)
from
  Dados_Compras

Ele está disponível em http://sqlfiddle.com/#!18/c8d0f/3
Edição da resposta em 04/08/2020 as 22:39
Conforme comentário do usuário da pergunta, está ocorrendo o erro Conversion failed when converting date and/or time from character string, isto deve estar ocorrendo pois deve ter data inválida (com dia 31 em mês que somente tem 30 dias, mês acima de 12 e outras formatações). Isto ocorre por causa da utilização do tipo de campo inadequado para data, como já falei na minha resposta.
Para encontrar o registros com erro, rode o  SQL abaixo. Também atualizei o exemplo. Novo link Resposta atualizada no SQL Fiddle
select
  *
from
  Dados_Compras
where
  try_convert(datetime, data, 103) is null

Comment: @Alineat atualizei a resposta e atualizei o exemplo no sql fiddle.
Comment: Eu tentei converter o tipo de dado, mas ele retorna um erro "Conversion failed when converting date and/or time from character string."
Answer: Converta o campo para o tipo DATE:
SELECT
    MIN(CONVERT(DATE, LEFT(Data, 10), 103)) AS Data_Minima,
    MAX(CONVERT(DATE, LEFT(Data, 10), 103)) AS Data_Maxima
FROM Dados_Compras

Comment: Tente utilizar o LEFT para pegar apenas os caracteres da data sem considerar o horário: LEFT(Data, 10), alterei na resposta para você testar.
Comment: Se usa o tipo errado e coisas banais ficam complicadas...
Comment: Eu tentei isso, mas ele retorna um erro: "Conversion failed when converting date and/or time from character string."
Comment: Eu tentei com o LEFT e retorna o mesmo erro "Conversion failed when converting date and/or time from character string."

Como obter a data max() e min() no SQL?


CSS not displayed on GitHub Pages?

Question: I need help regarding a mini project I'm working on. It's a simple site and it does not do any much yet. But when I push it on Git, CSS seemed to be not working.
Link: https://chxrain.github.io/Mini-School/
I tried changing the href link to the ff and it still doesn't work:
./css/style.css
../css/style.css
./Mini-School/css/style.css
../Mini-School/css/style.css
/css/style.css
/Mini-School/css/style.css
\css\style.css
Big thanks to those who can help!
Comment: Did you try to just use `css/style.css`?
Comment: yes, it's currently on css/style.css
Comment: Your website works fine, just press Ctrl+F5 to hard refresh.
Comment: Yes, your website worked really fine.
Answer:
This is the true link of the logo
Comment: and for all img too
Comment: yes thank you. I'll fix them all. I got too focus on changing the CSS href link when in fact, linking the images on all pages should be fixed as well.
Answer: Update:
For internal linking of files, the proper way of calling it will be:
/RepositoryName/folder/image.jpg
In my case, it is /Mini-School/media/image.jpg (which is inside the media folder)
CSS link remains as css/style.css (which is inside the css folder)
Answer: make sure that your local modification or your css is pushed into git
Comment: the true link for the logo is
../Mini-School/media/logo.png
Comment: I'm still about to review your code, I'll send it to you later
Comment: @ANDOAndriamalala, it's working fine now. Sorry there was a typo from NOT to NOW. It also works without the 2 dots. Thanks again
Comment: Yes, it's the first commit after modifying all files
Comment: can you send the complete link of the page
Comment: This(answer) should be a comment, not an answer
Comment: @ANDOAndriamalala, yes it's https://chxrain.github.io/Mini-School/
Comment: @ANDOAndriamalala, I tried without the two dots and is not working. Thank you!
Comment: for me it's work by removing / before media in all html pages

CSS not displayed on GitHub Pages?


Drupal GPL Questions

Question: I'm planning a new project that will require a great deal of custom code that must remain proprietary to my client. I found the licensing FAQ http://drupal.org/licensing/faq to be unclear.  I know this is primarily a coder as opposed to legal Q&A forum, but hopefully some experienced Drupal developers can shed more light on this issue.

What constitutes distribution?  For example, if the code is used on two unique domains owned by the same client, is that considered distribution?  Page 533, Chapter 24 of The Definitive Guide to Drupal 7 states "Modules built for ourselves or a single client are not considered distributed", but that isn't very clear.
If a module has been distributed and you have a copy, are you obligated to give me a copy, or is it up to you?  (In other words, could I demand a copy from you?)
If custom javascript is called from a Drupal javascript object (such as Drupal.behaviors), is it considered GPL'd and distributed?  The licensing FAQ Answer #7 states "Drupal's JavaScript, including the copy of jQuery that is included with Drupal, is itself under the GPL as well, so any Javascript that interacts with Drupal's JavaScript in the browser must also be under the GPL or a GPL compatible license."  That's a major non-starter for this particular project.  The client obviously doesn't want competitors walking off with highly specialized javascript that took months to develop with no legal recourse.
What is the legal status of modules that are not for distribution?  Are they license-free, or are they automatically GPL'd even if not intended for distribution?  For practical purposes, in a module that is not for distribution, would the following language have any legal effect:  "This module is copyright Company XXX and is not intended for distribution.  This software is not licensed and you may not use this module for your own purposes."

Apologies if these questions aren't as precise as they could be; I'm obviously not a lawyer.  I really want to use Drupal for this project, but if I can't offer an assurance to the client that the custom code (module code and javascript) will remain proprietary it's a non-starter.
Answer: (Disclamer: As usual with legal questions, I am not a lawyer, only a lawyer can give you a definitive answer).
Every Drupal module that is written and every javascript code that directly interacts with Drupal (or any other GPL code, but note that jQuery is dual-licensed and also available under the MIT License, this is not relevant when used with Drupal, though), automatically falls under the GPL. That's why GPL is also called a viral license. Everything it "touches" is GPL'ed automatically.
If you give the source code to someone, then he has every right the GPL grants him, including giving the source code to anyone he wants to, modify it and so on. However, viewing a website alone does not distribute your PHP code. JavaScript is a tricky question, see for example https://softwareengineering.stackexchange.com/questions/125955/using-gpl-licensed-jquery-scripts-on-website-with-ads and http://www.gnu.org/philosophy/javascript-trap.html. As far as I understand these, you always distribute the JS code.
So, obfuscating the JavaScript without providing a way to get the unmodified source code or adding a statement like the one you suggested above is in fact a direct violation of the GPL and someone could attempt to sue you.
Also note that there is an extended version of the GPL, the Affero General Public License, which explicitly includes viewing of a website as distribution. CiviCRM for example uses that license, so if you are required to allow visitors access to your custom adjustments/extensions of your website, when using a software like that.
Given the way the Ajax system in Drupal works, most relevant things usually happen on the server side, so that is usually not a big problem. Also, most GPL related lawsuits are usually related to companies selling products which run GPL software (e.g. routers) which don't provide access to their customized source code. I've never heard of a lawsuit against a website violating the GPL, but that could just be ignorance on my side, don't count on that ;)
Comment: I'd love to have your brain for a day...oh the things I'd know! :)
Comment: Thank you Berdir.  Would it be safe to say that any php code interacting with Drupal used within a single company (possibly across multiple domains) is not considered distributed?  Also, re: my original question #2, is a company obligated to release the source code of a custom Drupal module that is not distributed if requested to do so?
Comment: Exactly, that's not distributed publicly, so you don't need to release the source code to the public. If you give the code to your client, then he can re-distribute it, of course, but that's probably not in his interest :)

Drupal GPL Questions


Erro System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ao fazer update com entity

Question: Bom dia.
Estou precisando fazer um update via entity e ele me acusa o seguinte erro:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.

código do controller
 // GET: AreaClientes/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Protocolo protocloLatam = db.Protocolos.Find(id);
            if (protocloLatam == null)
            {
                return HttpNotFound();
            }
            PopulaTipo(protocloLatam.Id);
            PopulaArea(protocloLatam.Id);
            PopulaClassificacao(protocloLatam.Id);
            PopulaAtividade(protocloLatam.Id);
            PopulaCidades(protocloLatam.Id);
            PopulaDestinatarios(protocloLatam.Id);

            // ViewBag.GAreaClienteId = new SelectList(db.GAreaClientes, "Id", "Descricao", areaCliente.GAreaClienteId);
            return PartialView(protocloLatam);
        }
[WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult Editar() //[Bind(Include = "Id,Area,GAreaClienteId")]
        {
            if (ModelState.IsValid)
            {
                Protocolo protocolo = new Protocolo();
                protocolo.ColaboradorId = int.Parse(Request.QueryString["IdColaborador"]);
                protocolo.DestinatarioId = int.Parse(Request.QueryString["DestinatarioId"]);
                protocolo.OrigemId = int.Parse(Request.QueryString["OrigemId"]);
                protocolo.ClassificacaoId = int.Parse(Request.QueryString["ClassificacaoId"]);
                protocolo.ContaContabilId = int.Parse(Request.QueryString["ContaContabilId"]);
                protocolo.AcaoSolicitaId = int.Parse(Request.QueryString["AcaoSolicitaId"]);

                db.Entry(protocolo).State = EntityState.Modified;
                db.SaveChanges();

                return Json(new { resultado = true});
            }
            else
            {
                IEnumerable<ModelError> erros = ModelState.Values.SelectMany(item => item.Errors);

                return Json(new { resultado = false, mensagem = erros });
            }
        }

código do ajax que dispara a função
$("#btnEditar").on('click', function () {
    var erros = 0;
    $("div").find('*').each(function () {
        var classe = $(this).attr("class");
        if (classe !== undefined) {
            var numItems = $('.has-error').length;
            if (numItems > 0) {
                return false;
            }
            else {

                $.ajax({
                    type: 'GET',
                    url: 'ProtocoloLatam/Editar',
                    dataType: 'JSON',

                    data: {
                        IdColaborador: $("#lblColaborador").attr("data-idColaborador"),
                        DestinatarioId: $("#ColaboradorId").val(),
                        OrigemId: $("#OrigemId").val(),
                        ClassificacaoId: $("#ClassificacaoId").val(),
                        ContaContabilId: $("#ContaContabilId").val(),
                        AcaoSolicitaId: $("#AcaoSolicitaId").val(),
                    }, success: function (data) {

                        $("#minhaModal").modal('hide');

                    }
                }).done(function () {
                    toastr.success("Editado com sucesso.");
                    setTimeout(4000);
                    window.location.reload();
                });
                return false;

            }
        }

    });
});

Comment: @MarconcilioSouza HAHAHAHAHA acertou, vi isso aqui e funcionou kk
Comment: o que tem no objeto db.Entry(protocolo) => protocolo é da mesma chave que você recuperou ? o objeto ainda esta no próxis do EF ? se não esta você tem que attach ele antes
Comment: Notei que realmente precisava passar o id dele... agora está dando erro de conversão de datetime2 para datetime.
Comment: nem vou falar que você não esta passando a data e ele esta mandando 1901/01/01 hsuahsau
Answer: Seu problema é que você recuperar o objeto com o Entity FrameWork, mas quando você esta devolvendo ele não informa a chave primaria do objeto.
  db.Entry(protocolo).State = EntityState.Modified;

Lembrando também que para você fazer o código acima o objeto ainda tem que esta mapeado no EF no próxis, então o mais indicado seria você olhar para o contexto local e verificar se ele já existe.
var localProtocolo = Contexto.Set<Protocolos>().Local.FirstOrDefault(x => x.Codigo == protocolo.Codigo);
if (localProtocolo != null)
{
    localProtocolo = protocolo;
}

Veja o exemplo


Cálculos em PHP

Question: Estou começando em PHP e tenho a seguinte situação. Tenho um valor, resgatado de um banco, e seis botões com os seguintes valores: +100, +200, +300, +400, +500 e +600. Como faço para ao clicar em um destes botões, seja feito a soma do valor escolhido através dos botões com o valor resgatado em banco?
Exemplo: Eu clico no botão +500 e o valor resgatado na base é 1.000. O sistema faz a soma e salva o total.
Comment: Onde é exatamente a sua dúvida? O que você já tentou fazer?
Answer: Você terá que fazer algo mais ou menos assim.
<?php

            /*
                aqui esta a parte server-side do seu codigo esta será executada no servidor cada
               vez que o usuário submeter a pagina.
            */

            // abra sua conexão
        if(isset($_POST["acao"])&&$_POST["acao"] == "update"){// e verifique qual ação a se fazer
            $valor = $_POST["valor"];
            $update = mysql_query("UPDATE AlgumaTabela SET Valor = '".$valor."' WHERE id=X ");
        }

        // selecione o valor a resgatar do banco de dados
        $select = mysql_query("SELECT Valor FROM AlgumaTabela WHERE id=X ");
        $valor = 0;
        if($row = mysql_fetch_assoc($select)){
            $valor = $row["valor"];
         }
?>

  <form action="/" method="post" id="myform">
    <input type='hidden' name="acao" value="update">
    <input type='hidden' name="valor" id="valor"  value="<?php print $valor ?>" >

    <input type="button" onclick="send(this)" value="100">
      <input type="button" onclick="send(this)" value="200">
        <input type="button" onclick="send(this)" value="300">
          <input type="button" onclick="send(this)" value="400">
            <input type="button" onclick="send(this)" value="500">
              <input type="button" onclick="send(this)" value="600">

  </form>

Comment: Vinicius, o legal é explicar o *porquê* (neste caso, server-side e client-side)... aquela história de dar um peixe ou ensinar a pescar ;)
Comment: Tem razão @brasofilo fiz na pressa mas vou detalhar :)
Comment: Se possível @Tuyoshi já ensina fazendo uso do PDO pq o mysql_* está depreciado.
Answer: Você resgata o valor do banco de dados e salva em uma variável, soma o valor do botão com o da variável e faz o update.
ao clicar no botão +500:
valor_botao = 500
valor_banco = query("consulta valor no bd")
valor_total = valor_banco + valor_botao
update("valor = valor_total")

Se isso não responde sua duvida, tente detalhar.

Cálculos em PHP


Why does my JSONP request give me Uncaught SyntaxError: Unexpected token < (less than)?

Question: Following is my xmlfile
applica.luminoustec.net/file.xml

I need to access with this ajax call from my local host, all about is cross domain call
My AJAX CODE

following is the error
Uncaught SyntaxError: Unexpected token <
can anyone tell where i am at fault
i see this link
 and this link
but not succeded please help me out
Comment: You'll have to make up your mind—XML or JSONP?
Answer: http://applica.luminoustec.net/file.xml is XML.
dataType: "jsonp", tells jQuery to parse it as JSONP.
XML is not JSONP. Thus, it errors.
Either:

Change the URL to one which returns JSONP or
Remove the dataType line and let jQuery detect it as XML (NB: This will probably require that you set up CORS support on the server).
Comment: I attempt with 2 option , now error is

 XMLHttpRequest cannot load http://applica.luminoustec.net/file.xml. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:22791' is therefore not allowed access.
Comment: @jot yes, that is a CORS error. You have to set up CORS to do #2.
Comment: how to manage with that any idea or helpful link @GeorgeStocker
Comment: @Jot instructions for setting up CORS on various server environments http://enable-cors.org/server.html ... I think you'll want http://enable-cors.org/server_aspnet.html
Comment: @Jot — There's a link in the answer.
Comment: can i do this CORS adding in the plan asp.net or i have to choose asp.net MVC
Comment: if you have a relevent link that can help quicker please provide me
Comment: any example to do so please
Comment: @Jot Setting it up in ASP.NET MVC for development is covered here: http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method


meteorjs when running on android-device im getting this error

Question: I am trying to develop an app from meteor.js. I am able to compile and run on Apple devices. But when I try to run on android (meteor run android-device) I get the below error message from terminal. I have tried googling the issue but still could not get a fix!.

Status of the individual requirements:
✓ Java JDK
✓ Android SDK
✗ Android target: avdmanager: Command failed with exit code 1 Error output:
  Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
  at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
  at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
  at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
  at com.android.sdklib.tool.AvdManagerCli.run(AvdManagerCli.java:213)
  at com.android.sdklib.tool.AvdManagerCli.main(AvdManagerCli.java:200)
  Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
  at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
  at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
  at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
  ... 5 more
✓ Gradle
Comment: i had to install the correct version of android studio with its tools. its fixed. thanks
Comment: @SamaahRasheed please describe how you solved it in an _answer_ to your question, so that people who might face the same issue as you in the future can solve it quicker.
Comment: Does https://github.com/meteor/meteor/issues/9510 help?
Answer: This is what I did:
meteor remove-platform android

As mentioned by @SamaahRasheed I then went to Android Studio and updated it:

Android Studio > Check for updates

and then also updated everything else Android Studio then recommended I update as well.
Then I made sure JAVA_HOME was at least java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home

Then I re-added android platform:
meteor add-platform android

It may be that one of these was more important than the others, but this worked.


MS SQL Server 2012 Auto-Increment & Primary/Foreign Keys

Question: I'm trying to see if the Primary/Foreign keys can be used in the following way in MS SQL server 2012.
If I have two tables one with employer information and one with recruiter information.
If any given employer can have up to 5 recruiter accounts, then in my table each time a new recruiter account is created with the employer's PK ID in a matching column on the Recruiters table and have a matching field on the recruiters table that has a count of the # of recruiter accounts that exist in the recruiters table.
So
Employers Table = A
EmployerID  int Unchecked
UserID  int Checked
AccountStatus   varchar(50) Checked
CompanyName varchar(150)    Checked
JobsPosted  int Checked
ResumeViews int Checked
ResumeFavorites int Checked
Recruiters  int Checked

Recruiters Table = B
RecruiterID int Unchecked
EmployerID  int Checked
UserID  int Checked
AccountStatus   varchar(50) Checked
JobsPosted  int Checked
ResumeViews int Checked
ResumeFavorites int Checked

For each Recruiter that exists in table B auto-increment the value in Table A's Recruiters field.
Is that proper use of primary/foreign keys? Or should I be using TSQL to accomplish this?
Answer: I think you are missing the point of normalizing your database.
Let your employer data in the Employee  and Recruiter data in the Recruiter and a EmployerRecruiterAccount table where 1 employer can have 5 recruiters.
So your EmployerRecruiterAccount will have EmployeeID and RecruiterID as foreign keys.
Comment: so PK&FK relationships are simply so 1 does not have to repeat in my example `EmployerID` in both tables?
Comment: EMPID and RecruiterID will repeat in your EmployerRecruiterTable and will be controlled by an autoincrement primary key.
Comment: EMPloyerTable will not repeat EMPID , RecruiterTable will not repeat RecruiterID these are you PKs.


Removing Checked checkbox elements using a function

Question: Trying to make a to-do list using JavaScript but can't seem to figure out a way to delete the checked checkboxes.
I tried to have the program change the id then delete everything with that new id but that didn't seem to work, maybe I was missing something important not sure but if any of you know a different way of deleting checked checkboxes, I'd appreciate the help.

function add() {
   var myDiv = document.getElementById("myDiv");

   var inputValue = document.getElementById("myInput").value;

   // creating checkbox element
   var checkbox = document.createElement('input');

   if (inputValue === '') {
      alert("Input is Empty!");
   } else {
      document.getElementById("myUL").appendChild(checkbox);
   }

   // Assigning the attributes to created checkbox
   checkbox.type = "checkbox";
   checkbox.name = "name";
   checkbox.value = "value";
   checkbox.id = "checkBox";

   // create label for checkbox
   var label = document.createElement('label');

   // assigning attributes for the created label tag
   label.htmlFor = "checkBox";

   // appending the created text to the created label tag
   label.appendChild(document.createTextNode(inputValue));

   // appending the checkbox and label to div
   myDiv.appendChild(checkbox);
   myDiv.appendChild(label);

}

function remove() {
   var doc = document.getElementById("checkBox").checked;
   doc.remove;
}

To Do List

  <input type="text" id="myInput">

  <button onclick='add()'>Click me!</button>
  <button onclick="remove()">Delete</button>

Comment: How about add a class for the checked checkbox. Use css to hide the checkboxes with the class set?
Comment: Or you can attach a handler on the checkbox and hide it when it gets checked.
Comment: `checkbox.id = "checkBox";` should be unique
Comment: The problem is with this line. var doc = document.getElementById("checkBox").checked; This will not return a dom element. Assign unique Ids to the checkbox and then get the reference to the checkbox by using var doc = document.getElementById("checkBox"); Remove doc after this.
Answer: I think you should restructure your html. Create a separate function createItem() which
returns a
 containing <input> and text. Give a specific className to container div.
Inside remove() you querySelectorAll() to get all items. And use forEach() to loop through items and check if the input of item is checked then remove() it
Note: id of the element in whole document should be unique

function createItem(text){
  const container = document.createElement('div');
  container.className = 'item'
  container.innerHTML = `<input type="checkbox" /><span>${text}</span>`
  return container;
}

function add() {
   var myDiv = document.getElementById("myDiv");

   var inputValue = document.getElementById("myInput").value;

   // creating checkbox element
   var checkbox = document.createElement('input');
   if (inputValue === '') {
      alert("Input is Empty!");
   } else {
      document.getElementById("myUL").appendChild(createItem(inputValue));
   }
}

function remove() {
   var doc = document.querySelectorAll('.item');
   doc.forEach(x => {
    if(x.querySelector('input').checked){
      x.remove()
    }
   })
}

To Do List

  <input type="text" id="myInput">

  <button onclick='add()'>Click me!</button>
  <button onclick="remove()">Delete</button>

Answer: There are several issues to your code:

You are recycling the #checkBox ID. Remember that IDs must be unique within a document. Therefore, you should be generating a unique ID for each label + checkbox pair
You are only removing the checkbox element and not the label text, so even if your logic works, the appearance / outcome of your code is not what you want.

A solution will be wrapping your label text and the checkbox element inside the label. The advantages of this is that:

The  element does not need a for attribute, since clicking on the label will automatically check the nested checkbox
You can use .closest('label') to remove the entire label text + checkbox pair, when you hit the delete button

In order to iterate through all the checked checkboxes, you can simply run this selector: document.querySelector('.checkbox:checked'). To iterate through this Node collection, you can use Array.prototype.forEach().
Another note: you might want to return from the function if there an empty text is provided when a user wants to add a textbox.
See proof-of-concept example below:

function add() {
   var myDiv = document.getElementById("myDiv");

   var inputValue = document.getElementById("myInput").value;

   // creating checkbox element
   var checkbox = document.createElement('input');

   if (inputValue === '') {
      alert("Input is Empty!");
      return;
   } else {
      document.getElementById("myUL").appendChild(checkbox);
   }

   // Assigning the attributes to created checkbox
   checkbox.type = "checkbox";
   checkbox.name = "name";
   checkbox.value = "value";
   checkbox.classList.add("checkbox");

   // create label for checkbox
   var label = document.createElement('label');

   // appending the checkbox and created text to the created label tag
   label.appendChild(checkbox);
   label.appendChild(document.createTextNode(inputValue));

   // appending label to div
   myDiv.appendChild(label);

}

function remove() {
   const checkboxes = document.querySelectorAll('.checkbox:checked');
   Array.prototype.forEach.call(checkboxes, function(checkbox) {
    checkbox.closest('label').remove();
   });
}

To Do List

  <input type="text" id="myInput">

  <button onclick='add()'>Click me!</button>
  <button onclick="remove()">Delete</button>

Answer: Use a query:

function removeCheckedCheckboxes() {
    const query = document.querySelectorAll('[type="checkbox"]:checked');

    Array.from(query).forEach(element =>
        element.remove()
    );
}

    <input type="checkbox">

    <input type="checkbox">

    <input type="checkbox">

    <input type="checkbox">

    <input type="checkbox">

    <input type="checkbox">

  <button onclick="removeCheckedCheckboxes()">
    Remove checked checkboxes
  </button>


How to get image titles and source out of a view?

Question: I'm struggling hard to understand how drupal views work. With views i assembled a new front page which takes images from certain content types.
Now i'm writing a module to get the image data out of the view.
My Problem:
where can I find the images: when i write
views_get_view('viewsname');

I get an array of values but not the images.
How can i get the images out of the view properly?
Comment: this is a pretty in-depth question, but basically, if you do something along the lines of `$view=views_get_view('viewsname');` and then execute the view, $view->result will be an array of objects relating to each row.  There, there "should" be a `$view->result[#]->fid` which is the file id, and is an index into the files table and there you will find the file name and path etc of those images.  You can also look into the `views_get_view_result()` function which is a nice wrapper for getting just results from a view.
Comment: @Jimajamma views_get_view_result() made my day! Holy... Why do you guys know about that function? Thanks a lot. Please submit the answer!
Answer: If you are wanting to get Views results to use programmatically, check out the views_get_view_result() function.  If you do something like:
$result=views_get_view_result('viewname');

you can then loop through $result, which is an array of objects relating to each row, and the tried and true:
drupal_set_message('
' . print_r($result, TRUE) . '
');

will give you all the information you are working with.


Let $a_n = n^n$. For all $n \in \Bbb N$, show that

Question: Let $a_n = n^n$. For all $n \in \Bbb N$, show that

There exists some $k \in \Bbb N$ such that for each $n \in \Bbb N$ we have: $a_{n+k} \equiv a_n \pmod m$ where $m \gt 1$ is a square-free integer.
Find the minimum $k$, as a  function of $m$ that satisfies the above congruence. ($a_{n+k} \equiv a_n \pmod m$)
Answer: By the Chinese Remainder Theorem, we can study the congruence modulo $p$, where $p$ is a prime dividing $m$. Therefore you can assume $k$ satisfies
$$
(n+k)^{n+k} \equiv n^n \pmod p
$$
for every $n \in \mathbb N$. In particular,
$$
(p+k)^{p+k} \equiv p^p \equiv 0 \pmod p,
$$
which leaves the only possibility $k \equiv 0 \pmod p$. Write $k = \ell p$. Then the conditions on $k$ becomes
$$
(n + \ell p)^{n + \ell p} \equiv n^{n + \ell p} \equiv n^n \pmod p
$$
if and only if, by Fermat's theorem,
$$
n^{\ell} \equiv n^{\ell p} \equiv 1 \pmod p.
$$
This implies $\ell \equiv 0 \pmod {p-1}$. Now suppose $k = p(p-1)m$, hence
$$
(n+p(p-1)m)^{n + p(p-1)m} \equiv n^{n+p(p-1)m} \equiv n^n \pmod p,
$$
so that $k$ satisfies the constraints. Therefore the $k$ that satisfy the desired properties are the multiples of $p(p-1)$ and the minimal one is clearly $p(p-1)$.
Going back to $m$, since we must have $m \equiv 0 \pmod {p(p-1)}$ for every prime $p$ dividing $m$, the minimal $k$ you are looking for is
$$
k = \underset{p | m}{\mathrm{LCM}} \{ p(p-1) \}.
$$
Hope that helps,
Comment: Good, may I ask you what does $\underset{p | m}{\mathrm{ppcm}} \{ p(p-1) \}$ mean here? Is it some sort of notation?
Comment: It's the least common multiple of the numbers $p(p-1)$ where $p$ divides $m$. Since we must have $p(p-1)$ dividing $m$ for all primes dividing $m$, to get the least number $k$ that satisfies all of these conditions at the same time, you must take the least common multiple of them. I'm sorry, I just noticed the notation ppcm ("Plus Petit Commun Multiple") is french, that's probably why you didn't understand. I'll fix that.


Find the points closest to two lines using least squares method

Question: Given are two lines $g(t)=a+bt$ and $h(s)=c+ds$ with $a,b,c,d \in \mathbb R^3$. I need to find the points where the two lines are closest using the least squares method. However I am unable to find a solution for this problem.
Intuitively those points are where $g(t)-h(s)$ is as small as possible, but I don't know how to translate this into my understanding of a least squares problem. In my understanding what the least squares method does is it fits a line as close as possible to a set of given points. However given two lines this set of points seems to be infinite and therefore I don't know what that line should be. I think where I am stuck is that my understanding of the least squares method is too specific and limited to fitting straight lines.
Comment: What's wrong with minimizing $\|g(t)-h(s)\|^2$ as a function of $s,t$, using calculus?
Comment: The question specifically asks for a solution using least squares. Plus even if a solution using calculus would be allowed, now I want to know how to do it using least squares.
Comment: Isn't minimizing squared difference of two functions the least squares method itself? In other words, why don't my answer fit? Thanks.
Comment: Echoing @AlexeyBurdin: "least" and "minimizing" are pals, and $\|g(t)-f(s)\|^2$ is "squares".  "Solving the normal equations" is calculus.   Put another way: what do you think "least squares" is, anyway?
Comment: Fine, you're right, the [wiki](https://en.wikipedia.org/wiki/Least_squares) agrees with you.
Comment: @kimchilover I used to think this kind of problem was inextricably tied up with Calculus, until I taught Linear Algebra for the first time, and realized there is an entirely Calculus-free way of thinking about it that relies on thinking about the geometry of the parameter space and projecting onto a specific subspace.  See my answer for details. Since the question is tagged linear-algebra I assume that is the method the OP needs to use.
Comment: @mweiss Yes. Translated into Kimchi-speak, you are saying the line  connecting the 2 closest points is perpendicular to both the original lines, which can be seen by using complete-the-squares arguments encoding Pythagoras's theorem, without calculus.  I agree.  This is a non-calculus way of reaching the normal equations.
Answer: As you say, you're looking for a point where $g(t) - h(s)$ is as small as possible. Let's unpack what that means.
If the two lines actually crossed, we would be looking for a point where
$$bt - ds + (a-c) = 0$$
This can be written in the equivalent form as the matrix equation
$$\begin{bmatrix} b & -d \end{bmatrix} \begin{bmatrix} t \\ s \end{bmatrix} = c - a$$
If we introduce the notation $A = \begin{bmatrix} b & -d \end{bmatrix}$, $\vec{x} = \begin{bmatrix} t \\ s \end{bmatrix}$, $\vec{b_0} = \begin{bmatrix} c - a \end{bmatrix}$, you want to solve
$$A \vec{x} = \vec{b_0}$$
But this equation doesn't have any solutions, because the lines don't actually cross.  Another way of expressing this fact is that $\vec{b_0}$ is not in $\operatorname{im} A$.
This is where least-squares suddenly kicks in.  Since $\vec{b_0}$ is not in $\operatorname{im} A$, we find the point $\vec{b^*}$ that is in $\operatorname{im} A$ and is as close to $\vec{b_0}$ as possible.  This point can be found by projection onto $\operatorname{im} A$:
$$\vec{b^*} = \operatorname{proj}_{\operatorname{im} A} \vec{b_0}$$
Then we want to solve the least-squares equation
$$A \vec{x^*} = \operatorname{proj}_{\operatorname{im} A}\vec{b_0}$$
Can you take it from here?
Comment: @david No, I don't think so. With that setup the set of vectors $Ax$ would not be a subspace, and in particular would not be $\operatorname{im} A$, so the whole logic of the argument would break down.
Comment: If I had my $A=\begin{bmatrix} a & b & -c & -d\end{bmatrix}$, my $x=\begin{bmatrix} 1 \\ t \\ 1 \\ s \end{bmatrix}$ and my $b=0$ and project this $b$ instead, would that be correct also?
Comment: Hmm... I still don't quite get it then. With that setup the set of vectors $Ax$ would not be a subspace of what?
Comment: @david The set $\left\{A\vec{x} \vert \vec{x} = \left<1, t,  1 ,s \right>, s, t \in \mathbb R \right\}$ is a subset of $\mathbb R^4$, but it is not a subspace, because it does not contain the zero vector.
Comment: ahh and why does it need to be a subspace? thanks a lot for your clear explanations btw!
Comment: Do you know how to project onto a set that's not a subspace?  If so, great!  But projecting onto a subspace is conceptually simple: you find an orthonormal basis for the subspace, project onto each basis vector, and then sum the components.  If the set is not a subspace, then none of that works -- you don't have a basis to begin with, and it's not closed under sums, so the whole method fails.  1/2
Comment: In addition the usual way we teach least-squares (in a linear algebra course) is that you take the equation $$A\vec{x^*} = \operatorname{proj}_{\operatorname{im} A}\vec{b_0}$$ and manipulate it into the so-called "normal equation" $$A^T A \vec{x^*} = A^T \vec{b_0}$$ This relies on the fact that the set you project onto is $\operatorname{im} A$, which it can't be if it's not a subspace.  2/2
Answer: $$f(s,t)=(g(t)-h(s))^2$$
$$\begin{cases}
\frac{\partial f(s,t)}{\partial t}=2g'(t)(g(t)-h(s))=0\\
\frac{\partial f(s,t)}{\partial s}=-2h'(s)(g(t)-h(s))=0
\end{cases}$$
$$\begin{cases}
b(a-c+tb-sd)=0\\
d(a-c+tb-sd)=0
\end{cases}$$
$$\begin{pmatrix}
b^2&-bd\\bd&-d^2
\end{pmatrix}
\begin{pmatrix}
t\\s
\end{pmatrix}=
\begin{pmatrix}
b(c-a)\\d(c-a)
\end{pmatrix}$$
The linear system has one solution when $\det \begin{pmatrix}
b^2&-bd\\bd&-d^2
\end{pmatrix}=-(b^2d^2-(bd)^2)\ne 0$, i.e. when $b\not\parallel d$.
When $d=xb$ for some $x\in\mathbb{R}$ then the system becomes
$$b^2\begin{pmatrix}
1&-x\\x&-x^2
\end{pmatrix}
\begin{pmatrix}
t\\s
\end{pmatrix}=
\begin{pmatrix}
b(c-a)\\xb(c-a)
\end{pmatrix}$$
We see that the system is consistent and has solutions
$$t=\frac{b(c-a)}{b^2}+xs$$
for a free variable $s$.
Pluging values for $s,\,t$ back into $f$ we obtain the desired result.
Answer: Let $M=\pmatrix{b&-d}$. Then
$$
\|(a+bt)-(c+ds)\|^2=\left\|M\pmatrix{t\\ s}-(c-a)\right\|^2.
$$
Therefore, the least-norm least-square solution to the minimisation problem is given by
\begin{aligned}
\pmatrix{t\\ s}
&=M^+(c-a)\\
&=\begin{cases}
(M^TM)^{-1}M^T(c-a)&\text{if }\operatorname{rank}(M)=2,\\
\frac{1}{\operatorname{tr}(M^TM)}M^T(c-a)&\text{if }\operatorname{rank}(M)=1,\\
0&\text{if }M=0.\\
\end{cases}
\end{aligned}


Javascript passar mais de um parametro atraves do fetch

Question: No link abaixo, consegui como enviar um parametro atraves do fetch pelo body, mas preciso enviar mais de um, por exemplo, valores de um formulario.
Preciso de um exemplo, usando POST para enviar atraves do body, por exemplo:
id: 1234, nome: Teste, tipo: pagamento etc, algo assim.
Agradeço, ajuda.
Não estou conseguindo enviar um POST para o PHP pelo fetch do Javascript
fnConsultarDadosPost = () => {
    const nome = document.querySelector('#nome').value

    fetch('dados.php', {
        method: 'POST',
        body: nome,
        headers: {
            'Content-Type': 'plain/text'
        }
    })
        .then(res => res.text())
        .then(res => fnExibirResultado(res))
}

fnExibirResultado = (dados) => {
    document.querySelector('#mensagem').innerHTML = dados
}

Comment: Desculpe gostaria de acrescentar que estou tentando passar para uma pagina PHP.
Conseguindo passar os dados, como faço para recebe-los no PHP.
Obrigado.
Comment: edite sua pergunta e coloque essa informação lá ao invés de adicionar um comentário
Answer: Você pode criar um objeto com os valores e passar no body, assim por exemplo:
var dados = {
   id: 1234,
   nome: "Teste",
   tipo: "pagamento"
};

fetch('dados.php', {
    method: 'POST',
    body: JSON.stringify(dados),
    headers: {
        'Content-Type': 'application/json'
    }
})

O JSON.stringify vai serializar seu objeto com os dados e passar como parâmetro. Note que como está sendo passado um JSON, o header também deve ter esse valor.
Comment: Ricardo, como o AP está utilizando PHP, não seria melhor utilizar o _Content-Type_ `application/x-www-form-urlencoded` ao invés de `application/json`? Pergunto porque a superglobal `$_POST` já suporta _urlencoded_ nativamente, o que não acontece com o _json_... [Continuação desta pergunta?](https://pt.stackoverflow.com/questions/494083/como-pegar-valores-de-um-objeto-passado-pelo-fetch-pelo-php#comment917968_494083)
Comment: olá Luis. Sim seria possível, mas não do jeito que está na pergunta, passando um objeto, precisaria postar todo o form, por exemplo passando do `body` do `fetch` algo assim: `body: new FormData($(form))`, dessa forma iria receber o form e poderia sim ler os valores usando o `$_POST`. Se mudar o content passando um objeto json, deve dar um erro de *Bad Request*, mas precisaria fazer um teste para confirmar


samba not starting on ubuntu

Question: I have this output
 user123@Matrix-Server:~$ /etc/init.d/samba stop
    bash: /etc/init.d/samba: No such file or directory
    sputnik@Matrix-Server:~$ sudo /etc/init.d/samba restart
    sudo: /etc/init.d/samba: command not found
    user123@Matrix-Server:~$

 user123@Matrix-Server:~$ sudo apt-get install samba smbfs
    Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    samba is already the newest version.
    smbfs is already the newest version.
    The following packages were automatically installed and are no longer required:
      linux-headers-2.6.32-19-generic linux-headers-2.6.32-19
    Use 'apt-get autoremove' to remove them.
    0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

Answer: Samba is composed of two separated daemons:

smbd which provides the file and printer sharing services
nmbd which provides the NetBIOS-to-IP-address name service

to restart completely samba you need to restart both of them so the correct sequence of commands is
sudo /etc/init.d/smbd restart
sudo /etc/init.d/nmbd restart

or in a more "ubuntish" way
sudo service smbd restart
sudo service nmbd restart

Comment: Thanks. All the guides out there say to start/stop the "samba" service. I saw the smbd and nmbd but wasn't positive if those were what I needed ... are they new in this version or something?

On a related note, how would I check that?
Answer: sudo /etc/init.d/samba start

Try that or try
cd /etc/init.d/
sudo ./samba start

If that fails as well reinstall samba:
sudo apt-get install --reinstall samba

And then try restarting it.
Comment: I checked /etc/init.d directory and see smbd over there and it worked but not samba
Comment: strange. what version of ubuntu?
Answer: You can also run this on a single line
restart smbd && restart nmbd

If this won't work opt for Fen0x's suggestion.
Answer: update for who using Raspberry Pi

samba command not found

$ sudo /etc/init.d/samba restart
sudo: /etc/init.d/samba: command not found

find out the new service name of samba

$ ls -al /etc/init.d/ | grep -E "\ss"
-rwxr-xr-x   1 root root 2259 Aug  1  2022 samba-ad-dc
-rwxr-xr-x   1 root root 2224 Apr 15  2018 saned
-rwxr-xr-x   1 root root 2061 Aug  1  2022 smbd
-rwxr-xr-x   1 root root 4056 Jul  2  2022 ssh
-rwxr-xr-x   1 root root 1030 Jan 14  2023 sudo

restart smbd service

$ sudo /etc/init.d/smbd restart
Restarting smbd (via systemctl): smbd.service.

# OR
$ sudo systemctl restart smbd
# OR
$ sudo systemctl restart smbd.service

screenshot

refs
https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units

samba not starting on ubuntu


Get Nvarchar length in Database From Class

Question: I have Class use as Table in SQL server
Then properties below
[Column(Storage = "_new_name", DbType = "nvarchar (2000)")]
public string new_name { get { return _new_name; } set { _new_name = value; } }

So. Can I get Length From my Class using C#
In this case It's 2000
Thank
Comment: There is a markdown designed for code formatting. Please, use it.
Answer: You can't easily, without resorting to Reflection. Attributes are meta-data, so they only decorate code with additional information required for various processes. In your case, for your ORM to identify which property maps to which column.
Assuming you have a class like this:
public class TestTable
{
    private string _new_name;
    private string _address;

    [Column(Storage = "_new_name", DbType = "nvarchar (2000)")]
    public string new_name {
        get
        {
            return _new_name;
        }
        set
        {
            _new_name = value;
        }
    }

    [Column(Storage = "_address", DbType = "nvarchar (5000)")]
    public string address {
        get
        {
            return _address;
        }
        set
        {
            _address = value;
        }
    }
}

You can read the attribute values from the properties like this:
var properties = typeof(TestTable).GetProperties();

var attributesPerProperty = new Dictionary<string, string>();
foreach (var propertyInfo in properties)
{
    var attribute = System.Attribute.GetCustomAttributes(propertyInfo).FirstOrDefault();

    if(attribute is ColumnAttribute)
    {
        var columnAttribute = (ColumnAttribute)attribute;
        attributesPerProperty.Add(propertyInfo.Name, columnAttribute.DbType);
    }
}

It's not an ideal way of doing things, and I've just given a rough example but if you really, really need to read this kind of information from your classes, the above will get you there.


Converse to a proposition on homogeneous polynomials

Question: I know that for a homogeneous polynomial $P$, if $P(x_1, ... , x_n) = 0$, then $P(ax_1, ..., ax_n) = 0$ for every $a$ in the field of $P$. Is the converse of this proposition true? That is, if $P(x_1, ... , x_n) =0$ implies $P(ax_1, ..., ax_n) = 0$ for every $a$ in the field of $P$, is $P$ homogeneous?
Comment: I'd say this is essentially correct but you have to make some amends to deal with pathological cases like $x^2 + 1$ over $\mathbb{R}$. It is clearly not homogeneous, but since it has no zeroes every zero vacuously satisfies the condition that all its scalar multiples are also zeroes.
Comment: What about $P(x,y) = x^2 + y^4$ over $\mathbb R$? $x^2 + y^4 = 0$ implies that $x = y = 0$ and then clearly $P(ax,ay) = 0$ aswell but $P$ is not homogeneous. Maybe require that your field is algebraically closed or something? Just guessing. You would also need nonzero characteristic I think.
Answer: We are assuming that we are working on field of characteristic $0$.
Let $(x_1,x_2,\ldots,x_n)$ be a root of $P$. Then consider the one variable polynomial $Q(t)=P(tx_1,tx_2,\ldots,tx_n)$. Hence $Q(a)=0$ for any $a$ in the field implies all the coefficients of $Q$ are $0$. What are the coefficients of $Q$ ? Write $P(x_1,x_2,\ldots,x_n)$ as sum of monomials and proceed. I think it will work.
The coefficient of $X^d$ in $Q(X)$ is infact a homogeneous polynomial of degree $d$ in the variables $X_1,X_2,\ldots,X_n$.
$P(X_1,X_2,\ldots,X_n)$ can be represented as follows,
$$\sum_{j=1}^{m}a_jR_j(X_1,X_2,\ldots,X_n)$$
Where $m$ is the degree of $P$ and each $R_j$ is a homogeneous polynomial of degree $j$ with $R_j(x_1,x_2,\dots,x_n)=0$ for all $1\leq j\leq m$. Moreover $a_m\neq0$.
Comment: In that case your answer is very misleading, you don't say what you actually prove in your statement and what youre conclusion is.
Comment: $Q(a) = 0$ for all $a$ implying that the coefficients of $Q$ are zero is not true over a field with nonzero characteristic. Take $x - x^2$ over $\mathbb F_2$ for example.
Comment: Yeah. I actually meant here for field of characteristic $0$. Sorry I have missed it. Thanks
Comment: I don't see how this proves the statement, $P(x,y) = x^2 + y^4$ over $\mathbb R$ is a counterexample, it is only zero when $x = y = 0$ and then obviously $P(ax,ay) = 0$ aswell for all $a \in \mathbb R$.
Comment: @NoelLundstrom your polynomial is not a counter example. Because, we can write it as follows. $$P(x,y)=a_1R_1(x,y)+a_2R_2(x,y)+a_3R_3(x,y)+a_4R_4(x,y)$$ where $a_1=a_3=0$. $a_2=a_4=1$ and $R_2(x,y)=x^2$ is a homogeneous polynomial of degree 2; $R_4(x,y)=y^4$ is a homogeneous polynomial of degree 4.
Comment: A sum of homogeneous polynomials is not necessarily a homogeneous polynomial. All summands have to be of the same degree for that to happen. Look up the definition of a homogeneous polynomial. $x^2 + y^4$ is not homogeneous.
Comment: @NoelLundström I didn't prove that $P$ will be homogeneous. You please look at my solution. I found the general form of the polynomial $P$ satisfying the hypothesis. My proof indeed shows that $P$ must not necessarily be homogeneous.


Creating a room for a dungeon gives wrong dimensions/no walls

Question: I'm using Python 2.7 libtcod to make a Roguelike, and currently trying to get a function to create an individual room based on a given floor number, x1, x2, y1, and y2 set of coordinates. The expected behavior is that I should get a room bounded with walls and otherwise filled with emptiness. For instance, makeRoom(0, 1, 1, 10, 10) should give:
----------
|********|
|********|
|********|
|********|
|********|
|********|
|********|
|********|
----------

Instead, however, I get a room that's as wide as the dungeon floor, respecting only the height, and the walls on the side never arrive. So instead, I get an arrangement more like this:
---------------------------
***************************
***************************
***************************
***************************
***************************
***************************
***************************
***************************
---------------------------

Changing the total available width of the dungeon floor causes the room to shrink or grow horizontally regardless of what size I ask it to have. The side walls never appear no matter how I tweak the ranges, where I tweak them, or what I comment or uncomment. In short, only the height and top/bottom is ever obeyed, no matter what I attempt.
base.py (main game loop):
import sys
import libtcodpy as libtcod
import entity
import dungeon

SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
LIMIT_FPS = 20

libtcod.console_set_custom_font('../dejavu10x10_gs_tc.png', libtcod.FONT_TYPE_GRAYSCALE | libtcod.FONT_LAYOUT_TCOD)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'MadNet Zero', False)
libtcod.console_set_foreground_color(0, libtcod.white)

# The buggy functions
saturnSeven = dungeon.Dungeon(5)
saturnSeven.makeRoom(0, 1, 1, 10, 10)

player = entity.Player(25,25,3,4,0)
libtcod.console_print_left(0, player.X, player.Y, libtcod.BKGND_NONE, '@')
libtcod.console_flush()

while not libtcod.console_is_window_closed():
    libtcod.console_set_foreground_color(0, libtcod.white)
    #clear the player's old position
    libtcod.console_print_left(0, player.X, player.Y, libtcod.BKGND_NONE, ' ')

    #print terrain
    for y in range(len(saturnSeven.floor[player.Z][0])):
        for x in range(len(saturnSeven.floor[player.Z])):
            symbol = saturnSeven.getTerrainSymbol(x,y,player.Z)
            libtcod.console_print_left(0, x, y, libtcod.BKGND_NONE, symbol)
    libtcod.console_print_left(0, player.X, player.Y, libtcod.BKGND_NONE, player.char)
    libtcod.console_flush()

dungeon.py (does the meat of the work):
# Define terrain types as a pseudo-enum
wall, empty, solid = range(3)
class Cell(object):
    def __init__(self, terrain, items):
        self.terrain = terrain
        self.items = items
    def isPassable(self):
        if self.terrain != wall:
            return True
        else:
            return False

class Dungeon(object):
    def __init__(self, numfloors):
        self.MAXFLOORS = numfloors
        self.floor = [None]*numfloors
        for i in range(numfloors):
            self.floor[i] = makeFloor(20,20)

    def makeRoom(self, floorNum, Xmin, Ymin, Xmax, Ymax):
        #inner area
        for x in range(Xmin+1, Xmax):
            for y in range(Ymin+1, Ymax):
                self.floor[floorNum][x][y] = Cell(empty, None)
        #top/bottom wall
        for x in range(Xmin,Xmax+1):
            self.floor[floorNum][x][Ymin] = Cell(wall, None)
            self.floor[floorNum][x][Ymax] = Cell(wall, None)
        #left/right wall
        for y in range(Ymin, Ymax+1):
            self.floor[floorNum][Xmin][y] = Cell(wall, None)
            self.floor[floorNum][Xmax][y] = Cell(wall, None)

    def getTerrainSymbol(self, X, Y, Z):
        if self.floor[Z][X][Y] == None:
            return ' '
        if self.floor[Z][X][Y].terrain == wall:
            return '#'
        if self.floor[Z][X][Y].terrain == solid:
            return ' '
        if self.floor[Z][X][Y].terrain == empty:
            return '.'

def makeFloor(Xmax, Ymax):
    return [[Cell(solid, None)]*Xmax]*Ymax

I've eliminated the graphics as being a problem; the dungeon itself is definitely what's wrong, not how it's being displayed on screen. I can't find any reason the algorithm should be wrong in this way, though.
EDIT: The original version of the code that gave the diagram above had the "inner area" portion underneath the part that made the walls; putting it on top, as I did, results in the entire room being made up of walls, but still too wide. So far as I can tell they should give equivalent results; they do not.
Comment: Did you try to look at self.floor before and after each of the blocks that create the room?
Comment: I had the loop give me the coordinates where it should have been writing individual wall segments, and I've commented/uncommented each part of the function in turn to see the different results. Even if I narrow it down to one row, that row still winds up being as wide as it physically can, rather than as wide as it's set to be.
Answer: Your problem (or at least one of them) is the definition of makeFloor.  Try this instead:
def makeFloor(Xmax, Ymax):
    return [[Cell(solid,None) for i in range(Xmax)]
            for j in range(Ymax)]

Explanation: If you do [x]*10, then you get a list containing 10 elements, each of which is x -- the same x.  If you change one, then the others will change as well.  Similarly, if you do [[x]]*10, then you get a list containing 10 sublists, each of which is the same sublist -- again, changing one will change them all.
Comment: This was it exactly: the room gets set exactly how it should with your definition. Thanks!


pam limits in docker containers aren't working

Question: I added something in /etc/security/limits.conf in a docker container to limit the max number of user processes for user1, but when I run bash in the container under the user user1, ulimit -a doesn't reflect that limits defined in the pam limits file (/etc/security/limits.conf).
How can I get this to work?
I've also added the line session required pam_limits.so to /etc/pam.d/common-session, so that's not the problem.
I start the docker container with something like sudo docker run --user=user1 --rm=true <container-name> bash
Also, sudo docker run ... --user=user1 ... cmd doesn't apply the pam limits, but sudo docker run ... --user=root ... su user1 -c 'cmd' does
Comment: Have you seen [this SO question](http://stackoverflow.com/questions/21979137/enable-pam-configuration-limits-conf-for-a-running-daemon), does it help here?
Comment: Docker 1.6 (soon to be released), will allow setting per-container ulimits. More information and partial documentation can be found in the pull-request; https://github.com/docker/docker/pull/9437/files
Comment: Hmm, I guess that does clarify a few things. Using `su user1 -c 'cmd'` is essentially the same thing as using a wrapper that sets all the ulimits I guess. That might be my best option here. Thanks!
Answer: The /etc/security/limits.conf is just a file that is read by PAM infrastructure on boot.  Docker containers are clones of the kernel in pristine state after it just started.  This means that none of the inherited initializations of the environment will apply to container.  You have to use the 'limit' command directly to set the process limits.
Better way to do that would be to use container limits,  unfortunately current version of docker doesn't support limits on number of processes.  Looks like the support will be coming in version 1.6 when it comes out, as @thaJeztah has mentioned.


Odd Behavior of DNS forwarding with SRV record resolution

Question: I'm running into a weird problem while setting up a new SAMBA AD DC on my network. I've got the DC itself up and running and checked on the server that I am able to resolve the DNS name of the server, along with the Kerberos and ldap SRV records. I have its Internal DNS set to forward to my network's gateway, and all my client computers are configured to point their Primary DNS to the DC (I do not have any secondary DNS entries on the client computers).
The odd thing is, that from the clients, I can ping the DC from its IP address, NetBIOS name, or FQDN and all map to the correct IP address. But when I go to add the clients to the domain, I get an error complaining that the DC could not be contacted, with the following detail in the error box:

The following error occurred when DNS was queried for the service
  location (SRV) resource record used to locate an Active Directory
  Domain Controller (AD DC) for domain "local.foobar.com":
The error was: "DNS name does not exist." (error code 0x0000232B
  RCODE_NAME_ERROR)
The query was for the SRV record for
  _ldap._tcp.dc._msdcs.local.foobar.com

But if I SSH into the server and run:
<code>$ host -t SRV _ldap._tcp.local.foobar.com
_ldap._tcp.local.foobar.com has SRV record 0 100 389 dc1.local.foobar.com.
</code>
I'm beginning to wonder if maybe I'm misunderstanding how the DNS Forwarder works. My understanding was that the clients (which are all pointing to the DC's DNS) would reference it first for DNS information, and then get forwarded along to the gateway's DNS if they don't find the entries they need. But it seems like they are not finding the existing SRV records In the DC's DNS (or they are just getting forwarded directly to the gateway, which I definitely did not add the entries too.... What do you think could be the problem here? Do I need to manually add the SRV records to the gateway or should the DC's internal DNS be responding to these requests?
P.S. As an aside, I did try entering the NetBIOS Domain name "LOCAL" and it seems to find the server and prompt me to enter the Administrator credentials and it lets me join the domain. I didn't go through with adding them this way though, as there is apparently a deeper issue here, but just wanted to mention this in case it could shine any light on the situation.
Comment: Did you noticed that the name record you queried is not the name specified in the error message?
Comment: Good Call, I changed the host query to match the error message and I did still get a correct record entry.
Answer: OK, I figured out what was causing the problem. My client computers get their IP addresses via DHCP from the gateway, which is configured to pass along the DC's IP address for the primary DNS.
However, for the IPv6 address, that was getting the wrong DNS address for the server, which (I believe)  caused the DNS on the computer to default to the gateway. Anyway, my solution for now is to simply disable the IPv6 protocol for the client computers, which then allows the computer to find and join the network. The only thing is this seems a bit hacky. I want to find a way to setup the gateway to properly configure the IPv6 settings, but will post about this in a separate post.
Comment: When there's a problem wiht AD, It's always DNS...  I was going to post a comment on the Q along the lines of where are the machines you're trying to join getting their DNS settings from?


Relative Major/Minor keys question

Question: I've got a question, I thought perhaps one of you fine human beings could help me out.
I am under the impression that you can find the relative minor key of a major key by counting down 3 steps, alternately, you can find the relative Major by counting up 3 steps from the minor. That minor should have the same amount of sharps and flats as it's relative Major. Correct so far?
So, I'm doing an exercise that requires me to identify the diatonic 7th chord for a particular scale degree of a particular minor key. The question is in the form of; B Minor, VII7 = _ _ _ _ _ . So for that instance, I got A7.
I worked that out by first identifying the relative major of B, which is D, which I know has 2 sharps, F and C. Then I wrote out the B Minor scale and knew that A was the 7th degree, and that the 7th degree of a minor diatonic progression would make it a Dominant 7th, thus A7.
Now, when I go to the next example; F Minor, v7 = _ _ _ _, I try to repeat the same process but it doesn't work. A 3rd up from F is A, A Major has 3 sharps, so F C G are sharp, but F Minor obviously can't have an F# in it. So what am I missing? I know I can just write out F minor by the W-H-W-W-H-W formula, but I'm trying to do it with the relative major/minor formula. Halp?
Comment: A third up from F minor is Ab : )  That might be part of your problem
Comment: Note also that it's 3 half-steps, rather than steps.
Comment: @Stephen is right. You should be calculating a minor third up and in your post you're pointing a major one. :)
Answer: F minor has 4 flats (Bb, Eb, Ab, Db) its relative major would be Ab Major. Knowing that the v7 for F minor is a C minor 7th (C, Eb, G, Bb) as per the f minor scale but if we are in the context of the F harmonic minor then this chord would be C, E, G, Bb. Context matters here.
(corrections made.)
I think this is a kind of round about way at learning relative chords. Better to learn your key signatures by heart as a more direct route to the answer. Thinking about the relative major and minor has its place but this does not appear to be here.
Comment: Thanks for the help guys, it was just a careless mistake in reading comprehension, I was going up/down in whole steps, not half-steps. DUH!
Comment: Not a problem. Keep those whole steps in mind if you ever need to use the whole tone scale.
Answer: This may sound annoying and hard to you, but to avoid this type of problem you could try memorizing which keys have which sharps and flats so you don't have to rely on counting half steps. This way you can quickly think "E♭ major has three flats, c minor has three flats..." without counting the half-steps.
Answer: The way I was taught it is to go down from the Major Key we have a whole tone and then another semi tone to a different note. So for instance.
D Major. Go down a whole tone -> C. Then another semi tone to a different note -> B
C Major go down a whole tone -> Bb. Then another semi tone to a different note -> A
Ab Major go down a whole tone -> Gb. Then another semi tone to a different note -> F
And so on and so forth.

Relative Major/Minor keys question


"Syntax error, unexpected '&'" ao chamar a função exec

Question:

    <meta charset="UTF-8">
    <title>Executar</title>

    <?php
        exec( 'Done.exe', &$resultado);
        echo $resultado;
    ?>

Não está funcionando o comando exec, como faço para habilitá-lo?
Comment: Removi as tags HTML, CSS, JavaScript e Node porque não vi relação alguma com a pergunta. Se existir uma relação, recomendo que edite a pergunta detalhando melhor o problema.
Comment: E com base em que você afirma que o `exec` não está funcionando? Deu algum erro? Qual? O que `Done.exe` faz? Ele está no mesmo diretório? O usuário possui permissão para executá-lo? Quais são as últimas mensagens no arquivo de log do seu servidor PHP?
Comment: Para passar uma variável como referência no PHP apenas o argumento da função precisa indicar o `&`. Você não precisa indicar isso na chamada da função, então faça apenas `exec('Done.exe', $resultado)`
Comment: Parse error: syntax error, unexpected '&', expecting ')' in C:\xampp\htdocs\Executar\index.php on line 8
Comment: O arquivo está na mesma pasta do index.php
Comment: O arquivo Done.exe executar um jogo em C++ que eu programei e o erro que dar é esse: syntax error, unexpected '&', expecting ')' in C:\xampp\htdocs\Executar\index.php on line 8
Answer: Vide documentação:

Nota: Não há o sinal de referência na chamada da função - apenas nas definições de função. As definições de função, sozinhas, são suficientes para passar o argumento por referência. A partir do PHP 5.3.0 você receberá um alerta de "call-time pass-by-reference" está obsoleto quando usar o & na em chamadas de função: foo(&$a);. A partir do PHP 5.4.0, passagem por referência na chamada foi removido, e usar isso causará um erro fatal.

Ou seja, apenas a assinatura da função que deve indicar que a passagem será feita por referência e não por valor. A partir da versão 5.4 as chamadas utilizando o caractere & causarão um erro de sintaxe como você obteu.
Ou seja, na chamada de exec basta fazer:
exec('Done.exe', $resultado);

Mesmo a variável não existindo no contexto ela será criada para receber o valor definido pela função.
Comment: @SchillerDrummond No servidor, sempre.
Comment: Se eu colocar isso em um servidor, irá ser executado na máquina do servidor ou no computador da pessoa?
Comment: Agora como vou infectar minhas vítimas com esse comando :(
Comment: @SchillerDrummond Não vai...


Databases in local programming

Question: I am trying to model cooperation in Ruby, and I have classes like  Simulator and Agent. I find I will end up doing things that would fit well with databases, like saying things like this.agent.find_by_id(1).score.increment or this.cooperate, where cooperate passes a value to the Simulator, which then adds some value to the two agents score, and keeps one tally for the agents. Is this possible, or am I just thinking about it wrong?
Comment: Do you want to use a database? Your syntax doesn't drive the need to have a database. Data storage and persistence, random access for fast access, huge amounts of data, all those start to point toward the need for a database. If you want ActiveRecod-like syntax, you can write methods based on AR, without the DBMS.
Answer: You can use ActiveRecord outside of rails:
require 'active_record'
require 'mysql2'

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql2',
  :database => 'database_name',
  :username => 'username',
  :password => 'password',
  :host     => 'localhost'
)

You classes should just inherit from ActiveRecord::Base. You can probably also use Mongoid or any other database mapper.

Databases in local programming


Can you show me a path for $\lim_{(x,y)\to(0,0)} \frac{(x^2 - y)\cdot y}{x^4} \neq 0$

Question: I've been trying differents paths for this limit. They all resulted in the limit being $0$, so I've tried an epsilon-delta definition but reached a contradiction.. my guess is that the limit doesn't exist and I just can't come up with a curve that will prove it.

$$   \left\{
\begin{array}{ll}
      \lim_{(x,y)\to(0,0)} \frac{(x^2 - y)\cdot y}{x^4} & 0<y<x^2 \\
      0 &  otherwise\\
\end{array}
\right. $$

Can you show me a path? Going along the axis, straight lines and parabolas didn't work for me...
Comment: I believe you'll want to make it more clear that you want $0<y<x^2$.
Answer: Suppose we approach $(0,0)$ along the path $(x,y)=(t,at^2)$ where $0<a<1$. Then the limit along this path is
$$\lim_{t\to 0} \frac{at^4-a^2t^4}{t^4} = a-a^2$$
which is usually not equal to $0$.
Comment: I think you'll want $0<y<x^2$, as per the question.
Answer: Take the limit along a path on the curve $y=ax^2$, for fixed $a$ with $0 < a < 1$.
Answer: $(t,0)$ where $t$ tends to $0$, and $(t,-t^2)$, $t$ tends to $0$.
Answer: I'm going to take a simplistic approach and assume the $x=x(t),\ y=y(t)$ and apply L'Hôpital's rule. Thus,
$$\lim_{(x,y)\to(0,0)} \frac{(x^2 - y) y}{x^4} = \frac{\frac{d}{dt}(x^2 - y) y}{\frac{d}{dt}x^4}=\frac{x^2\dot y+2xy\dot x-y\dot y}{4x^3\dot x}$$
The object is to choose $y=f(x)$ so as to cancel the $x$-terms in the numerator an denominator. The clear choice is $y=ax^2,\ \dot y=2ax\dot x$. Following through it can readily be shown that
$$\lim_{(x,y)\to(0,0)} \frac{(x^2 - y) y}{x^4} = a-a^2$$
as was demonstrated intuitively earlier by @florence.


Evento Mysql para deletar linhas com data expiradas

Question: Estou tentando criar um evento para deletar linhas, que a coluna date esteja com a data expirada, ou seja menor do que a atual.
Estava tentando com o seguinte comando:
create event e on schedule every 1 day do delete from Reserve where date < curdate();

Mas depois fui testa-lo adicionando uma linha com ma data já passada e trocando o every 1 day para every 1 second Mas não tive sucesso...
Alguém poderia me ajudar com a query correta para o meu problema?
Comment: Tente where trunc(date) < curdate(). Ou ainda, veja se o formato do teu campo date está igual a saida do curdate.
Comment: Se você tentar algum outro evento ou um diferente parâmetro para o where, ele executa?
Comment: Não consegui, @Diego. E sim, o formato utilizado é o mesmo.
Comment: @LeonardoCoelho Tentei com outros parâmetros, mas não tive sucesso também...
Comment: é bom usar CronJob para coisas como essas.
Answer: CREATE EVENT IF NOT EXISTS `dbName`.`eventName`
ON SCHEDULE
    EVERY 1 DAY // or 1 HOUR
COMMENT 'Description'
DO
    BEGIN

    DELETE FROM `dbName`.`TableName` WHERE `DateCol` < NOW();

    END

Amigão adapte esse código acima! (como você não disponibilizou os campos eu não posso adaptar para vossa pessoa :/ )
LEMBRANDO É NECESSÁRIO ATIVAR O MySQL Event Scheduler
Fonte: https://stackoverflow.com/questions/18181458/auto-delete-a-record-in-table-when-date-is-expired
Comment: Não sabia que tinha que ativar algo antes :(. Mas deu tudo certo aqui, Raphael. Muito obrigado!
Comment: Sim, concederei. Mas só posso daqui a 23 horas. :))
Comment: Sem problemas, boa sorte no seu projeto, qualquer duvida estou aqui para ajudar, e se quiser conceder a recompensa eu fico feliz :D, mas mesmo assim, boa sorte.


How to prove real symmetric matrix can be diagonalized via my approach?

Question: My idea of proving every real symmetric matrix can be diagonalized is that, first prove two eigenvectors with different eigenvalues must be orthogonal, then I failed to prove that all the eigenvectors span the whole vector space.
To be specific, my question is, if $A$ is a real symmetric $n\times n$ matrix, let $p(t)=\det(tI-A)$ be the characteristic polynomial of $A$, and $\lambda$ be some eigenvalue of $A$, and $\lambda$ is a root of $p(t)$ of order $k$, then how to prove $\dim (\ker(\lambda I-A))=k$?
Comment: Do you already know a proof of the theorem and want to find your own using this particular caracterisation of diagonalizability, or do you ask for any proof of this fact? I ask because it seems to me a little unsuited, but comments and answers may prove me wrong, to go about proving the theorem uaing this criterion of diagonalizability.
Comment: @OlivierBégassat Yes, I do know a proof, yet I find the proof in my textbook seems delibrately avoid the question I put here, so I'm here asking for help~
Comment: What is the gist of your textbook proof? One way to prove it is to use the fact that any real endomorphism stabilizes a line or a plane (possibly both), to show that the induced endomorphism remains symmetric, and that the orthogonal complement is also stabilized, and to use recursion. there are slightly easier proofs along the same lines...
Comment: Do you know what is relation between the multiplicity of $\lambda$ and $\dim (\ker(\lambda I-A))=k$?
Comment: On another note: you are aware that it is possible for a symmetric matrix to have repeated eigenvalues, and yet still have orthonormal eigenvectors, right?
Comment: Here is one possible way to go about. You should first show that there are only real eigenvalues. Then you know $A$ to be trigonalizable. Then use the Gram-Schmidt process to orthonormalize this basis. Because of how this process is done, the orthonormal basis you end up with is stil a basis of trigonalization. But being an orthonormal basis, the matrix has to be symmetrical. As a result, your matrix is both upper triangular and symmetrical thus is diagonal. At first I wanted to look at symmetrical nilpotent matrices, but this is quicker, albeit a little furthee away from your request.
Answer: There are obviously many ways to prove your statement. Some of the comments suggest to use the following:
Let $v$ be an eigenvector to the eigenvalue $\lambda$. Set $U=\mathbb R v$ and write $\mathbb R^n=U\bot U^\bot$. Then $A(U)\subseteq U$ and $A(U^\bot)\subseteq U^\bot$ (you use symmetry here). Therefore we can restrict $A$ to $U^\bot$, get a symmetric matrix and proceed by induction. This is somewhat the standard proof of the spectral theorem.
Another way - I think a way closer to what you asked - would be the following lemma:
If $x\in Ker(\lambda I-A)^k$, then $x\in Ker(\lambda I-A)$.
For simplicity I will proof the case $k=2$. Let $x\in Ker(\lambda I-A)^2$ and $y=(\lambda I-A)x$. We want to show $y=0$. We have
$$\lambda x=Ax+y$$
and
$$\lambda y=Ay$$
It follows
$$\lambda \left<y,x\right >=\left<y,Ax+y\right >=\left<y,Ax\right >+\left<y,y\right >=\left<Ay,x\right >+\left<y,y\right >=\lambda\left<y,x\right >+\left<y,y\right >$$
Which means $y=0$.
If you believe that there is a basis of generalised eigenvectors you are done.


Using Feeds Tamper to convert one list to another?

Question: I am using a feeds importer to import a number of FIPS county codes for given locations and I was hoping to use the Feeds Tamper module to convert those county codes to county names, but have thus far been unsuccessful. Any ideas? I realize that there is a "Find replace" plugin for the Feeds Tamper, but seeing as this seems only to convert a single word or phrase at a time, I'd have to do this too many times for it to be worthwhile, though it does seem to reveal that the module is capable of doing the task I desire.
Thanks in advance,
David
Answer: For like http://www.census.gov/2010census/xls/fips_codes_website.xls use Feeds or Migrate modules to fill-in a Content Type with the Fields in the Excel file. The are many tutorials online of importing data from a csv or excel sheet to Nodes.
Comment: Perhaps I was unclear, sorry if that was the case. I already have all the FIPS codes within a content type, but I'd like a way to convert those codes to county names automatically (via Feeds Tamper or maybe, Taxonomy, I don't know)
Comment: sorry i dont understand your question. what fields or relationships do you want in your final Drupal structure of data for your website?
Comment: I apologize in advance for the long explanation. I have a "county" field in a content-type I've made. I've been searching for a file that relates the county to another field within that same content-type. While I couldn't find anything relating the county name, I found a file relating the county code. So I uploaded that to the county field in the content-type. However, I would like the county name instead of the county code, but do not wish to have to enter all the names in manually - though I could do that. Better?
Comment: If you have not found a file of `county names` -- you'll have to enter them by hand per Node. https://www.drupal.org/project/views_bulk_operations or https://www.drupal.org/project/editableviews should help you list all your nodes in 1 form to add county names and not have to edit each node individually.


Xcode - How IBOutlets and Nib files work?

Question: I'm for the first time using nib files. I mean xib and the corresponding swift class.
Here is my swift class:
import UIKit

@IBDesignable class LittleVideoView: UIView {

    var view: UIView!

    var nibName: String = "LittleVideoView"

    // MARK: Views
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var clicksLabel: UILabel!
    @IBOutlet weak var channelNameLabel: UILabel!
    @IBOutlet weak var thumbnailImageView: UIImageView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        addSubview(view)
    }

    func loadViewFromNib() -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        return view
    }
}

From the editor view I created some IBOutlets as you can see. Everything works properly.
There is just something I don't understand. I am programmatically loading the nib in this class, so why can I create IBOutlets while Xcode doesn't really knows that I will really load the correct nib file? Shortly, I don't understand how IBOutlets can work in this case. So, how will Xcode correclty link the loaded UIView in the setup() method with the IBOutlets ?
Comment: This is not an unreasonable thing to want to know, but there is no need to ask it _again_; it has been explained many times here.
Answer: Nib files have a "File's Owner" type which the editor uses to list available outlets and actions. However when the nib is loaded at runtime that type is not enforced. Outlet's are connected using -setValue:forKey: under the assumption that the "Owner" passed to instantiateWithOwner is compatible with any outlet bindings defined in the nib.
One xib File with Multiple "File's Owner"s
If you have an IBOutlet, but not a property, is it retained or not?
Comment: Thank you, I forget about the "instantiateWithOwner" :)