How do I determine if a HTML-form answer is correct (calling PHP via $.post), without revealing the answer?

Question: I'm working on a fill-in-the-blank quiz (current state).  In my index.php, I want to verify that the user input is the correct answer (as in, it matches what's in my MySQL server).
I can verify the answer is correct by <?php echo ... ?>-ing the answer, but this results in the answer being in the in the html file, which has the drawback of allowing cheating.
I gather from this answer, that I need to use something like $.post('file.php', {variable: variableToSend});, so I attempt to do that:

The above Javascript function is called from a html form elsewhere in my index.php; I can used console.log to verify that the input variable above is the actual user input.  However, judging from console.log, the way I'm using $.post is totally wrong, but I'm not sure what the correct syntax is.
In process_answer.php I have:
<?php
    if($_POST['guess'] == $problem_data["answer"]) echo "1";
    else echo "0";
?>

I'm not sure how to proceed from here.
Question: How do I determine if a HTML-form answer is correct (calling PHP via $.post), without revealing the answer?
Comment: So post the answer to the server and have the server check to see if it is right. Have the server return a boolean
Comment: `$.post('process_answer.php', {guess: input}).done(function(xxx) {
    console.log(xxx);
  });`
Comment: Yes, that's what I'm trying to do.  I'm just not succeeding.
Comment: I think what you might need to do is to `json_decode` the response in the PHP before you check since you are passing a JSON object in the `$.post`
Comment: @aljx0409 OP is not posting JSON. That is how jQuery posts `application/x-www-form-urlencoded` data
Answer: You're approach is good. The ajax call is a good way to do it.
In Javascript, according to the documentation, you just have to wait for a server response. But you have to notice that is asynchronous (so the code below, will probably be executed before your callback). I propose something like that.
$.post('process_answer.php', {guess: input})
  .done(function( data ) {
    // Execute your logic inside the request callback
    if(data) {
        [...snip...]
    }
    else {
        [...snip...]
    }
  }
);

And in your php, I suggest to exit the script or simply return a value
<?php
// return a json encoded boolean
header('Content-type: application/json');
echo json_encode($_POST['guess'] == $problem_data["answer"]);die;
?>

EDIT after Phil's comment :
Phil is right, I've updated my example.
Comment: @Phil You're right, after a quick test, the return isn't sufficient. Bad habit from using frameworks :)
Comment: The PHP needs an `echo`, not a `return`. I would also add `header('Content-type: application/json')` and `json_encode()` the response


Difficultly understanding the inclusion exclusion identity because of difficult notation

Question: This is the property: $\mathbb{P}(E1\cup E2\cup ...\cup En)= \sum_{i}^{n} \mathbb{P}(E1) - \sum_{i1<i2} \mathbb{P}(Ei1Ei2) + ... + -1^{r+1}\sum_{i1<i2<...<ir} \mathbb{P}(Ei1Ei2...Eir) + -1^{r+1}\sum_{1<2<...<n} \mathbb{P}(E1E2...En) $
While I understand the property, I don't understand the summation symbol notation. What does the book mean by $\sum_{i1<i2<...<ir}$? Can someone draw out specifically what this sum is so I can understand it? I lost my question privileges due to this question but can someone please let me know what about this question was so bad? I couldn't find the syntax anywhere.
Comment: I'm not sure why it isn't showing the whole equation it shows up in my edit
Comment: Learn how to write with [latex](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) .
Comment: use `\cup` for $\cup$ and `\sum_{i=1}^{n}` for $\sum_{i=1}^{n}$.
Answer: There are $r$ distinct terms, where $i_1, \ldots, i_r$ are chosen from $\{1, \ldots, n\}$ and satisfies $i_1 < i_2 < \ldots, i_r\}$.
For example if $n=4$, $r=3$,
$$(-1)^{r+1} \sum_{i_1 < i_2<i_3}P(E_{i_1}\cap E_{i_2}\cap E_{i_3})=(-1) \left( P(E_1 \cap E_2 \cap E_3) + P(E_1 \cap E_2 \cap E_4)+P(E_1 \cap E_3 \cap E_4)+P(E_2 \cap E_3 \cap E_3)\right)$$
Using this notation avoid listing the same thing multiple times, for example $P(E_1 \cap E_2 \cap E_3) = P(E_3 \cap E_2 \cap E_1)$ and we don't want to list it twice.
Answer: Some people would write the sum $\sum_{i_1<i_2<\cdots<i_r}$ as
$\sum_{1 \leq i_1<i_2<\cdots<i_r \leq n}$
in order to emphasize that all the variables $i_1,i_2,\ldots,i_r$ have to be between $1$ and $n$ inclusive.
The $r$th sum can be rewritten in more basic summation notation as
$$
\sum_{1 \leq i_1<i_2<\cdots<i_r \leq n} \mathbb{P}(E_{i_1}E_{i_2}\cdots E_{i_r})
= \sum_{i_1 = 1}^{n - r + 1}\, \sum_{i_2 = i_1 + 1}^{n - r + 2}\,
   \sum_{i_3 = i_2 + 1}^{n - r + 3} \cdots  \sum_{i_{r-1} = i_{r-2} + 1}^{n - 1}\,
   \sum_{i_r = i_{r-1} + 1}^{n} \mathbb{P}(E_{i_1}E_{i_2}\cdots E_{i_r}).
$$
Each side of the equation ends up with $\binom nr$ individual terms in the sum, one for each possible sequence of $r$ increasing integers where none is less than $1$ or greater than $n.$
Each of those sequences picks out a different subset of $r$ of the events in the set $\{E_1, E_2, \ldots, E_n\}.$
Personally, I find the notation on the left is a lot easier to understand.


How should I configure my Active Directory servers so that if one goes down, users are not kicked off SQL?

Question: Today, we shut down one of our Active Directory servers during office hours to check the loading on a UPS.  Since all the server did was provide Active Directory in a separate building incase the main building caught fire, or whatever, we didn't think it would have any effect on our users.
Seconds after the server was shut down, we had a dozen phone calls from users experiencing this issue:-
[Microsoft SQL Server Login]
SQLState: '28000'
[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed.  The login is from an untrusted domain and cannot be used with authentication.
Once we realized what had happened, we quickly rebooted the down Active Directory server.  Problem solved.
But why did this happen.  And what if one day a server has a breakdown and is offline for hours, or days?  Shouldn't the other Active Directory servers in the domain service authentication requests without disruption to users?
We have 3 Windows Server 2003 Standard servers running Active Directory as Domain Controllers with Global Catalogs, all physically located on the same network at Gigabit speeds.
I believe the domain was originally Windows Server 2000, or maybe even NT 4.0.  Could the issue be to down to old Group Policies inherited from these old server OS's, or some default setting in Active Directory that needs changing?
Answer: It sounds like you may not have your DNS configured properly.  You have to make sure that the clients can issue DNS requests to the other DCs.  In other words your client DHCP settings should provide the DNS records for all of your DCs (if they run the DNS service).  Either way you also need to make sure that all of your DCs are registered in DNS as well.
Clients should automatically fail over for authentication but if your application caches credentials for some reason it may have tried to only go back to the original DC for authentication.
Comment: All 3 AD servers are configured as DNS servers in DHCP.  There are also _kerberos and _ldap records under _msdcs.example.com\dc\_tcp.  The SQL Connection string is "ODBC;DRIVER=SQL Server;SERVER=example-server;DATABASE=DB_Live;Trusted_Connection=Yes;".  I wonder if there is some limitation to the "SQL Server" ODBC driver and we should be using a Native SQL Client driver instead?
Comment: @MattyBrown That really shouldn't matter, but to eliminate that as a problem you could easily open a connection to SQL with the standard OLE provider and see if that helps, via DSN.
Comment: Also, make sure you're SQL box has the proper DNS settings as well for all three DCs.
Comment: Our SQL box has the correct DNS server settings.  I've coded our application so that if the SQL Server Native Client is available, that's used instead of the SQL Server driver.  I suppose I won't be able to see if this has corrected the problem without shutting down or disconnecting one of our AD servers.
Comment: @MattyBrown It's never easy to test AD problems ;)


Getting an object from mongoDB with Mongoid

Question: Simple enough situation. I've got a MongoDB database with a bunch of information from a previous developer. However I have limited information on the model that came before hand and I DONT have access to the original model class. I've been tinkering with the MongoDB driver to get some more information on it (MongoID will have to be used eventually to map the object back out) as follows.
<code>#The flow is as follows
  #Connection
  #Databases
  #Database
  #Collection
  #Hash Info

  #Setup the connection. you can supply attributes in the form of ("db",portno) but most of the time it will pick up the defaults
  conn = Mongo::Connection.new

  #Database info
  mongodbinfo =conn.database_names
  conn.database_info.each { |info| puts info.inspect }

  db = conn.db("db_name_here")
  db.collection_names.each { |collection| puts collection.inspect  }

  collection = db.collection("model_name_here")
  puts collection.inspect

  collection.find.each { |row|
    puts row.inspect
    puts row.class
  }
</code>
Each row is a separate object and as MongoDB works, each object/document is a BSON object.
So the bottom line question is How do i de-serialize the BSON into a model using mongoID?
P.s Feel free to use the above code if your trying to figure out a new mongoDB, its been handy for debugging IMHO.
Answer: So this was a bust.
In the end I used the Mondb driver to manually pull the data out with queries. However creating the object was far more difficult.
Its better to have the actual model when using ORM.


Finding the Galois group of $\mathbb{Q}(\alpha,i)|\mathbb{Q}$, whereby $\alpha^2 = \frac{3}{2}+\frac{1}{2}i\sqrt7$

Question: I would like to find the Galois group of the finite extension $\mathbb{Q}(\alpha,i)|\mathbb{Q}$, whereby $\alpha^2 = \frac{3}{2}+\frac{1}{2}i\sqrt7$.
Note that $\mathbb{Q}(\alpha,i)$ is the splitting field of $(X^4-3X^2+4, X^2+1)$.
I would know what to do if I would find a primitive element of the extension, but that seems not so easy to find.
I would appreciate any hints.
Comment: Maybe I missed something, but aren't the four roots of $X^4-3X^2+4$ equal to $\pm(\frac{\sqrt7\pm i}{2})$, so that $\mathbb Q(\alpha,i)=\mathbb Q(\sqrt7,i)$ and the degree of the extension is $4$? If so, then as the group has two elements of order $2$ (one sending $i$ to $-i$ and another sending $\sqrt7$ to $-\sqrt7$), it must be $\mathbb Z/(2)\times\mathbb Z/(2)$.
Comment: @mathcourse yes, but $$\pm \sqrt{\frac{3\pm i\sqrt7}{2}} = \pm(\frac{\sqrt7\pm i}{2})$$
Comment: The roots should be $$\pm \sqrt{\frac{3\pm i\sqrt7}{2}}$$.
Comment: Oh yes, thank you!
Answer: Since the four roots of $X^4-3X^2+4$ are equal to $\pm(\frac{\sqrt7\pm i}{2})$, we find $\mathbb Q(\alpha,i)=\mathbb Q(\sqrt7,i)$ and the degree of the extension is $4$. As the Galois group has two elements of order $2$ (one sending $i$ to $-i$ and another sending $\sqrt7$ to $-\sqrt7$), it must be $\mathbb Z/(2)\times\mathbb Z/(2)$.

Hope this helps.


java.lang.IllegalArgumentException: n must be positive in deck class

Question: I'm making a card game and I'm getting the error that n must be positive. I did some research and it means that (cards.size) is equal or less than 0 I believe, but I don't understand how to make my code work, something must be wrong.
Code:
public class Deck
{
public ArrayList <Card> cards;
Deck()
{
    cards = new ArrayList<>();
    for (int a = 0; a < 52; a++)
    {
            cards.add(new Card(a));
    }
}

public Card PlayerCardDraw ()
{
    Random generator = new Random ();
    int index = generator.nextInt (cards.size ());
    return cards.remove (index);

}

How can I fix my array list so i don't get this error? it relates back to Card so I'll post that code too, I know something isn't right in my Card class but I don't know if that's the problem or not.
public class Card
{
int c = 52;
int cardpath[] = new int[c];

Card ()
{

}

public Card(int c)
{
    this.c = c;
}

public int getCardPath()
{
return cardpath[c];
}
}

Error message:
java.util.Random.nextInt(Unknown Source) at Cards.Deck.PlayerCardDraw(Deck.java:21)
line 21 is int index = generator.nextInt (cards.size ());

EDIT: I did what Nankumar Tekale said and it's saying what you guys predicted: It's drawing more than 52 cards. What I don't understand is the error is popping up at
for (int i = 0 ; i < 4 ; i++)
    {
        C = deck.P1CardDraw ();
        card [cardNum].draw (i*75+100, 400); //Error line
        cardNum++;
    }

my P1CardDraw() class
public ArrayList < Card > p1Hand;
public ArrayList < Card > P1CardDraw ()
{

    p1Hand = new ArrayList < > ();
    p1Hand.add (PlayerCardDraw ());
    return p1Hand;
}

Comment: Where is it giving you the error? Can you post the error message/stack trace?
Comment: @Adio thats type inference, it'd work in java 7, however < java7 its a compiler error
Comment: It seems there is other code we might need to see, but my guess is `PlayerCardDraw()` is being called too many times, emptying out `cards` and causing `0` to be sent to `nextInt()`.
Comment: cards = new ArrayList<>(); should be ArrayList (); I guess.
Comment: @iamnotmaynard at java.util.Random.nextInt(Unknown Source)
 at Cards.Deck.PlayerCardDraw(Deck.java:21) line 21 is  int index = generator.nextInt (cards.size ());
Comment: @Hitman47 i do not know how to call a constructor in its own class
Comment: You should edit your question to include the error message. How many times does `PlayerCardDraw()` get called?
Comment: @HaydenHolligan acutally i did try your case and it works...so i tried new Deck().PlayerCardDraw ();
Comment: Instead of drawing randomly, you could simply shuffle the deck: `Collections.shuffle(cards);`.
Comment: @iamnotmaynard right now it's called through another arraylist for the player's hand and it is used in a for statement for (int i = 0 ; i < 4 ; i++)
Comment: @assylias after shuffling it how could i use that to generate a random number(index) to be removed from the deck and used when it's drawn?
Comment: @HaydenHolligan For example you could always remove the first item (`remove(0)`), until the deck is empty. As a separate comment, have you considered using a LinkedList instead of an ArrayList? It has a `removeFirst` and `removeLast` methods and could be more efficient for your use case.
Comment: @Hitman47 i don't really understand where to put that code..
Comment: @HaydenHolligan for testing, i just put it in main() and print out the value of the card, and it works for one card, but after seeing others' comments, i think it is worth checking the times you calling thr PlayerCardDraw() method
Comment: Do you have a stack trace/error message for the new code/error you posted? Again it looks like we're missing some code (e.g. what is `card[cardNum].draw()`?).
Comment: well i'm using slick2d so the draw command renders that to the screen(image stuff in a different part). I didn't mention slick2d because I thought the root of the problem was in my deck or card class which doesn't use slick. card[] is simply an array for images and cardNum is an integer meant for printing that card images in the the right order
Answer: Well looking at your Deck class, You have intialized cards in constructor so there should not be such an exception(as cards size is 52).
But one thing is possible to get an exception which is cards is declared public and you may have modified it outside class directly. So arraylist cards is of size 0 and you get IllegalArgumentException exception for your method Random.nextInt(int).
Make cards private.
If you have withdrawn all cards then size of arraylist would become 0, which may cause an exception. Add check for 0 as :
public Card PlayerCardDraw ()
{
    Random generator = new Random ();
    if(cards.size() > 0) {
        int index = generator.nextInt (cards.size());
        return cards.remove (index);
    } else {
        return null;
    }
}

Comment: this fixed the error i'm having but it's still returning null now; trying to fix it.
Comment: @HaydenHolligan I would suggest you add a print statement to you `playerCardDraw()` method, just for the purpose of debugging. Add `System.out.println("playerCardDraw() was called. There are now " + cards.size() + " cards left in the deck.");` If, as expected, the number of calls to the method is unexpected, also add a line saying `new Exception().printStackTrace(System.out);` Right after the previous debug statement. This way, you can tell from where the method was called.
Answer: You might be calling PlayerCardDraw method even before a card is added to the list. Means cards.size() must be returning a zero. So it is illegal to generate a random int using a zero seed. Hence is the error.
Refer to:
Random.nextInt( n )
Comment: I was thinking the same, but he needs to go through the Deck constructor which initializes the array.
Answer: My guess is that you keep calling PlayerCardDraw more than 52 times.
Each time, a card is removed from the deck, so the 53:d time, you are trying to draw a card from an empty deck (ie. a deck of size 0) which causes generator.nextInt(cards.size()); to throw an exception.
However it is not easy to say.
When you are having problems like this and want help, always show the full stack trace of the exception. Also, since we cannot see line numbers in code on stackoverflow, be sure to indicate in the code exactly at which line the exception occurs.
Comment: I found where that should be happening and I edited my question and posted the code there. It's running a for statement that only runs 4 times, it should reset at 53, not 4 right?


Warning: validateDOMNesting(...):  cannot appear as a descendant of

Question: Olá, estou tentando usar o componente Link do react-router-dom para gerar links em uma tabela de dados, porém, estou enfrentando o seguinte problema:
Warning: validateDOMNesting(...):  cannot appear as a descendant of
O código
function mapStateToProps(state) {
  return {
    pages: state.pages.map((page, index) => {
      let dropdownBtnOpts = [{
        text: 'Editar',
        to: '/admin/pages/' + page._id + '/edit',
        icon: 'edit'
      }, {
        text: 'Excluir',
        icon: 'delete',
        onClick: () => {
          handleDeletePage(page._id)
        }
      }];

      page._id = page._id.toString();
      page.title = page.title;
      page.url = <Link to={page.url}>{page.url}</Link>;
      page.published = page.published;
      page.actions = <DropdownButton state='default' size='small' options={dropdownBtnOpts}>Opções</DropdownButton>;

      return page;
    })
  };
}

O meu problema se econtra na linha:
page.url = <Link to={page.url}>{page.url}</Link>;
O resultado é algo parecido com:

<Link to=''>
<Link to='/url'></Link>
</Link>

Algum esclarecimento será bem vindo, obrigado.
Answer: Tive um problema parecido com este utilizando o Material-UI 1.0-beta. O problema que você está tendo é pelo fato de você estar renderizando uma tag do tipo link () uma dentro da outra, o que é uma inválida marcação HTML e o React dá este warning.
Veja esta parte do teu código:
let dropdownBtnOpts = [{
    text: 'Editar',
    to: '/admin/pages/' + page._id + '/edit',
    icon: 'edit'
  },

e logo abaixo você renderiza o componente DropdownButton que pelo que me parece é um componente que gera Link.
Se você observar, na árvore de componentes gerada que você colocou aqui está a exatamente a marcação HTML problemática:
<Link to=''>
  <Link to='/url'></Link>
</Link>

Como pode ver, aí é um Link dentro do outro e isto é inválido. Para contornar isto, mude o que o tipo de componente mais externo para, por exemplo, uma div.
Então uma saída válida deveria ser:

  <Link to='/url'></Link>


Change var to data-id value with click on button

Question: I have this link:
<a class="PQReport" href="#" data-id="<?php echo $rowA['pq_id']; ?>">

When I click that link I wan't the id of this button to change:
<button class="BorderBtn AskForDelete" id="">Delete</button>

When I click that button I wan't this script to work:
$(document).ready(function(){
    $('.AskForDelete').click(function() {
        var id = $('.AskForDelete').attr('id');
        $.ajax({
          type: 'post',
          url: 'delete.php',
          data: {id:id},
          dataType: 'html',
            success: function(data) {

            }
         });
        return false;
    });
});

The thing is that each link open a popup with that button (all on the same page - so no worries). Instead of making a popupbox for each link I would like to be able to just make 1 popup box that changes values depending of the link that is being clicked on.
I have tried all sorts of things - can't get it to work.
Any advice or pointers?
Thank you.
Comment: Changing id's is generally a bad idea. For example id's must be unique on a page. If you change them based on data your likely going to get the same id on different items. This will break all sorts of things and generally cause weirdness. If your storing data use `data-` attributes, if you want to activate functionality, use `class`es.
Comment: @Liam - Okay, thank you. I will look into that. Unamata's answer is working perfectly - I will modify it, so it changes the data-id instead.
Answer: Capture the click on .PQReport. Take it's data-id and put it in .AskForDelete's id. For example:

$(document).ready(function(){

$('.PQReport').click(function(e){
e.preventDefault();
    $('.AskForDelete').attr('id', $(this).data('id'))
})

    $('.AskForDelete').click(function(e) {
        e.preventDefault();
        var id = $('.AskForDelete').attr('id');

        console.log(id);
        $.ajax({
          type: 'post',
          url: 'delete.php',
          data: {id:id},
          dataType: 'html',
            success: function(data) {

            }
         });
        return false;
    });

});

<a class="PQReport" href="#" data-id="<?php echo $rowA['pq_id']; ?>">CLICK ME

<button class="BorderBtn AskForDelete" id="">Delete</button>
Comment: Happy to help! Remember, always experiment! :)
Comment: Perfect! This works. I didn't even think about it like that. Thank you very very much!


Booting with PXE over VLANs using Packetfilterrules in the Firewall

Question: we´ve recently setup multiple (4) VLANs on ProCurve 2510G Switches and one Astaro v8.301 Gateway. We´ll have one PXE Server on VLAN 400 and Nodes to boot to PXE on VLAN 100, 200 and 300.
I would like to create a DHCPd on the Astaro Node pointing to the PXE Server and using Paketfilterrules to transport the Traffic over the VLAN-Borders.
Is this possible?
Answer: Okay i managed it by myself but want to tell you the answers for that.
So its possible.
In the latest ASG v9 you can easily activate the TFTP filename and next-server DHCP Options. in 8.3 you need to do this manually by logging into the ASG via SSH and root (trough loginuser first).
Once youre root, execute the following commands "cc"->"OBJS"->"dhcp"->"server"->"REF..." which is the DHCP Server you wanna add the options.
then modify the following command to fit your needs and type them (but leave first and last ")
"custom = "filename \"pxelinux.0\";\nnext-server 10.10.10.4;""
this will add the filename and next-server options using the custom-options method.
then "w" to write the config via the ASGs MiddleWare and then "exit" to leave the Confd "cc".
done.
now you can easily create paketfilterrules like u normally did but also for PXE booting (TFTP at least) but you can figure this out by watching the live log while trying to PXE boot.


Como evitar o envio de requisições PHP seguidas?

Question: Bom, a situação é a seguinte existem alguns formulários em meu website. Esses formulários estão programados para disparar e-mails, utilizando a classe PHPMailer. O que acontece é o seguinte, se a pagina demora um pouco para responder o usuário fica clicando muitas vezes no botão enviar, o que gera vários disparos de e-mails duplicados. Existe uma maneira de evitar que ocorra tantas requisições?
Comment: sim, você pode simplesmente bloquear o botão logo apos o usuário clicar nele, bloquear que eu falo é dar um `disable`
Comment: Apesar desta ser sobre email, e a outra sobre inserção de DB, a grande maioria das respostas da outra tem solução que serve para qualquer envio repetido, em especial o redirect (e o PHPMailer não tem relação nenhuma com o problema, apesar de estar nas tags).
Answer: Você pode usar JavaScript para desabilitar o botão
assim que seja clicado uma vez,
assim o usuário não poderá fazer várias requisições
se estiver com JavaScript ativado,
o que é o caso da maioria,
mas ai depende do tipo de usuários do seu sistema:
Exemplo de botão de submit que se desabilita sozinho:
<input type="submit" onclick="this.disabled = true; this.value = 'Enviando…'; this.form.submit();" value="Enviar">

Exemplo no JSFiddle
Comment: @CesarAndré, "se validarmos de alguma forma" já é [*uma outra pergunta*](http://pt.stackoverflow.com/questions/ask) ;) Muito elegante a solução, Miguel! Um detalhe, precisei incluir um `form.submit()` pro envio do formulário poder funcionar: **`onclick="this.disabled=true; this.value='Enviando...'; this.form.submit(); return true;"`**
Comment: Vale a pena também adicionar em alguma parte do layout um aviso do tipo: 'Aguarde alguns instantes, seu email já está sendo enviado!' =)
Comment: Você pode fazer uma função em JS para validar seu formulário e coloca-la no evento onsubmit deste. Nesta função você aproveita para verificar o(s) campo(s) e, de acordo com a necessidade, habilitar ou desabilitar o botão...
Comment: O problema é que se validarmos de alguma forma o formulario, o botao vai ficar desabilitado...
Comment: @brasofilo: boa observação, vou alterar a resposta para refletir isso. Obrigado!
Answer: Uma maneira eficiente de evitar multiplas requisições desnecessarias seguidas é utilizar um serviço de captcha, assim a requisição só é feita uma vez e depois que o usuário enviar o captcha, isso evita a multiplas requisições e também o problema de possíveis spams.
Porém captcha acaba deixando o envio do formulário mais lento para o usuário (o que é desagradavel), então uma solução que me vem em mente é a seguinte:
Você pode armazenar em uma session o tempo exato em que a ultima requisição foi feita, e estabelecer um limite minimo de tempo para realizar uma nova ação.
Você também pode desabilitar o botão de envio com o atributo disabled utilizando javascript, isso vai causar um efeito mais agradável embora possa ocorrer o caso de o usuário estar com o javascript desabilitado.
O script abaixo pode ajudar:
$('form').on('submit', function() {

    $(this).find('[type="submit"]').attr('disabled', 'disabled');

});


Has many to many checkboxes won't save Rails 4

Question: I've tried making my has and belongs to many relation to work, following the Rails guides and everything I could find online, but they just wont show up.. When I save my form its only INSERTS into the Pin model, it doesn't insert any relations. If I add the relation manually via terminal like so:
p = Pin.new
p.minors = [1,2]
p.save

It works, but my form which looks like this (iam using rails 4, so collections yay) it doesn't save the relations (it saves the pin just fine)
new.html.erb
  <%= collection_check_boxes(:minor_ids, :minor_ids, Minor.all, :id, :name) %>
  <%= collection_check_boxes(:competence_ids, :competence_ids, Competence.all, :id, :name) %>

pinscontroller.rb
class PinsController < ApplicationController

 def create
  @pin = Pin.new(pin_params)
  @pin.user_id = current_user.id

  if @pin.save
    redirect_to pin_path(@pin)
  end
 end

def new
 @pin = Pin.new()
end

def show
 @pin = Pin.find(params[:id])
end

private
def pin_params
 params.require(:pin).permit(:title, :name, :url, { :minor_ids => [] }, { :competence_ids => [] },)
end

end
and my model Pin.rb
 class Pin < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :minors
has_and_belongs_to_many :competences
 end

Minor.rb
 class Minor < ActiveRecord::Base
has_and_belongs_to_many :pins
 end

Competence.rb
 class Competence < ActiveRecord::Base
  has_and_belongs_to_many :pins
 end

pin/show.html.erb
This is the way I try to check if the relations came through. They all come back empty and 0, except for the ones I did through console.
<%=  @pin.minors.count.inspect %>
<%=  @pin.competences.count.inspect %>

<% if !@pin.minors.empty? %>
<%= @pin.minors.each do |minor| %>
  <%= minor.name %>
<% end %>
<% end %>

<% if !@pin.competences.empty? %>
<%= @pin.competences.each do |comp| %>
  <%= comp.name %>
<% end %>
<% end %>

Schema.rb
create_table "competences", force: true do |t|
 t.string   "name"
 t.datetime "created_at"
 t.datetime "updated_at"
 t.integer  "pin_id"
end

create_table "competences_pins", force: true do |t|
 t.integer  "pin_id"
 t.integer  "competence_id"
 t.datetime "created_at"
 t.datetime "updated_at"
end

create_table "minors", force: true do |t|
 t.string   "name"
 t.datetime "created_at"
 t.datetime "updated_at"
 t.integer  "pin_id"
end

create_table "minors_pins", force: true do |t|
 t.integer  "pin_id"
 t.integer  "minor_id"
 t.datetime "created_at"
 t.datetime "updated_at"
end

create_table "pins", force: true do |t|
 t.string   "title"
 t.string   "url"
 t.string   "image"
 t.string   "username"
 t.integer  "views"
 t.datetime "created_at"
 t.datetime "updated_at"
 t.integer  "user_id"
end

So, am I missing a step? So far i've tried everything but the minors_pins and the competences_pins tables remain empty, all the help and insight I can get!
Answer: I fixed this by adding @minors = Minor.all in the pins controller in the new method. And by replacing <%= collection_check_boxes(:minor_ids, :minor_ids, Minor.all, :id, :name) %> with   <%= f.collection_check_boxes(:minor_ids, @minors, :id,:name)%>


Como obter o TimeStamp em Javascript?

Question: Gostaria de sabe como faço em JavaScript para obter o Timestamp? Um número que representa a data e hora atual. Sei que conseguimos o objeto para data e hora através de:
var d = new Date();

Mas não sei como prosseguir a partir dai.
Comment: O que seria esse `Timestamp`? Lembre-se que sistemas diferentes possuem maneiras diferentes de representar uma data por um número. Um dos mas conhecidos é o "Unix time" (com 32 ou 64 bits), mas existem outros (Python por exemplo utiliza um `float` em vez de um inteiro). Verifique se o formato usado pelo JavaScript é o mesmo que você precisa para sua aplicação. E, se aplicável, não se esqueça de prestar atenção no fuso horário.
Answer: Você pode usar o getTime() do objeto Date:
// Pegar do horário atual
var timestamp = new Date().getTime();

// Pegar de uma data específica
var timestamp = new Date(2013, 11, 17).getTime();

Mas atenção porque essa data/hora é fornecida pelo sistema operacional do cliente, se você precisar de alguma segurança ou a informação for para a base, use algum método na sua aplicação no servidor(back-end).
UPDATE:
Um detalhe importante que passou despercebido por mim - e parece que por todos - é que o parâmetro month do construtor do objeto Date é indexado por zero(zero-indexed), ou seja, começa a contar a partir do zero, então: 0 = Janeiro e 11 = Dezembro. No exemplo acima, usei o número 12 para extrair a data de hoje(17/12/13) porém como Dezembro é 11, o resultado do exemplo é Fri Jan 17 2014 00:00:00 GMT-0200 (Horário brasileiro de verão), ou seja, Janeiro, pois ele joga a data pra frente - ou para trás - fazendo o cálculo. Mas isso é uma outra história.
Comment: +1 pela observação sobre o mês. Isso sempre acontece em Javascript e também em Java. Porém eu sugiro editar a questão e não deixar o 12 em cima, pois um leitor apressado pode copiar o código e não ler a atualização.
Comment: @utluiz as respostas que não citam essa observação merecem upvote já que podem reproduzir um resultado errado?
Comment: @utluiz boa idéia, alterei o código.
Comment: @durtto No vejo problema. Ter uma informação a mais é bom, mas não totalmente necessário, a menos que é claro, que isto faça a resposta errada ou leve o leitor ao erro.
Comment: utluiz eu particularmente faria o que você disse acima. rs rs
Answer: Como todos disseram:
new Date().getTime()

Ou então ainda mais simples:
Date.now()

Answer: Só para constar uma outra maneira, além dos mencionados:
+new Date
Answer: Você pode usar
new Date().getTime();

Answer: Com javascript puro é possivel pegar o timestamp assim:
console.log(new Date().getTime());
//ou
alert(new Date().getTime());

Answer: Curto e grosso:
+ new Date()

Um operador + dispara o método valueOf no objeto Date e retorna o timestamp (sem qualquer alteração).
Detalhes:
Em quase todos os navegadores atuais, você pode usar Date.now() para obter o UTC timestamp em milissegundos; uma exceção notável é o IE8 e anterior (veja tabela de compatibilidade).
Para obter o timestamp em segundos, você pode usar:
Math.floor(Date.now() / 1000)

Ou, alternativamente, você poderia usar:
Date.now() / 1000 | 0

Que deve ser ligeiramente mais rápido, mas também menos legível (veja também esta resposta).
Eu recomendaria usar Date.now () (com correção de compatibilidade). É um pouco melhor porque é mais curto e não cria um novo objeto Date. No entanto, se você não quiser uma correção && compatibilidade máxima, poderá usar o método "antigo" para obter o registro de timestamp em milissegundos:
new Date().getTime()

Que você pode então converter para segundos como este:
Math.round(new Date().getTime()/1000)

E você também pode usar o método valueOf que mostramos em baixo:
new Date().valueOf()

Timestamp em milissegundos

var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();

console.log(timeStampInMs, Date.now());
Answer: Em um exercício de um curso eu preciso colocar o relógio na tela, a solução que deu certo para mim foi a seguinte:
HTML
 //na TAG  coloquei a função que será chamada no JS
.

 A hora será exibida aqui...

.

JavaScript
function carregar() { /*no script chamei a função declarada na TAG */
    var data = new Date;  /*objeto Date foi instanciado na variável data*/
    var h = data.getHours();  /*variável h recebe valor de parâmetro para pegar
                               as horas*/
    var m = data.getMinutes(); /*variável m recebe valor de parâmetro para pegar
                               os minutos*/
    var s = data.getSeconds(); /*variável s recebe valor de parâmetro para pegar
                               os segundos*/
    var hora_atual = h+ ':' +m+ ':' +s; /*variável hora_atual recebe os valores
                                        concatenados das variáveis h m s */
    p.innerHTML = `Hora atual: ${hora_atual}`; /* elemento HTML
 é
                                                modificado*/
    setInterval('carregar()', 1000); /*comando para chamar a função dentro de um
                                       intervalo de tempo, 1000 é igual a 1
                                       segundo */
    }

Como obter o TimeStamp em Javascript?


iptable rule for an IP address with "any" subnet mask

Question: I have a requirement to add an iptable rule for lets say src IP 10.10.10.20/any dest IP any.
iptables -t filter -A FORWARD_0_IN -p all --ipv4 --source 10.10.10.1/any --destination 10.10.10.2/any  -j DROP

Above command fails with error:
iptables v1.8.6 (legacy): invalid mask `any' specified
This /any implies all possible subnet masks /0 to /32.
I want to avoid adding individual 33 rules for each subnet mask.
What is a better way to achieve this ?
Till then let me get it clarified from requirements team, what is expectation with /any.
Comment: Why would you want to add all masks? The mask `/0` means any address so it covers all other masks.
Comment: Yes, even I thought so, /0 would mean any IP. Let me get the requirement clear from my Team.
Comment: Just simple **ommiting** `--source b.l.a.h` would mean "any IP", e.g. the same thing as /0 mask.
Answer:
I want to avoid adding individual 33 rules for each subnet mask.

It is very unlikely that you would ever need to that. And I think you don't quite understand what a subnet mask means or effects.
A very long Q&A is this one: How does IPv4 Subnetting Work?
But very simplified:
When you add an  IPv4 IP-address without any subnet subnet mask or with an /32 subnet mask that means "this particular IP-address".
When you use an IPv4 IP-address with any other subnet mask than /32  that means: "the CIDR subnet range that includes this IP-address".
In other words 10.10.10.1/24 means: "the /24 subnet range that includes 10.10.10.1"
i.e. the subnet ranging from 10.10.10.0 to 10.10.10.255  which is more commonly specified as 10.10.10.0/24
Subsequently  10.10.10.1/8 means: "the /8 range that includes 10.10.10.1"
i.e. the subnet ranging from 10.0.0.0 to 10.255.255.255  ; which is normally specified as 10.0.0.0/8 but 10.10.10.1/8 is equivalent.
Note that such a range includes 10.10.10.1/9 , 10.10.10.1/10 , 10.10.10.1/11  .... and all subnets until 10.10.10.1/32
And 10.10.10.1/0 means: "the /0 range that includes 10.10.10.1"   - that is the range from 0.0.0.0 to 255.255.255.255 or in other words  any IPv4 address.
Comment: This is very strange "clarification", because /32 in context of a firewall means "to match a single host". I can't imagine any circumstances of how "all" might appear there in this meaning, other than blatant incompetence.
Comment: Yes, I know about subnet masks, and I too am confused with /any requirement. Let me get it clarified from my requirements team. I thought /any is some standard term used in the industry and has some special meaning.
Comment: I got it clarified, they meant /any = /32.
Answer: IP address doesn't have a property of a "subnet mask". (It had, in the distant past of classful addressing, but these times are long long gone — more than 30 years ago, with the inception of a CIDR. You should forget about that and pretend this never was the case. Also, the rest of the answer is still valid even in case of classful addressing).
So, IP address is just 32 bits number and by seeing just an IP address you can't tell what mask it was configured with on the system where it is assigned. The mask has some meaning to that system only — it is meant to tell that system which addresses are reachable "immediately" and which ones it needs to access through the gateway. Netmask is a routing feature; the only effect it has is to define certain "connected"-type route.
It is meaningless requirement to "allow certain IP with any mask".

Probably this notation in your requirement was meant to be not a mask, but a port number? Then it needs a L4 protocol to be specified (TCP, UDP, etc.) which has a concept of port numbers. Or, this could have been a protocol itself, meaning "any" IP protocol number from that host should be permitted.


What does `aws configure` actually do?

Question: It's important to understand from a security standpoint what aws configure actually does behind the scenes. Having read the docs, I'm still not clear on this.
We have chosen to move the credentials file to a more secure location on our server, i.e. not in the default %USERPROFILE%\.aws\credentials location. I set the environment variable, AWS_SHARED_CREDENTIALS_FILE, for this secure location and run aws configure. Everything seems to work and I am able to use the AWS cli with the access keys provided.
Unfortunately however, I can't be clear on whether aws configure has compromised the security of the credentials in some way. For example, by simply moving the file to a non-secure location...
Comment: Install `auditd`, set it up to monitor file system calls and run `aws` then open logs and investigate
Comment: Thanks for the suggestion @RomeoNinov. I think it's a good idea. I'm actually trying a similar thing with `strace`, the output of which is ~13k lines. I'm not sure it's really the answer though as I can observe I/O operations but without knowing the implementation I don't really know what's going on, e.g. what is the contents of files being written... Perhaps auditd will be a bit clearer.
Comment: Also, I should say that this is for a windows application so neither `auditd` or `strace` will necessarily help with what's going on in windows
Answer: "aws configure" simple creates the credential file for you on your workstation or server in the file %USERPROFILE%\.aws\credentials. You type the credentials in, it puts them into the file on the local server. As far as I know it doesn't do anything else with the credentials.
You can edit it directly to do exactly the same thing. It's a regular file, holding AWS access key and secret keys.
In terms of security, having your credentials stored in a file on a workstation / server unencrypted isn't ideal. If your computer gets a virus or ransomware they could be lost or stolen. If this ever happens you should remove those keys in the AWS console and issue new keys once your machine is sufficiently secure again.
IMHO the risk is worthwhile if you need to use the AWS CLI, so long as your machine has good security practices. Basics like a firewall, virus / malware scanner, etc.
Comment: Thanks for your answer. I'm not 100% sure this is correct however. What I'm talking about is keeping the credentials file in a non-default location and setting that location as the environment variable `AWS_SHARED_CREDENTIALS_FILE` then running `aws configure`, this pattern is explained (here)[https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html]. I do agree that the docs would suggest `aws configure` creates the file at `%USERPROFILE%\.aws\credentials`, but having run the pattern above and checked, I can confirm there is no `%USERPROFILE%\.aws\` folder created.
Comment: Behaviour of this command is confusing. I tested by writing the credentials and config files to %USERPROFILE%\.aws\ : I am able to use the keys without needing to run `aws configure`, confirming what you suggest. I have also tested by running `aws configure` and entering the details on prompt. This creates credentials files at the default location. Again, confirming what you suggest. However, when using environment variables to outline non default locations for the files, and then running `aws configure`, `%USERPROFILE%\.aws` is not created, despite the CLI picking up the details correctly.
Comment: Ah. I will edit your question slightly to make it more clear what you're asking.
Comment: The AWS CLI is just reading the contents of the file. I suspect you're over thinking this.
Comment: Thanks Tim. But `aws configure` must be doing something: using cli doesn't work without first running `aws configure` (when putting credentials file in a non-default location). You say "the AWS CLI is just reading the contents of the file", but if this were the case, then it should be able to simply read the environment variables at the point of calling, for example `aws s3 ls`, i.e. it should work without first running `aws configure`. Do you see what I mean? Or am I missing something here?
Comment: Thanks for your help @Tim. Think I got to the bottom of this one, prompted by your help. See my answer above.
Answer: aws configure actually isn't required when using non-default locations for credentials and configurations files. If the file locations for these files are set correctly in the environment variables, AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE respectively, then the aws cli knows where to look for the credentials and configuration. I therefore do not need to worry about any security issues relating to aws configure.

What does `aws configure` actually do?


Database - Data Versioning (followup)

Question: My original question can be found here, for which I've gotten some great answers, idas and tips.
As part of a feasibility and performance study, I've started to convert my schemas in order to version my data using those ideas. In doing so, I've come up with some kind of other problem.
In my original question, my example was simple, with no real relational references. In an attempt to preserve the example of my previous question, I will now extend the 'Name' part to another table.
So now, my data becomes:
Person
------------------------------------------------
ID                UINT NOT NULL,
NameID            UINT NOT NULL,
DOB               DATE NOT NULL,
Email             VARCHAR(100) NOT NULL

PersonAudit
------------------------------------------------
ID                UINT NOT NULL,
NameID            UINT NOT NULL,
DOB               DATE NOT NULL,
Email             VARCHAR(100) NOT NULL,
UserID            UINT NOT NULL,         -- Who
PersonID          UINT NOT NULL,         -- What
AffectedOn        DATE NOT NULL,         -- When
Comment           VARCHAR(500) NOT NULL  -- Why

Name
------------------------------------------------
ID                UINT NOT NULL,
FirstName         VARCHAR(200) NOT NULL,
LastName          VARCHAR(200) NOT NULL,
NickName          VARCHAR(200) NOT NULL

NameAudit
------------------------------------------------
ID                UINT NOT NULL,
FirstName         VARCHAR(200) NOT NULL,
LastName          VARCHAR(200) NOT NULL,
NickName          VARCHAR(200) NOT NULL,
UserID            UINT NOT NULL,         -- Who
NameID            UINT NOT NULL,         -- What
AffectedOn        DATE NOT NULL,         -- When
Comment           VARCHAR(500) NOT NULL  -- Why

In a GUI, we could see the following form:
ID            :  89213483
First Name    :  Firsty
Last Name     :  Lasty
Nick Name     :  Nicky
Date of Birth :  January 20th, 2005
Email Address :  email@example.com

A change can be made to:

Only to the 'name' part
Only to the 'person' part
To both the 'name' and person parts

If '1' occurs, we copy the original record to NameAudit and update our Name record with the changes.  Since the person reference to the name is still the same, no changes to Person or PersonAudit are required.
If '2' occurs, we copy the original record to PersonAudit and update the Person record with the changes.  Since the name part has not changed, no changes to Name or NameAudit are required.
If '3' occurs, we update our database according to the two methods above.
If we were to make 100 changes to both the person and name parts, one problem occurs when you later try to show a history of changes.  All my changes show the person having the last version of the name. Which is wrong obviously.
In order to fix this, it would seem that the NameID field in Person should reference the NameAudit instead (but only if Name has changes).
And it is this conditional logic that starts complicating things.
I would be curious to find out if anyone has had this kind of problem before with their database and what kind of solution was applied?
Comment: I know this thread is several years old, but can you tell us what solution you ended up implementing?
Answer: You should probably try to read about 'Temporal Database' handling. Two books you could look at are Darwen, Date and Lorentzos "Temporal Data and the Relational Model" and (at a radically different extreme) "Developing Time-Oriented Database Applications in SQL", Richard T. Snodgrass, Morgan Kaufmann Publishers, Inc., San Francisco, July, 1999, 504+xxiii pages, ISBN 1-55860-436-7. That is out of print but available as PDF on his web site at cs.arizona.edu.  You can also look for "Allen's Relations" for intervals - they may be helpful to you.

I assume that the DATE type in your database includes time (so you probably use Oracle).  The SQL standard type would probably be TIMESTAMP with some number of fractional digits for sub-second resolution.  If your DBMS does not include time with DATE, then you face a difficult problem deciding how to handle multiple changes in a single day.
What you need to show, presumably, is a history of the changes in either table, with the corresponding values from the other table that were in force at the time when the changes were made.  You also need to decide whether what you are showing is the before or after image; presumably, again, the after image.  That means that you will have a 'sequenced' query (Snodgrass's term), with columns like:
Start time        -- When this set of values became valid
End time          -- When this set of values became invalid
PersonID          -- Person.ID (or PersonAudit.ID) for Person data
NameID            -- Name.ID (or NameAudit.ID) for Name data
DOB               -- Date of Birth recorded while data was valid
Email             -- Email address recorded while data was valid
FirstName         -- FirstName recorded while data was valid
LastName          -- LastName recorded while data was valid
NickName          -- NickName recorded while data was valid

I assume that once a Person.ID is established, it does not change; ditto for Name.ID.   That means that they remain valid while the records do.
One of the hard parts in this is establishing the correct set of 'start time' and 'end time' values, since transitions could occur in either table (or both).  I'm not even sure, at the moment, that you have all the data you need.  When a new record is inserted, you don't capture the time it becomes valid (there is nothing in the XYZAudit table when you insert a new record, is there?).

There's a lot more could be said.  Before going further, though, I'd rather have some feedback about some of the issues raised so far.

Some other SO questions that might help:

Data structure for non-overlapping ranges within a single dimension
Why do we need a temporal database
Determine whether two date ranges overlap
Best relational database representation of time-bound hierarchies

Since this answer was first written, there's another book published about another set of methods called 'Asserted Versioning' for handling temporal data.  The book is 'Managing Time in Relational Databases: How to Design, Update and Query Temporal Data' by Tom Johnston and Randall Weiss.  You can find their company at AssertedVersioning.com.  Beware: there may be patent issues around the mechanism.
Also, the SQL 2011 standard (ISO/IEC 9075:2011, in a number of parts) has been published.  It includes some temporal data support.  You can find out more about that and other issues related to temporal data at TemporalData.com, which is more of a general information site rather than one with a particular product axe to grind.
Comment: Thanks for the references, I look forward to exploring those!

As for the DATE type, I'm currently using MySQL for my tests.  I have written my SQL examples in some sort of pseudocode (due to my limited database knowledge).  When using DATE, I meant it to mean date/time.  Sorry about the informal SQL syntax.  Same goes with UINT, it was meant as an unsigned integer.
Comment: When a new record is inserted, you don't capture the time it becomes valid (there is nothing in the XYZAudit table when you insert a new record, is there?).

Yes, I use the 'AffectedOn' to track the modification dates.
Comment: I'm kinda starting to understand the idea behind 'temporal databases'.  In your answer above, you have a 'start time' and 'end time'.  Can you give me an added benefit of maintaining these values?  I could also use a boolean 'isActive' variable in order to indicate which records are valid and invalid.
Comment: @Jeach: so, do you insert into the audit table on all non-retrieval DML operations?  If so, then you only need to look at the audit table to get the history - and the non-audit table to get the current version (but that's an optimization since the current version of the info is also in the audit table).
Comment: The advantage of a start time and end time in a single record is that you tell the range of validity of the record without looking at any other record.  As soon as you drop one of those two, you have to look at the prior or next record to find the data, and that - believe me - makes the SQL harder.  (It ain't easy to start with; you don't need it to be any harder.)
Comment: I do like your proposal of 'start time' and 'end time', since this would also allow me to perform queries like: "Give me all the updates performed in 2008".  But how would one go about obtaining the CURRENT record?  "Give me the record where EndTime = INFINITY"?  Is that the only difference between the old records and the current record?
Comment: Both references discuss different ways of organizing temporal data.  One way of representing the current record is with an end time of NULL (usually a bad choice); another uses 'end of time' or 'doomsday' (e.g. 9999-12-31 23:59:59) which is generally better.  A third way, recommended by DD&L in TDRM (ref 1) is two tables - one for the current values (including the time when the record became valid but no explicit end time), and the other for historic values (which include start and end time).  Your table design is closest to that but missing a key ingredient (start time in current table).
Comment: The two table design runs into issues with future data - what happens when you schedule something to end at a time in the future (e.g. validity of a digital certificate).  Since there is a known end point, does it appear in the current data or the historical data?  Can you have current data in the historic table?  DD&L discuss this extensively.  I don't recall Snodgrass doing so, but it is a while since I last read that book (and it is not all easy going, either - neither book is a light read).
Comment: It's probably time to start transferring some of these comments into the 'answer'.  It's also time to get on with some real work, boo hiss! :(  :D
Answer: Keep a single changes table with an autoincrement ID and make all your changes to refer to that table.
Always put the original record to the audit table.
To build a history, select all your changes and show the value closest to the change.
Like this:

`Change`

1
2
3
4
5
6

`NameAudit`

1 - created as John Smith
5 - changed to James Smith

`PersonAudit`

1 - created as born on `01.01.1980` in `Seattle, WA`
2 - changed DOB to '01.01.1980`
3 - changed DOB to '02.01.1980`
4 - changed DOB to '02.01.1980`
6 - changes POB to `Washington, DC`

Then select:
SELECT  c.id,
        (
        SELECT   MAX(id)
        FROM     NameAudit na
        WHER     na.id <= c.id
        ) as nameVersion,
        (
        SELECT   MAX(id)
        FROM     PersonAudit pa
        WHER     pa.id <= c.id
        ) as personVersion,
        na.*,
        pa.*
FROM    change c
JOIN    NameAudit na
ON      na.id = nameVersion
JOIN    PersonAudit pa
ON      pa.id = nameVersion
WHERE   change_id BETWEEN 1 AND 6

Database - Data Versioning (followup)


ExecuteCommand throwing "The method or operation is not implemented" exception

Question: In WIA, ExecuteCommand is getting exception:
The method or operation is not implemented

Code:
WIA.CommonDialog dialog = new WIA.CommonDialog();
WIA.Device camera = dialog.ShowSelectDevice(WIA.WiaDeviceType.CameraDeviceType, false, true);
WIA.Item takenItem = camera.ExecuteCommand("{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}");

Any help.....?
Answer: if you are getting error you have maybe unsuitable camera. Microsoft canceled WIA library many years ago and newest digital cameras do not support WIA protocol.
Here is a short list of suitable cameras:
Digital IXUS 430
Digital IXUS 500
Digital IXUS IIs
PowerShot A310
PowerShot A400
PowerShot A75
PowerShot A85
PowerShot A95
PowerShot Pro1
PowerShot S1 IS
PowerShot S60
and also (maybe):
Agfa ePhoto 307
Agfa ePhoto 780
Agfa ePhoto 1280
Agfa ePhoto 1680
Canon PowerShot A5
Canon PowerShot A5 Zoom
Canon PowerShot Pro70
Casio QV 10
Casio QV 10A
Casio QV 11
Casio QV 30
Casio QV 70
Casio QV 100
Casio QV 120
Casio QV 200
Casio QV 300
Casio QV 700
Casio QV 770
Casio QV 5000SX
Casio QV-770 (IrTran-P)
Casio QV-5000SX (IrTran-P)
Casio QV-7000SX (IrTran-P)
Epson PhotoPC / CP-100
Epson PhotoPC 500 / CP-200
Epson PhotoPC 600 / CP-500
Epson PhotoPC 700 / CP-600
Epson PhotoPC 750Z / CP-700Z
FujiFilm DX-5/DS-10
FujiFilm DX-7/DS-20
FujiFilm DX-9/DS-30
FujiFilm MX-700
FujiFilm DS-300
HP PhotoSmart C20
HP PhotoSmart C30
HP PhotoSmart C200
JVC GCS1 (IrTran-P)
Kodak DC200
Kodak DC210
Kodak DC215
Kodak DC220 (USB only)
Kodak DC260 (USB only)
Kodak DC265 (USB only)
Kodak DC290 (USB only)
Kodak DC240 (USB only)
Kodak DC280 (USB only)
Konica Q-M100
Konica Q-M100V
Minolta Dimage V
Nikon CoolPix 900
Nikon CoolPix 950
Nikon CoolPix 700
Olympus D-200L
Olympus D-220L
Olympus D-300L
Olympus D-320L
Olympus D-340L
Olympus D-340R
Olympus D-500L
Olympus D-600L
Olympus D-400Z
Sanyo DSC-V1/VPC-G200
Sanyo DSC-X1/VPC-X300
Sharp VE-LC2 (IrTran-P)
Sony DSC-F3 (IrTran-P)
UMAX AstraCam (USB)
UMAX AstraCam 1000 (USB)

Newest digital cameras such as Canon IXUS 162,170,180 etc. does NOT support WIA protocol. If you are looking for a replacement of the old "take a picture" WIA 1.x/2.x command: {AF933CAC-ACAD-11D2-A093-00C04F72DC3C} , the suitable way is Canon EOS series and CanonSDK library.
jerry


How do I render the 'user_picture' of a user account?

Question: I load a user object, and I would like to be able to show the user's picture somewhere. I tried the following code.
$row_user = \Drupal\user\Entity\User::load($uid)->user_picture->first()->view('large');

What I get is this (using kint()).

This user has a picture and it is shown correctly in the user page.
How do I exactly show the picture associated with a user account?
Answer: Just like every other render array, render it.
If you print it out in twig, that just works, in PHP, use \Drupal::service('renderer')->render().
Comment: Thanks. I was wondering why `#url => NULL` because I would like to get the URL to the image.
Comment: large is a user view mode, not an image style. You can create and configure the field there to show a link. Or pass an array with configuration to it, same structure as stored in view displays


Ugly Differentiation

Question: If $$y=\frac{ax^2}{(x-a)(x-b)(x-c)} + \frac{bx}{(x-b)(x-c)}+\frac{c}{x-c}+1$$
Then prove that $$\frac{dy}{dx}=\frac{y}{x}(\frac{a}{a-x}+\frac{b}{b-x}+\frac{c}{c-x})$$
What is the smartest way to solve this?
Comment: May be to solve the ODE...
Comment: But I don't think that reverse engineering will be appreciated in exam...
Comment: $$x-c$$ Should be there in first line .
Comment: yup a typing error occurred.
Answer: HINT:
$$\dfrac c{x-c}+1=\dfrac x{x-c}$$
$$\dfrac{bx}{(x-b)(x-c)}+\dfrac x{x-c}=x\cdot\dfrac{b+(x-b)}{(x-b)(x-c)}=\dfrac{x^2}{(x-b)(x-c)}$$
$$\frac{ax^2}{(x-a)(x-b)(x-c)}+\dfrac{x^2}{(x-b)(x-c)}=x^2\cdot\frac{a+(x-a)}{(x-a)(x-b)(x-c)}=\dfrac{x^3}{(x-a)(x-b)(x-c)}$$
Now take logarithm in both sides and differentiate
Answer: HINT:
Use Partial Fraction Decomposition,
$$\frac{ax^2}{(x-a)(x-b)(x-c)} + \frac{bx}{(x-b)(x-c)}+\frac{c}{c-x}=\dfrac A{x-a}+\dfrac B{x-b}+\dfrac C{x-c}$$
$$\implies ax^2+bx(x-a)+c(x-a)(x-b)=A(x-b)(x-c)+B(x-c)(x-a)+C(x-a)(x-b)$$
Compare the constants and the coefficients of $x,x^2$ to find $A,B,C$

Ugly Differentiation


Enable a button basing on multiple form values being equal

Question: I would not like users to be able to submit a form until:

All fields are filled out
The password and confirm password fields are equal

I can do this with JavaScript, potentially, but then the JavaScript code would managing some states and the PHP code would manage other states. It seems messy.
This is the code I wrote.
'disabled' => array(
// disable button if missing required fields
        array(
          ':input[name="field1"]' => array('value' => ''),
        ),
        array(
          ':input[name="field2"]' => array('value' => ''),
        ),
        array(
          ':input[name="password"]' => array('value' => ''),
        ),
        array(
          ':input[name="confirm_password"]' => array('value' => ''),
        ),
      ),

      // only enable the button when passwords are ==
'enabled' => array(
        array(
          ':input[name="password"]' => array('value' => ':input[name="confirm_password"]')
        )
      )

Answer: 'array('value' => ':input[name="confirm_password"]')

This means the value equals the literal string ":input[name="confirm_password"]".
As far as I know, #states can't check if the value of two fields are the same.

I can do this with JavaScript, potentially, but then the JavaScript
  code would managing some states and the PHP code would manage other
  states. It seems messy.

Here is a way that may seem less messy. Use a hidden compare_passwords field whose value will indicate whether the password and confirm_password fields have the same value:
$form['compare_passwords'] = array('#type' => 'hidden', '#default_value' => 'fail');

Use the value of that field in the #states array for your button.
':input[name="compare_passwords"]' => array('value' => 'match')

Write some JavaScript that changes the value of compare_passwords whenever the value of password or confirm_password changes (use .on() instead of bind() if your site uses jQuery 1.7+):
var password_selector = ':input[name="password"]';
var confirm_selector = ':input[name="confirm_password"]';
var compare_selector = ':input[name="compare_passwords"]';
$(password_selector + ',' + confirm_selector).bind("change paste keyup blur", function () {
  if ($(password_selector).val() == $(confirm_selector).val()) {
    $(compare_selector).val('match').change();
  } else {
    $(compare_selector).val('fail').change();
  }
});

By the way, you can use '!value' to put all your "does not equal empty string" conditions under "enabled", using the Boolean "AND" structure. The Boolean "OR" structure, which is wrapping each condition in its own array, is harder to understand if you aren't familiar with #states.
// Only enable the button when all fields have a value and passwords match.
// The value in "compare_passwords" is dynamically updated by my_script.js
//  whenever the user types inside the password or compare_password fields.
$form['my_button']['#states'] = array(
  'enabled' => array(
    ':input[name="field1"]' => array('!value' => ''),
    ':input[name="field2"]' => array('!value' => ''),
    ':input[name="password"]' => array('!value' => ''),
    ':input[name="confirm_password"]' => array('!value' => ''),
    ':input[name="compare_passwords"]' => array('value' => 'match'),
  ),
);

Comment: Thanks. I feel the same about the API. In fact, the documentation for [drupal_process_states](https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_process_states/7.x) mentions that there are some states that are not fully implemented. For example the `valid` and `invalid` states combined with a [password_confirm field](https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#password_confirm) looked promising, but it doesn't look like `valid` has been implemented for `#states` (turns out the `password_confirm` field doesn't implement it either).
Comment: Thats a clever approach. Having dynamic values only on the left side of a bool like field feels like an incomplete api to me, but thanks for the tip on how to handle it.


Showing a function of random walk is a martingale

Question: I would like a hint for the following problem:

Consider a biased random walk on the integers with probability $p<1/2$ of moving to the right and probability $1-p$ of moving to the left.  Let $S_n$ be the value at time $n$ and assume that $S_0=a$, where $0<a<N$. Show that $M_n=[(1-p)/p]^{S_{n}}$ is a martingale.

I need to show that $\mathbb{E}[M_{n+1}|S_{0}, \dots S_{n}] = M_{n}$. However
$$
\begin{align}
\mathbb{E}[M_{n+1}|S_{0}, \dots, S_{n}] &= \mathbb{E}[[(1-p)/p]^{S_{n+1}}|S_{0}, \dots, S_{n}] \\
&= \mathbb{E}[[(1-p)/p]^{S_{n+1}}|S_{n}] &&\text{(By Markovity.)} \\
&= [(1-p)/p]^{p(S_{n}+1) + (1-p)(S_{n}-1)} \\
&= [(1-p)/p]^{S_{n}+2p-1},
\end{align}
$$
which is not what I need. So it seems that either I'm making a mistake or the problem is wrong.
Am I making a mistake?
Is $M_n$ a martingale?
Comment: I don't think $E[M_{n+1}]=((1-p)/p)^{E[{S_{n+1}}]}$
Answer: Your mistake is that $\newcommand{\E}{\mathbf{E}} \E(\exp(S_{n+1}))$ is not the same as $\exp(\E(S_{n+1}))$. Here's the corrected work:
$$
\begin{align*}
\mathbf{E}[M_{n+1} \mid S_0, \ldots, S_n]

&= \mathbf{E} \left[ \left.  \left( \frac{1-p}{p} \right)^{S_{n+1}} \right| \ S_0, \ldots, S_n \right]

\\ &= p \cdot \left( \frac{1-p}{p} \right)^{S_n + 1}  +  (1-p) \cdot \left( \frac{1-p}{p} \right)^{S_n - 1}

\\ &= p \cdot \frac{1-p}{p} \cdot M_n  +  (1-p) \cdot \left(\frac{1-p}{p}\right)^{-1}  \cdot  M_n

\\ &= (p + (1-p)) \cdot M_n

\\ &= M_n.

\end{align*}
$$
Comment: Thanks. I think $(1-p)\cdot \frac{1-p}{p}$ should be $(1-p)\cdot \frac{p}{1-p}$.
Comment: @Srivatsan I took the liberty and added a missing power. Feel free to roll back if it was not a typo.
Comment: Thanks, @Sasha. That was indeed a typo.


Artifactory: Can the Database Collation be different than the SQL Server Instance?

Question: According to the Artifactory documentation "Configuring the Database" (https://www.jfrog.com/confluence/display/RTF/Microsoft+SQL+Server), for a Microsoft SQL Server database, "set Collation to Latin1_General_CS_AI".
If the collation for the SQL Server (and specifically for tempdb) is "accent sensitive" and the database collation is "accent insensitive", does Artifactory accommodate this configuration?
Comment: SQL Server doesn't have a problem with different collations. In fact, a *column* can have a different collation. The rest is up to Artifactory.
Answer:
If the collation for the SQL Server (and specifically for tempdb) is "accent sensitive" and the database collation is "accent insensitive", does Artifactory accommodate this configuration?

The Artifactory documentation does not say anything about accent insensitivity, though it does specify an accent insensitive Collation (as you stated). Hence, I would give them the benefit of the doubt and assume that they have tested it. They do clearly state on that page:

Selecting a Case-sensitive Collation
  While Microsoft SQL Database Server is not case-sensitive by default, it is important to select a case-sensitive collation because Artifactory is case-sensitive.

Also, a difference in accent sensitivity is not the focus when wondering if there will be issues with temp tables (assuming that they have queries that JOIN on string fields and did not explicitly set a Collation in the CREATE TABLE #.. statements). Any difference in Collation at all will cause Collation conflict errors with temp tables when JOINing on string columns of differing Collations. It doesn't matter if all of the properties of the two Collations are the same; if there is any difference in the Collation name of two columns being JOINed on, there will be an error. So, I think it is safe to assume for the moment that they have accounted for such a scenario, especially since the default Instance Collation is usually accent sensitive.
That said, Instance-level Collation controls (besides the system DBs like tempdb): variable names, cursor names, GOTO label names, and datatype alias names. If there was going to be a problem with a difference in accent sensitivity, it would be in those areas.


Only show the complete form at the end of the quiz

Question: In the Quiz module, After each question that the user answers, it shows a page that have some information (such as: right or wrong, question, answers, etc.).
And in the last of quiz it shows a complete form too.
I want to change this, so that the form is shown just at the end and not after each question. Is there a template I should change or some other way I can change the normal module behaviour?
Answer: I don't know enough about the Quiz module to say for sure but have you checked out the theme functions available for Quiz?
There is a theme function called theme_quiz_take_summary().
It has a form that it adds if the quiz is set to display_feedback. Maybe it's a setting for the quiz somewhere?
// Get the feedback for all questions. These are included here to provide maximum flexibility for themers
if ($quiz->display_feedback) {
  $form = drupal_get_form('quiz_report_form', $questions);
  $output .= drupal_render($form);
}

If you want to have your own version of that theme function you should place the whole function in your theme and replace theme_quiz_take_summary() with NAMEOFYOURTHEME_quiz_take_summary().


Folder Dialog Box in ASP.Net

Question: How we can achieve the below business requirement.
-->The End user needs to "select a folder path using Aps.net"
Whereas selecting a file can be achieved by <input type="file" />, but how to browse a folder path.
Thanks
Abdul
Comment: Populate a dropdown.
Comment: there's no folder selection - it could be a regular text box.
Comment: Most important piece of information is missing: *Why do you need to do that?* Usually there is no need to be even able to that.
Comment: something which you like this https://stackoverflow.com/questions/2302257/how-could-i-select-folder-or-file-from-the-asp-net-web-application
Answer: It is not possible to select folder from a website using native HTML+JS. You can only select a file or list of files for upload, but not a folder itself. Usually you won't even get see the original file path of the file that was uploaded, and you just cannot get direct access to the user's filesystem. Web communication is based on HTTP requests and is stateless, so there would be no way the server could access the folder on the user's (remote) PC. And for security reasons, not even JavaScript on client can do so.
Flash and Java could pick a folder and work with it on client, but those technologies are practically deprecated on modern web.
Only way this could work reasonably would be if the ASP.NET Server was running on the user's PC. Then the user could manually input the path to a given folder and the server could then access it directly. But when the server is running somewhere else, this is unfortunately out of the question.
Comment: There is a way: You can link programms to specific protocolls, the same way you can link them to filetypes. So if you could get the client side to install your little programm, it might react to a properly prepared link. But as you said, this is a security issue no mater how you slice it.
Comment: Actually this pattern is in use. Steam uses the "steam://" protoll for everything. All those links on your desktop? Technicalyl internet links (steam://rungameid/289070) Granted steam does provide it's own WebBrowser (the steam client) and I never teted what happens if I click on Play on a Storepage I opened in my webbrowser. I am pretty sure if we we install it with Adminsitrative Rights, we can get around any warning/set up a proper default. And at that point, it is the Admins decision :)
Comment: Yes, that is an interesting idea! But it wouldn't really feel secure to the user, especially when trying to open a non-http protocol on web causes a dialog warning window on most browsers.
Comment: Didn't know that! But the scenario I described is rather that when you are on a website which has for example a `magnet:` protocol link, it first shows a security alert the user has to confirm before the external application is opened. But it is possible the alert can be overridden not to display.
Comment: Thanks for your Reply.
But how we can achieve this functionality.
Also i saw few websites are using "Browse folder" dialog..
Comment: Those websites however must have used plug-ins to achieve this functionality (Flash, Java). You can technically use those, but the functionality will not work in most modern browsers unfortunately

Folder Dialog Box in ASP.Net


Inductive algorithm: linear independent versus spanning lists

Question: I'm trying to understand a proof in Axler's textbook which states that the size of any linearly independent list cannot exceed the size of any spanning list. He proves it algorithmically. The idea is to start with the full spanning s et $w_1, \ldots, w_n$, add the first element, $u_1$ of the linearly independent set, and then remove some element (say, $w_n$, without loss of generality) so that $u_1, w_1, \ldots, w_{n-1}$ still spans.
The "base step" involves removing one vector and adding $u_1$, which is fine. But then Axler assumes that it holds for steps $1$ through $j-1$. This is something I'be never been able to understand. In induction, I assumed that we say that $P(n)$ implies $P(n+1)$. If I started with $n-1$ and $n \in \{1, \ldots,\}$, then I need to take a base case of $n = 0$. But what exactly is the "zeroth" step of the algorithm? Do nothing, and notice that we still span?
If that is the case, and the $0$th step is just vacuously true and doesn't merit mention, I'm fine with this. Otherwise, should the proof technically address the zeroth step and/or add a $2nd$ step in and then assume $j \geq 2$?
Answer: There is a conceptual problem here, which has nothing to do with Linear Algebra. It's about induction. The most common way of proving that all statements from a sequence $\{P(n)\mid n\in\Bbb N\}$ of statements are true consists of:

proving that $P(1)$ is true;
proving that, for each $n\in\Bbb N$, if $P(n)$ is true, then $P(n+1)$ is also true.

But we can do induction in a slightly different way. It consists of:

proving that $P(1)$ is true;
proving that, for each $n\in\Bbb N\setminus\{1\}$, if $P(n-1)$ is true, then $P(n)$ is also true.

It's actually the same thing, express in a slightly different way. And it's this approach that Axler uses.
Comment: Ok, so the inductive hypothesis is $n-1$ holds for $n > 2$? If so, I think I am all set. Thank you.
Comment: No. The inductive hypothesis is that $P(n-1)$ holds form some $n>1$. And you deduce from this that $P(n)$ holds.


Netbeans php - expected eof but found }

Question: I am using netbeans php 7.3 and cant seem to solve this warning
" Expected EOF but found } "
The code is below. Its in a php file.

Netbeans throws up a red circle /exclamation mark on the second last  line });
The php file is 600+ lines and so to make matters simple i pasted the code section into a new file and netbeans still threw an error at the same place  });
Comment: I think you confuse netbeans with your buggy js?
Comment: Just use print/echo statements, don't use all these  ?>  double quotes, the red circle is still there - same place as before, that is at });
Answer: I edited the code, try this now:
<?php
function downloadStats($filename,$album,$type){
?>
$('#downloaddiv').html('');
$.ajax({
    type: 'POST',
    url: 'download.php',

<?php
if($_GET['urltype']=='basketball') :
?>
    data: "filename=" + $filename + "&album=" + $album + "&type=" + $type + "&area=source&uploadyear=<?php echo $uploadyear;?>",
<?php
else :
?>
    data: "filename=" + $filename + "&album=" + $album + "&type=" + $type + "&uploadyear=<?php echo $uploadyear;?>",
<?php
endif;
global $tag; ?>
    success: function(msg) {
        $('#downloaddiv').html('<?php echo $tag['view_013'];?> <?php echo $tag['view_014'];?> <?php echo $tag['view_015'];?> <?php echo $tag['view_016'];?>');
    }

});
<?php
}
?>

About closing and opening php this is what I mean:
This works but is not the bestway:
<?php
endif;
?>
<?php
global $tag; ?>

This works but is much better:
<?php
endif;
global $tag; ?>

Also if posible don't use global see more info about that see this url: https://stackoverflow.com/a/12446305/1788516
Edit
The problem is because there is javascript and php in the same file. for more information see this http://netbeans.org/bugzilla/show_bug.cgi?id=166694  for the bug.
Comment: Perry, Could you tell me where i missed the closing tag. Also which one did you delete?
Comment: Also i pasted your code in and it threw up 2 more red circles :)  I think i should have mentioned its javascript in a php file. I am tasked with maintaining it and documentation is scarce.
Comment: I just saw you changed it. I will take a look at it.
Comment: will retry. Thanx for the effort.
Comment: the red circles still appear at line                                                          success: function(msg) {
        $('#downloaddiv').html('   ');                                                              and at line
    }
Comment: The problem seems to be at                                     success: function(msg) { }
Comment: When I test the code I don't have any read circle, have you any other code above these lines? I also tried the code to see what the out will be and that is also correct
Comment: The php file is about 600+ lines and the code section in question is about lines 113-137
Comment: Lol ok. You should check the code above this there must be the problem :)
Comment: i tried creating a new php file in netbeans and pasted that code  section alone and netbeans still threw a red circle at the exact same place  });
Comment: That is strange u have the same netbeans version and it don't have that red circle. What is happing when you execute the code?
Comment: The 600+ line php file is fine....nothing seems broken...i am getting the functionality we are suposed to get. Its just the netbeans red circle error... i just want to get rid of it..
Comment: Check out this bug: https://netbeans.org/bugzilla/show_bug.cgi?id=166694 can you test the JavaScript code in a js file or a html file?
Comment: great find. At least I can breathe easy and just move on to the next bug/warning. The code section has php embedded in it, kinda hard to replace dynamically? When i remove the php tags, more red circles pop up... :) I am accepting your last comment as a virtual "answer". Thanx     for the effort.

Netbeans php - expected eof but found }


How do I add an image field to my node.tpl.php template using render($content['field_example'])?

Question: I am creating a Bootstrap sub-theme and want to customize my node.tpl.php template. I have an image field with a machine name of 'field_poster'. According to the default node template:

$content: An array of node items. Use render($content) to print them all,
or print a subset such as render($content['field_example']). Use
hide($content['field_example']) to temporarily suppress the printing of a
given element.

So, doesn't this mean I can add print render($content['field_poster']); to my node.tpl.php and it will output the image, right? Well, I've tried that and it does nothing!
How can I get my image field to render in my template?
Update
My field_poster was set to display within a Field Group in Display Settings. This changes how things work in the template. See below for my solution.
Answer: Ok, so here was the problem. My field_poster was nested in a Field Group under display settings. Apparently, you need to include the parent field group if you want to render child fields outside the group.
So, if my container field group is named group_fieldgroup1 I need to use the following to render my field:
<?php print render($content['group_fieldgroup1']['field_poster']); ?>
You can render the entire field group by using the following.
<?php print render($content['group_fieldgroup1']); ?>


Bubble sort in a Vector in Java

Question: I'm creating a program that can sort objects (vector) with the Bubble sort method. I found a code on the internet which helped me alot to create it (Bubble sort in Arrays):
http://www.programmingsimplified.com/java/source-code/java-program-to-bubble-sort
When i compile the program i don't get any syntax error, but the results are not correct. I think i made an error in the IF-Statement, but i'm not sure if that's the only error. Here is the result i get when i run it:
Input number of integers to sort
5
Enter 5 integers
2
0
1
6
4
Sorted list of numbers
1
2
3
3
3

And here's my code:
import java.util.Scanner;
import java.util.*;
import java.io.*;
class BubbleSortVector {
  public static void main(String []args) {
    int n, c, d, swap;
    Scanner in = new Scanner(System.in);

    System.out.println("Input number of integers to sort");
    n = in.nextInt();

    Vector v ;
    v = new Vector();

    System.out.println("Enter " + n + " integers");

    for (c = 0; c < n; c++)
      //v.addElement(c);
     v.insertElementAt(in.nextInt(),c);

    for (c = 0; c < ( n - 1 ); c++) {
      for (d = 0; d < n - c - 1; d++) {
        if ((Integer)v.elementAt(d) > (Integer)v.elementAt(d+1)) /* For descending order use < */

        {
          swap = (Integer)v.elementAt(d);
          v.insertElementAt(d+1,d);
          v.insertElementAt(swap,d+1);

        }
      }
    }

    System.out.println("Sorted list of numbers");

    for (c = 0; c < n; c++)
      System.out.println(v.elementAt(c));
  }
}

Comment: Any particular reason you are using a Vector? Not that it matters in this case, just curious. In 99.9996 (I believe that to be the exact number) of the cases you do not want a `Vector` in most of those cases what you want is a `List` implementation, in this case I recommend an `ArrayList`. Again, not related to the error.
Comment: @Emz It's for my oral exam, i have to make one with arrays and another with vectors. And make a mini-presentation of it :)
Comment: Do you have access to a proper IDE that lets you set breakpoints for debugging?
Comment: @Coderchu i have tried it but i don't really see my error :/
Comment: I think I just picked it out, take a look at my answer. It's a bit confusing with your variable names ;)
Answer:     // ...
    Vector<Integer> v = new Vector<>();
    // ...
    for (c = 0; c < (n - 1); c++) {
        for (d = 0; d < n - c - 1; d++) {
            if (v.get(d) > v.get(d + 1)) {
                swap = v.get(d);
                v.set(d, v.get(d + 1));
                v.set(d + 1, swap);
            }
        }
    }
    // ...

Comment: @petie12 Then you are *still* using **raw types**. ***Please* don't** do that.
Comment: Thanks it worked! I just had to convert the objects into Integers:if ((Integer)v.get(d) > (Integer)v.get(d + 1)) { AND swap = (Integer)v.get(d);
Comment: @petie12, please do not cast them as Integer, instead follow Elliott's answer and tell what objects the `Vector v` stores.
Comment: @ElliottFrisch why did you delete your own answer?
Comment: This is not Bubble Sort though.
Answer: Your following code is wrong, inserting d+1 at index d means you're using the value of the loop index/counter into the vector, not the actual value that is at d+1
swap = (Integer)v.elementAt(d);
v.insertElementAt(d+1,d);    // this is incorrect, d is the index/loop counter
v.insertElementAt(swap,d+1);

Chage that middle line to:
v.insertElement((Integer)v.elementAt(d+1), d);

Comment: I changed it but when i input the same numbers as the one from above, i get 0 0 2 2 0 instead of 0 1 2 4 6
Answer: you can solve it by simple swapping method. after loop you print the array.
        int[] Array = new int[5]{2 , 0 , 6 , 1 , 4};

        int temp = 0;
        for (int i = 0; i < Array.Length; i++)
        {
            for (int j = 0; j < Array.Length - 1; j++)
            {
                if (Array[j] > Array[j + 1])
                {
                    temp = Array[j + 1];
                    Array[j + 1] = Array[j];
                    Array[j] = temp;
                }
            }
        }

Bubble sort in a Vector in Java


Excel count number of days by group

Question: I have a table with employee ID and benefits receive date as below.
The first column is ID and the second column is the date
Employee ID Date
1   01/01/2013
1   01/10/2013
1   11/01/2013
2   03/01/2014
2   04/01/2014
2   05/10/2014
3   03/01/2016
3   04/01/2016
3   06/01/2016
3   08/01/2016

I need to find an automated way to calculate the number of days has each employee receive the benefit. For example, employee #1 is 305 days (11/1/2013 - 1/1/2013 + 1). The result should look like this:
Employee ID Days
1        305
2        71
3        154

I have tried to use "if" and "sumproduct" function discussed here: Simple Pivot Table to Count Unique Values
and that does not get the answer I am looking for.
Comment: What do you get from Pivot Table?
Answer: try:
=MAX(IF(A:A=E2;B:B;""))-MIN(IF(A:A=E2;B:B;""))+1

accept formula CTRL+SHIFT+ENTER
A - column with employee id
B - column with date
E2 - cell with employee id

Excel count number of days by group


Any matrix ring $R_k$ is isomorphic to a subring of the ring $R_{2^k}$

Question: I am reading the paper: "Logical connections between some open problems concerning nil rings" by Jan Krempa.
I have a problem trying to understand the last part of Theorem 2. It says:
"Any matrix ring $R_k$ is isomorphic to a subring of the ring $R_{2^k}$".
I don't see why is that true and he is not giving any clue of that. Any help is much appreciated.
Comment: The paper deals with rings without identity, otherwise the very concept of nil ring is meaningless.
Comment: I think the clame is independent of the ring I consider. I mean, if the ring is unital, the claim have to follow the same way. Is it? Thank for the comment
Comment: Why should it? Rngs and rings are quite different animals.
Comment: I don't know. I'm new dealing with rings and rngs. That was my thought reading that. Do you have any proof or suggestion of why the claim is true? Thanks in advance
Comment: In short: the result is false if you're dealing with rings and subrings need to share the identity.
Comment: And supposing they don't share the identity, why is it true? That's what I don't see. I think @rschwieb is right. Do you agree?
Comment: If subrings need not share the identity, this is essentially obvious: if $m\le n$, then $\mathrm{End}(R^m)$ is (isomorphic to) $e\mathrm{End}(R^n)e$ for a suitable idempotent $e$.
Answer: Why don't you just map things in $R_k$ to matrices in $R_{2^k}$ which have the matrix from $R_k$ in the upper left hand block? You seem to be suggesting it's ok that it does not share identity.
That's a subring isomorphic to $R_k$.
Comment: That set is closed under multiplication but it is not under adittion. Perhaps I am missing something. Could you explain a bit more your idea? Thanks!
Comment: I mean, the inclusion is not a ring map.
Comment: @EmilianoAcri Hm , I don't know what I was thinking. Why I was suggesting only works for embedding GL(n) into GL(m) for m> n.  But I don't understand your second comment. The inclusion is a ring map (but not unital, and you said that was ok?)
Comment: I tried to say that the inclusion from $R_k$ to the set you proposed is not a ring map because that set is not a subring, is it? I feel I'm missing something.
Comment: I deleted the part about non-unital. I That was a mistake because I was thinking on the generalities of the paper but this demonstration is nothing to be with that. Sorry about that.
Comment: @EmilianoAcri oh I see.  You were right, I edited accordingly.
Comment: I see your edition. Using that identification you're not using that matrices are of size $2^k$. It means that $R_n$ is included in $R_m$ as a subring if $n<m$. Is that correct? Perhaps Krempa uses this identification in particular because he can explode some properties. Thank you so much for your comments, there were very useful.
Comment: Sorry for my earlier lapse.i always appreciate that
Comment: @EmilianoAcri Maybe there is another way I didn't think of.


Android- Next Class function

Question: Please i will like to have a method/function in a separate class
that will enable me to go to next activity or fragment class when i call it
here is my little try of code
inside my go_to.class i have this below
for activity
void goToActivity(Activity t){
        startActivity(new Intent(this, t.class));
    }

void goToFragment(Fragment f,package.com.R l){
        getSupportFragmentManager().beginTransaction().add(l,new f).commit();
    }

and to use example
goToActivity(mynextactivity.class);

goToFragment(mynextfragment.class,R.id.fragment_layout);

Any help is welcome
Comment: And your problem is???
Comment: my problem was i am getting error
Comment: why did you down vote my question i am only looking for help
Comment: this is really not **fear
Comment: How we can help if we dont know whats your error ? :)
Comment: if you like to help you post example not down voting question
Comment: What error are you getting? Post the text of the error, or a screenshot or something. We are not mind-readers.
Comment: here is the line i am getting from first method `startActivity(new Intent(this, t.class));// unknown class`
Comment: then second method/function is like this, since resources id cannot be determine so i want have a piece of code that i can override latter in activity/fragment class to go to the fragment
Answer: From non activity class you can create a function it like this:
public static void goToHomeActivity(Context context)
{
    Intent i = new Intent(context, ActivityDashboard.class);
    context.startActivity(i);
}

Then call it like this MyUtils.goToHomeActivity(context);
Alternatively, from activity class like this:
private void goToHomeActivity()
{
    Intent i = new Intent(getBaseContext(), ActivityDashboard.class);
    context.startActivity(i);
}`

Then call it like this goToHomeActivity();
Answer: I later solve it this way after many trial:
What i am trying to achive is to have a function to call new activity class and fragment when a button is clicked on at runtime
void goToActivity(Class t){
        startActivity(new Intent(this, t));
    }

my where i have been getting the fragment concept wrong is fragment is not indepent activity class, so to overcome fragment need anactivity parent or root layout to hold the fragment layout that is you can never start fragment instance alone like activity which is very big issure for begginers to understand
void goToFragment(Fragment f){
        fragmentTransaction.replace(R.id.your_layout, f);
fragmentTransaction.addToBackStack(null);
    }

or if you cannot determine your xml layout you can write it like this:
void goToFragment(int l,Fragment f){
            fragmentTransaction.replace(l, f);
    fragmentTransaction.addToBackStack(null);
        }

Thank you all for your help

Android- Next Class function


Confusion related to derivation of conditional distribution

Question: I was reading this paper http://stat.duke.edu/phd-program/gcc/resources/ResourcesDocuments/CodeExplanation.pdf related to Gibbs sampling.
Suppose we have n iid samples $x_i$ from $N(\mu,\sigma^2)$
Prior probabilities for
$\mu$ ~ $N(m,s^2)$
$\sigma^{-2}$ ~ $Gamma(a,b)$
Then

Can anyone help me with how the conditionals are derived. I tried for $p(\mu|\sigma^2,x)$ which I got something like
$\frac{N(\frac{\sigma^{-2}\mu + s^{-2}m}{\sigma^{-2} + s^{-2}}, \frac{\sigma^2s^2}{\sigma^2+s^2})}{p(x|\sigma^2)} $. Then I didn't get how to proceed and got stuck.
This is what I tried then
$p(\mu|\sigma^2,x) = \frac{N(\frac{\sigma^{-2}\mu + s^{-2}m}{\sigma^{-2} + s^{-2}}, \frac{\sigma^2s^2}{\sigma^2+s^2})}{\int N(\frac{\sigma^{-2}\mu + s^{-2}m}{\sigma^{-2} + s^{-2}}, \frac{\sigma^2s^2}{\sigma^2+s^2})d\mu}$. I don't think this will give me the required expression.
Suggestions?
Comment: Some more information about where you're getting stuck would allow a more direct answer.
Comment: @Actually, I got the expression above. I am not sure this is what I am supposed to get. I don't think it will give me the target expression
Comment: @user34790 You may take a look of the book "Bayesian data analysis" (chapter 3) by A. Gelman et al..
Answer: Note that the key to getting the conditionals is to treat all variables except for one as "constant".  It is also easier most of the time to work with the log probabilities as these generally add instead of multiply.  So for the conditional $(\mu|\sigma^2,x_1,\dots,x_n)$ is written on the log scale as:
$$\log[p(\mu|\sigma^2,x_1,\dots,x_n)]=\log[p(\mu|\sigma^2)]+\log[p(x_1,\dots,x_n|\mu,\sigma^2)]$$
$$-\log[p(x_1,\dots,x_n|\sigma^2)]$$
Now as is usual in this we ignore the last term, as it is not a function of $\mu$ (or put another way, we can implicitly calculate it by normalising the probability distribution so that it integrates to 1).  Also, we can write the log-likelihood for all the data as a function of the individual log-likelihoods.  So we have for the prior:
$$\log[p(\mu|\sigma^2)]=\log[p(\mu)]=-\frac{1}{2}\left(\log(2\pi s^2)+\frac{(\mu-m)^2}{s^2}\right)$$
$$=c_1-\frac{1}{2s^2}\mu^2+\frac{m}{s^2}\mu$$
Where $c_1$ is a number which depends only on $m$ and $s^2$ but not on $\mu$.  Thi part of a probability distribution is often known as the "kernel", although kernels usually aren't written on the log scale.  Note that identifying the kernel is equivalent to identifying the probability distribution.  The log-likelihood has a similar form:
$$\log[p(x_1,\dots,x_n|\mu,\sigma^2)]=\sum_{i=1}^{n}\log[p(x_i|\mu,\sigma^2)]$$
$$=\sum_{i=1}^{n}-\frac{1}{2}\left(\log(2\pi\sigma^2)+\frac{(\mu-x_i)^2}{\sigma^2}\right)$$
$$=-\frac{1}{2}\sum_{i=1}^{n}\left(\log(2\pi\sigma^2)+\frac{x_i^2}{\sigma^2}+\frac{\mu^2-2\mu x_i}{\sigma^2}\right)$$
$$=c_2-\frac{1}{2\sigma^2}\sum_{i=1}^{n}(\mu^2-2\mu x_i)=c_2-\frac{n}{2\sigma^2}\mu^2 +\frac{n\overline{x}}{\sigma^2}\mu$$
Where $c_2$ depends on the data $x_1,\dots,x_n$ and on $\sigma^2$, but not on $\mu$.  Combining the likelihood and the prior gives you:
$$\log[p(\mu|\sigma^2,x_1,\dots,x_n)]=c_1-\frac{1}{2s^2}(\mu^2-2m\mu)+c_2-\frac{n}{2\sigma^2}(\mu^2-2\mu \overline{x})$$
$$-\log[p(x_1,\dots,x_n|\sigma^2)]$$
$$=c_0-\frac{1}{2}\left(\frac{1}{s^2}+\frac{n}{\sigma^2}\right)\mu^2+\left(\frac{m}{s^2}+\frac{n\overline{x}}{\sigma^2}\right)\mu
$$
Where $c_0=c_1+c_2-\log[p(x_1,\dots,x_n|\sigma^2)]$
This is the same form as the prior, but with different values for $m$ and $s^2$.  So the posterior is a normal distribution.  On comparing the two equations, we see that the mean and variance of the posterior satisfy:
$$-\frac{1}{2s_*^2}=-\frac{1}{2}\left(\frac{1}{s^2}+\frac{n}{\sigma^2}\right)$$
$$\frac{m^*}{s_*^2}=\frac{m}{s^2}+\frac{n\overline{x}}{\sigma^2}$$
Solving these equations gives you the mean and variance.  I hope this approach will help you get the conditional for $\sigma^2$.


Base of tensor product

Question: Given the tensor product $V_1 \otimes V_2$ (so we have a bilinear map $\otimes : V_1 \times V_2 \to V_1 \otimes V_2$) and bases $B_i$ of $V_i$ (not need to be finite) how to prove using only the universal property (u.p.) that $\otimes(B_1 \times B_2)$ is a base of $V_1 \otimes V_2$?
My attempt is to consider the map $f: V_1 \times V_2 \to  \langle \otimes(B_1 \times B_2) \rangle$ with $f(v_1,v_2)=v_1 \otimes v_2$ and apply u. p. in somehow.
Answer: Let $B_1:=\{u_1,\dots, u_m\}$ and $B_2:=\{v_1,\dots,v_n\}$ denote bases of $V_1$ and $V_2$ respectively.  From the bilinearity of the tensor product it follows that
$$
u_i\otimes v_j,\hspace{0.2in} i=1,\dots, m,~j=1,\dots, n
$$
spans $V_1\otimes V_2$.  What we need to do is prove that $\{u_i\otimes v_j\}$ is linearly independent.
So suppose then that
$$
\sum_{i,j} c_{ij} u_i\otimes v_j = 0.
$$
Let $f_{ij}: V_1\times V_2\rightarrow \mathbb{R}$ be the bilinear map defined by
$$
f_{ij}(u_k,v_l)=\delta_{ik}\delta_{jl}
$$
In other words, $f_{ij}(u_k,v_l)=0$ whenever $k\neq i$ or $j\neq l$ and $f_{ij}(u_k,v_l)=1$ when $k=i$ and $l=j$.  By the universal property of the tensor product, there exists a linear map $\widehat{f}_{ij}: V_1\otimes V_2\rightarrow \mathbb{R}$ such that
$$
\widehat{f}_{ij}\circ \otimes = f_{ij}
$$
Hence, $\widehat{f}_{ij}(u_k\otimes v_l)=1$ only when $k=i$ and $j=l$.  So
$$
\begin{align*}
0&=\widehat{f}_{ij}\left(\sum_{k,l}c_{kl}u_k\otimes v_l\right)\\
&=\sum_{k,l}c_{kl}\widehat{f}_{ij}(u_k\otimes v_l)\\
&=\sum_{k,l}c_{kl}\delta_{ki}\delta_{lj}\\
&=c_{ij}
\end{align*}
$$
which proves linear independence of $\{u_k\otimes v_l\}$.
Comment: Thank you. "From the bilinearity of the tensor product it follows that ui⊗vj,i=1,…,m, j=1,…,n spans V1⊗V2."Can you prove that? However the bases not need to be finite, if you can rewrite the proof also for vector spaces with bases not necessarly finite, I can accept the answer.

Base of tensor product


Facebook Connect for Drupal

Question: The readme.txt of the Facebook Connect module is seriously out-dated! It really needs a review concerning the FB updates.
Now, the real problem:
I have installed the module, inserted my appID and all that, but when in /admin/config/people/fbconnect I click on 'appearance' I get this fatal error:
Fatal error: Call to a member function getUser() on a non-object in /customers/denotenbalkers.be/denotenbalkers.be/httpd.www/sites/all/modules/fbconnect/fbconnect.module on line 421

When I click on 'app settings' it shows me the notice: "Ensure that you entered valid api keys." but those keys ARE valid. Maybe I'm missing something from the readme? Ex.:
5. Enter the Connect URL on Connect settings tab (e.g. copy value from admin/settings/fbconnect field "Connect url").
There is no such thing as a connect settings tab!
6. Add your server to the Server Whitelist on Advanced settings tab on Facebook or disable Session Secret Whitelist Exception.
What am I supposed to add here? Because only the url doesn't work. I suppose an IP-address but I wouldn't know which one.
I've done all the rest, so I'm guessing that that's the problem.
EDIT / SOLUTION:
The problem was that I followed the readme that was on Facebook Connect's project page. The information in there is OUT-DATED and insufficient. The readme that comes with the module itself is the one you should read!
Answer: Did you double check that you installed the Facebook PHP library correctly per the README?
2. Upload facebook-php-sdk library (http://github.com/facebook/php-sdk/) into the libraries folder so that it looks like 'sites/all/libraries/facebook-php-sdk/src/facebook.php'.

The error you are getting looks like it is coming from a library function not in memory.
You can confirm whether this is loaded or not on your admin 'status' page. You should also check the drupal logs to see if there is any more descriptive error to share.
If its in the right place but not loading, you might want to check this thread:
http://drupal.org/node/1318296
for advice on how to get it to work with the libraries API.
Comment: Hi, thanks for your quick response! I did figure it out, after I read through the readme of the module itself (I read the readme that's on the page of the module itself, which is apparently out-dated! Now I can access the settings pages, but when I click on the log-in button, it asks for permissions and when I click 'Okay' (or whatever it is) it doesn't do anything! Doesn't go to a new page or anything, just sits there.. I'm not logged in because I can't use the comments. Any ideas?
Comment: Bram - can you be more specific about what you figured out and what you did so others can benefit? Did downloading the above php-sdk address the fatal error you were getting?
Comment: Hi schnippy. I edited my post with the solution and marked yours as correct. Should I make a new post for the problem I encounter now?

Facebook Connect for Drupal