What do i need to know to contribute to Rails?

Question: I am a user of Ruby on Rails framework and am thinking of giving back to it by contributing to the code.
I understand that there is a need for thorough understanding of the Ruby language concept to contribute?
Ive cloned the project, looked at the code, check out the tickets and have no clue how to begin?
From what i see the Rails Framework utilizes metaprogramming alot? So what other aspect of Ruby do i have to master in order to start contributing? or to contribute is to know the ins and outs of Ruby?
Thank you.!
Comment: Don't listen to these other guys, there's tons you can do right now without knowing Ruby. Start with documentation and tests, work your way up as you gain understanding
Comment: I agree w/ @Chuck Vose "Start with documentation and tests, work your way up as you gain understanding".  In addition - pick one part of the framework that interests you & write a plugin or two that extends it's capability.  This should really help understanding the internals of that area.  Once you have that understanding, look @ tickets for that area & see what you can do.  Best of luck!
Answer: It has been quite awhile since I ran across ruby code I didn't understand, but there are parts of rails that really push my understanding of ruby.
That being said, even if you are at more of an intermediate level with the language, figuring out how rails works would probably be a great way to up your game.
As for where to begin, I would start by writing plugins. Think of a cool plugin you could write that hasn't been done yet, or something that you think you could do better. Whatever it is you want to do, chances are you are going to need to hook into some sort of rails internals to do it, which will give you a good place to start. Once you have a bit of knowledge of a given area of the framework, see if there are any open bugs in that area you can fix.
The barrier is quite high, since rails is a quite large and complex program written by people who have a high level of mastery with an incredibly flexible language. It is also a great challenge that will probably make you a better programmer in the end. :)
Edit: to help out banister
This is actually pretty interesting if it is a snippet designed to illustrate how class variables and singleton classes work, but there are much clearer ways to accomplish the same thing if it is "real" code.
Singleton Class
In ruby, every object has a parent class that it gets its methods from. This is pretty normal for OO languages. What isn't normal is ruby also has a concept called "object individuation, that means that objects can have methods that are only on a specific instance, but not on the parent class. here is a quick irb example
irb(main):001:0> foo = "bar"
=> "bar"
irb(main):002:0> def foo.foo_method
irb(main):003:1>   "this is _only_ on the foo instance, not on all strings"
irb(main):004:1> end
=> nil
irb(main):005:0> foo.foo_method
=> "this is _only_ on the foo instance, not on all strings"
irb(main):006:0> "bar".foo_method
NoMethodError: undefined method `foo_method' for "bar":String
    from (irb):6
irb(main):007:0> foo = "New string"
=> "New string"
irb(main):008:0> foo.foo_method
NoMethodError: undefined method `foo_method' for "New string":String
    from (irb):8

First, we assign a string to a variable. Next, we define a method on that instance. Calling the method works, but calling it on a new string does not work. Assigning a new string instance to our foo variable also does not have that foo method.
To make object individuation possible, there needs to be something in between the instance, and the parent class. That thing is the singleton class, and every instance has one that is unique from all other object instances. When ruby is looking up a method, it will look at the singleton class before the parent class.
Believe it or not, even if you have never heard of this before, you have probably already used it. If you want to add a "class method" to something, you usually do this
class Foo
  def self.bar
    "i am on the class"
  end
end

Foo.bar #=> "I am on the class"

To start from the top, the statement class Foo is the exact equivalent of this Foo = Class.new do. What is happening is you are assigning a new instance of type Class to the constant Foo. (as an aside, this is what I love about ruby. most of the syntax is actually just sugar around some core concept)
Inside a class definition, self refers to the class, so saying def self.bar is essentially saying "define the method bar on the singleton class of the Class instance that is stored in the constant Foo".
If you find this stuff complex, it is because it is. I don't think there is anything more complected in ruby other then what happens during method lookups, and singleton classes are a big part of what makes it so complex.
Class Variables
A class variable is prefixed by @@, and basically is a variable whose scope is all instances, the class object, and all classes that inherit from the class. I'll do a quick irb to illustrate this in action
irb(main):003:0* class Foo
irb(main):004:1>   @@instance_count = 0
irb(main):005:1>
irb(main):006:1*   def initialize
irb(main):007:2>     @@instance_count += 1
irb(main):008:2>   end
irb(main):009:1>
irb(main):010:1*   def count
irb(main):011:2>     @@instance_count
irb(main):012:2>   end
irb(main):013:1> end
=> nil
irb(main):014:0>
irb(main):015:0* class Bar < Foo
irb(main):016:1> end
=> nil
irb(main):017:0>
irb(main):018:0* f = Foo.new
=> #<Foo:0x7fa9089c7da0>
irb(main):019:0> f.count
=> 1
irb(main):020:0>
irb(main):021:0* b = Bar.new
=> #<Bar:0x7fa9089be0e8>
irb(main):022:0> b.count
=> 2
irb(main):023:0>
irb(main):024:0* f.count
=> 2

First, we define Foo. Foo has a class variable that tracks how many instances were created. To do that, we increment that variable in the constructor, and lastly just define a quick getter. Bar just extends Foo.
Now, to see it in action, we make a new foo, and check the count, which is 1. Next, we create a new bar, and check the count, we are now at 2. Just to make sure that both Foo and Bar share the same count, we check our foo instance again, and it is 2 now.
Class variables are a very situational feature that you usually don't see outside of framework code. It is usually used when you want to keep track of all instances of a given class.
Banisters Code
class << Object.new
  @@var = 6
end

String.class_variable_get(:@@var) #=> 6

Your code is showing those two concepts in action. First, we open up the singleton class of a new object, and put a class variable on it. If it were anything other then a class variable, those first three lines would be the most useless ruby code in the world. But since it is a class variable, that becomes visible to the class, all instances of the class, all classes that inherit from the class, and all instances of all classes that inherit from the class. Since the class we are talking about is object, that means everything. So doing class_variable_get on String gives it to you, but you could access that variable from any class or instance you wanted to.
I am sorry
This is horribly complected stuff that is very hard to explain clearly. These concepts took me about a week or so of fairly concerted effort to wrap my head around. If you have any questions about what I wrote, feel free to ask, but don't be discouraged if you don't "get it".
Comment: Right i have tried writing a few plugins based on Railscasts and Rails Guide and still trying to work on it... Appreciate your respond... and i will definitely try to work my way there! Thanks!
Comment: here's some ruby code i don't understand....you give it a go too ;) : `class << Object.new; @@var = 6; end; String.class_variable_get(:@@var) #=> 6` :( :( :(
Comment: @banister: wrote a fairly lengthy explanation into my post :)
Comment: heya, since you're not updating the code, i hope you dont' mind if i edit it for you, just to correct the information :)
Comment: @banister: Go for it. I have no idea why that works that way, probably has to do with the way that singleton classes are implemented. I also wouldn't be suprised if this was a bug
Answer: RoR has a bunch of places you can start out but they may not be what you're looking at. The first place to start is probably documentation here. You'll need to know a ton of Ruby at a deeply personal level in order to contribute serious core patches, but you can get in on the discussions right now and you can improve documentation in a way that the core team really, really, really needs.
Sorry, better link here
Answer: The thought is really appreciated. I think you answer the question yourself. If you can't read and/or understand Rails code, then that is the bottle-neck. Without even looking at the code, I'll take a wild guess they use inheritance, mixins and meta-programming. You should definitely try to study those aspects regardless if you will contribute to Rails. They are essential concepts in Ruby, Rails and Ruby/Rails libraries.
Answer: I think you answered a lot of your own questions: yes, you need to understand Ruby to contribute to a Ruby project.
If you want to learn, you can pick up a ticket and start hacking on it: there's nothing quite like jumping in the deep end! However, I think you can only begin to contribute effectively to a project once you've used it enough for yourself to understand:

What features exist and are useful, and how they work
What features are lacking and need help
What's unclear or confusing and needs documentation

All of the above should come from real-world needs: otherwise you can't state your case for why some feature that you thought up needs to be added...
Answer: To work on any framework you need to have a reasonable understanding of the language or if you know lots in one certain area but really get in touch with the people and just talk to them ask what there currently working on and if you feel you can help say and give them your ideas, etc.... i mean the dev community is very nice and the fact that they spend there time working on something to give to other people for free so there always happy to help and try and include and let you know if and how you can help.
But mainly,
a little more then the ins and outs and best if you know lots in a certain area
Answer: In addition to the comment I left on your original question...
Ryan Bates (of Railscasts) fame recently released 2 screencasts where he walks through the internals of the Rails 3 router.  I found it to be a great & eye opening approach to reading and understanding framework code.  If you get the opportunity, check them out:

http://railscasts.com/episodes/231-routing-walkthrough
http://railscasts.com/episodes/232-routing-walkthrough-part-2

Perhaps these 'casts may help you to be more comfortable in building your approach to getting down with the framework code.
Hope this helps!


Musescore: add dotted 16th note triplet on a dotted 8th note space

Question: I am trying to transcribe a piece of sheet music in MuseScore.   However, I am having difficulty making a triplet of dotted 16th note.
The music is in 4/4.

Can anyone help me with this please?
I have tried How to create triplets and other tuplets but still can't understand how to make it work.
Comment: What you are trying to notate is equivalent to writing three sixteenths without a triplet.
Comment: `Ctrl+3` on a quaver, then `.` to get dotted semiquavers.
Comment: Also, what piece are you trying to transcribe? It's possible that you're notating the rhythm there incorrectly and therefore don't need to ask this question.
Comment: I'm prone to thinking that the triplet is for only the first 2 dotted 16th notes.
Answer: Using Musescore 3.1.0, I am able to produce triplets from a dotted sixteenth note. First, you should have only two sixteenth notes in your measure, not three. Below is a diagram showing how it is done. Start with two sixteenth notes. Then go to tuplets, and then select triplets and you shoud see the sixteenth note split into three notes with a bracket underneath with a small 3 in the bracket. The first triplet will be the same tone that you clicked on while the other two are shown as rests. Then enter the notes that are desired for the two remaining triplets. You an also cange the first triplet as well, if desired. If this doesn't work I sugest that you reload the Musescore program.


Prove that if $\int_a^\infty g(x) dx$ is convergent then $\int_a^\infty f(x) dx$ is convergent.

Question: where $f$ and $g$ are positive continuous functions on $[a, \infty)$, and $$\lim_{x\to\infty} \frac{f(x)}{g(x)} = 0$$
I tried to prove this as follows:

But something tells me I can't do the bottom-left part, or that I'm missing some parts, or that my logic might be flawed altogether.
Thanks :)
Comment: Image missing...
Answer: It may not be wrong that $\lim_{x\to+\infty}f(x)\to0$, but it could be that $g(x)$ grows faster than $f(x)$, and so maybe that's why $\lim_{x\to+\infty}\dfrac{f(x)}{g(x)}\to0$. So, it's not a flaw in logic - it's just that you are removing other plausible situations.
Comment: @SammiFernandez Not necessary - $f(x)$ need not be bounded in the general case: Try showing that $\lim_{x\to\infty}\dfrac{x}{e^x}\to0$ (maybe by L'Hopital's rule and using the fact that $\lim_{x\to\infty}e^x\to\infty$), but $\lim_{x\to\infty}x\to\infty,$ so $f(x)=x$ is not bounded. Also, $\lim_{x→∞}f(x)$ will necessarily be less than $\lim_{x→∞}g(x)$ for large $x$.
Comment: So $\lim_{x\to\infty} f(x)$ will _necessarily_ be less than $\lim_{x\to\infty} g(x)$, but not necessarily 0? Which makes $f(x)$ also bounded.
Answer: There is an $r\ge a$ such that
$$
\frac{f(x)}{g(x)}\le 1 \quad \forall x \ge r.
$$
It follows that
$$
0\le \int_a^\infty f(x)\,dx\le \int_a^rf(x)\,dx+\int_r^\infty g(x)\,dx<\infty.
$$


Functions like node_load() are not found

Question: I successfully installed Drush on Ubuntu 12.04, and I created a script containing the following line.
print_r(node_load(10));

I am calling the script with drush php-script --uri=http://localhost myscript.php which returns the following error.

PHP Fatal error: Call to undefined function node_load()

I also tried with drush --uri=http://localhost cache-get, but I get the following error.

Command cache-get needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
The drush command 'cache-get' could not be executed.
Drush was not able to start (bootstrap) the Drupal database.
Hint: This may occur when Drush is trying to:

bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See drush topic docs-aliases for details.
connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.
Drush was attempting to connect to:
Drupal version:  7.26
Site URI:  http://localhost
Database driver:  mysql
Database hostname: 127.0.0.1
Database username: username // This is shown correctly
Database name: database_name  // This is shown correctly
PHP executable: /usr/bin/php
PHP configuration:  /etc/php5/cli/php.ini
PHP OS:  Linux
Drush version:  7.0-dev
Drush temp directory:  /tmp
Drush configuration:
Drush alias files:
Drupal root:  /opt/lampp/htdocs
Site path:  sites/default
Comment: are you running the command from the site root folder
Comment: Yes, I am calling drush from the site root folder.
In my case that is user@computer:/opt/lampp/htdocs/sites/default$
Comment: If you are calling drush from the site root folder, why do you need to specify the `--uri` parameter?
Answer: I finally figured out what was missing.
In my case I had to install the mysql-client-core-5.5 package with sudo apt-get install mysql-client-core-5.5.
Answer: I ran into the same problem (user_load() and other functions were not found), but had a different solution.
For me, it turned out that my sql privileges on the database were not correct.
I found the error by running my script with the -d option:
drush -d scr /path/to/my/script.php

I noticed in the log it spewed out that it was getting an error connecting to the database. I apparently had messed up the privs when I set them up. I sql granted  the privs and my script ran just fine.
The error message about not being able to find a function was a total red herring.
Comment: Red herring indeed...


MYSQL Backward compatible to 5.1.1?

Question: I have a Wordpress site that was developed on a server running the latest version of MYSQL, however, I've just found out the host server (BT) is running 5.1.1. and they have no plans to upgrade anytime soon.
Does anyone know if there is a way of converting the database so it runs on 5.1.1 with no issues caused re the site being built in the latest version of Wordpress?
If this is a massive issue, then I do have some alternative hosting options, but I'm hoping for a way forward re conversion - any geniuses out there?
Many thanks
Answer: I doubt that BT is running MySQL 5.1.1. That version was never released. It was an internal development milestone in 2005.
The first GA release of the 5.1 branch was 5.1.30 in 2008. The last 5.1 release was 5.1.73 in 2013. But after 2013, 5.1 has been in "sustaining support" which means they will not make any new versions or fixes.
You shouldn't deploy to a hosting site that still runs any 5.1.x version. A site that is so far behind is probably behind on other software too, and I would not be surprised if they have known security vulnerabilities.
Wordpress officially requires MySQL 5.6 or later, according to https://wordpress.org/about/requirements/.
You could try to test that by testing on MySQL 5.1 (assuming you can find an installation package of MySQL 5.1). Use mysqldump to export data from your 5.6 database server and then import that to MySQL 5.1. The output of mysqldump wraps newer syntax in special comments that will be ignored by older versions of MySQL Server.
Regardless, my recommendation is:

Find another hosting service running MySQL 5.6 or 5.7.
Develop and test your site with the same versions of all software (MySQL, PHP, Apache, etc.) that you will eventually deploy to.
Comment: Thanks for the info Bill. This gives me even less confidence in their support, as they themselves told me the BT connect server was running 5.1.1. which is clearly not true (believe me, I have more confidence in your information than I do in theirs). I do have another host lined up so will be recommending as you say.

MYSQL Backward compatible to 5.1.1?


conflito com googleapis jquery

Question: Estou a importar várias apis para no mesmo site, o problema é algumas deixam de trabalhar. Por exemplo, uma api para fazer um autocomplete, outra para fazer um efeito no menu e outra para uma caixa de feedback. Há alguma maneira de contornar estes conflitos? estou a chama-las da seguinte maneira:
No footer tenho o seguinte:

No header:
<link rel="stylesheet" href="js/layerslider/css/layerslider.css" />
<link rel="stylesheet" href="js/fancybox/jquery.fancybox.css" />

Para o autocomplete, também se encontra no header:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

Estou usando o autocomplete do jQueryUI.
Answer: Não dá para rodar várias versões diferentes do jQuery numa mesma página. Escolha apenas uma delas, de preferência a mais recente:

Outras dicas e recomendações:

A ordem dos

Eu apenas re-ordenei, e removi o jQuery duplicado. O jQuery precisa vir antes de tudo, pois os demais scripts dependem dele. Por isso é o primeiro que aparece.
Comment: mas sendo assim vou perder funcionalidades, certo?
Comment: Não. Você só precisa de um jQuery.
Comment: Por outro lado, talvez as bibliotecas que você esteja a carregar tenham algum conflito entre si ou exijam versões diferentes do jQuery. Não dá para adivinhar sem saber exatamente quais são. Edite a sua pergunta, incluindo TODOS os `
Comment: obrigado! já editei. Mas ao substituir apenas por um, houver funcionalidades que deixaram de trabalhar
Comment: Agora só não trabalha o autocomplete. O código do autocomplete está no header e o restante no footer. há problemas se estiver por essa ordem?
Comment: Você está confundindo as coisas. Você só precisa de um `
Comment: Entenda: quanto mais código você postar, melhor. :-) Ajude-nos a te ajudar.
Comment: ja editei, obrigado por continuar a ajudar!
Comment: agora só o autocomplete é que não funciona. O menu e seus efeitos e uma barra de feedback já trabalham.
Comment: Atualizei a resposta. Por favor, verifique se a sugestão funciona.
Comment: já verifiquei. ficou tudo a trabalhar! obrigado e um abraço! :)

conflito com googleapis jquery


Não permitir repetir valores em DropDownList diferentes usando jQuery?

Question: Eu tenho 3 DropDownList onde os mesmos tem 4 itens com o mesmo valor (1,2,3,4). Eu preciso respeitar q cada DropDownList não repita o valor selecionado nos outros.
Exemplo:
ddl0= 1
ddl1= 2 (não permitiria escolher os valores 1 e 3)
ddl2= 3 (não permitiria escolher os valores 1 e 2)

*ddl= DropDownList

Eu consegui fazer com 2 DropDownList dessa forma:
$(document).ready(function () {
$("#ddl0").on('change', function () {
  if ($(this).val() == '1') {
    $("#ddl1 option[value='1']").prop("disabled", true);
    $("#ddl1 option[value='2']").prop("disabled", false);
    $("#ddl1 option[value='3']").prop("disabled", false);
    $("#ddl1 option[value='4']").prop("disabled", false);

 } else if ($(this).val() == '2') {
    $("#ddl1 option[value='1']").prop("disabled", false);
    $("#ddl1 option[value='2']").prop("disabled", true);
    $("#ddl1 option[value='3']").prop("disabled", false);
    $("#ddl1 option[value='4']").prop("disabled", false);

 } else if ($(this).val() == '3') {
    $("#ddl1 option[value='1']").prop("disabled", false);
    $("#ddl1 option[value='2']").prop("disabled", false);
    $("#ddl1 option[value='3']").prop("disabled", true);
    $("#ddl1 option[value='4']").prop("disabled", false);

 } else if ($(this).val() == '4') {
    $("#ddl1 option[value='1']").prop("disabled", false);
    $("#ddl1 option[value='2']").prop("disabled", false);
    $("#ddl1 option[value='3']").prop("disabled", false);
    $("#ddl1 option[value='4']").prop("disabled", true);

    }
   });
 });

agora entrando com um terceiro DropDownList. Como conseguiria fazer para nenhuma das ddls ficarem com valores repetidos?
Answer: Cada vez que ocorrer o evento change de um select, você cria um Array com todos os valores que já foram marcados.
Depois, você pode usar o método $.inArray() para desabilitar os options cujos valores estejam neste Array.

$(document).ready(function() {
  let s = $('select[id^=ddl]'), o = s.children();
  s.change(function() {
    let valores = [];
    s.find('option[value]:selected').each(function() { valores.push($(this).val()); });
    $(o).each(function() {
      $(this).prop('disabled', $.inArray(this.value, valores) !== -1);
    });
  });
});

<select id="ddl0">
   <option>...</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

<select id="ddl1">
   <option>...</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

<select id="ddl2">
   <option>...</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>
Comment: Obrigado pela ajuda LLeon.
Answer: Você pode fazer uma função genérica, em vez de repetir vários if's. Fiz da forma abaixo que creio que resolve (veja os comentários no código com algumas explicações). Também coloquei uma propriedade CSS com fundo vermelho para os options desabilitados para melhor ilustração no exemplo:

$(document).ready(function(){

   // seleciona todos os ddls que começam com o id "ddl"
   var ddls = $("[id^=ddl]");

   ddls.on("change", function(){

      // declara a array
      var slots = [];

      // busca option selecionado nas ddls
      var opts = ddls.find("option:selected");

      // laço para alimentar a array com os values selecionados
      opts.each(function(){

         var v = $(this).attr("value");

         // só inclui na array values com algum valor
         if(v) slots.push(v);

      });

      // redefino a variável opts, agora com todos os options
      opts = ddls.find("option");
      opts.each(function(){

         var t = $(this);

         // desabilita o option se o seu value estiver na array e não esteja selecionado
         t.prop("disabled", ~slots.indexOf(t.attr("value")) && !t.is(":selected") ? true : false);

      });

   });

});
option:disabled{
   background: red;
}

<select id="ddl0">
   <option>...</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

<select id="ddl1">
   <option>...</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

<select id="ddl2">
   <option>...</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

Abaixo o código "limpo":
$(document).ready(function(){

   var ddls = $("[id^=ddl]");
   ddls.on("change", function(){
      var slots = [];
      var opts = ddls.find("option:selected");
      opts.each(function(){
         var v = $(this).attr("value");
         if(v) slots.push(v);
      });
      opts = ddls.find("option");
      opts.each(function(){
         var t = $(this);
         t.prop("disabled", ~slots.indexOf(t.attr("value")) && !t.is(":selected") ? true : false);
      });
   });

});

Comment: Ficou ótimo, foi de grande ajuda sua explicação. Muito obrigado!


Como usar uma thread específica de uma classe com múltiplas threads?

Question: Estou com uma classe chamada Bola onde nela tenho uma thread que faz umas bolinhas se movimentarem na fase 1 de um do jogo. É possível eu implementar nessa mesma classe outra thread que faça as bolinhas se movimentarem de forma diferente no caso para fase 2 do jogo, se possível deixem um exemplo de como posso ter as 2 thread na mesma classe e como posso acessar cada uma.
Aqui está o código:
import java.awt.Rectangle;

public class Bola extends Thread {
private int x,y,tamanho;
private int direcao;
int opcao;

public Bola(int x,int y,int tamanho){
    this.x=x;
    this.y=y;
    this.tamanho=tamanho;
}

@Override

public void run() {
    super.run();
    while(1==1){

        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(x<150){
            direcao=1;

        }
        if(x>700){
            direcao=0;

        }
        if(direcao==1){
            x++;

        }
        if(direcao==0){
            x--;
        }
    }
//aqui gostaria de por outra thread, do mesmo jeito da primeira,porém vai //alterar o y...dai na classe da fase eu gostaria de chamar apenas essa thread //que altera o y

}

public Rectangle colisao(){
    return new Rectangle(x, y, tamanho, tamanho);
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}

public int getTamanho() {
    return tamanho;
}

public void setTamanho(int tamanho) {
    this.tamanho = tamanho;
}

}

Comment: A fase 1 do jogo ocorre **simultaneamente** à fase 2? Se não, não há razão para se criar duas threads... Use a mesma! O que você precisa é: a) uma classe para cada fase, como sugerido por @epx; ou b) uma classe **parametrizável** - se o comportamento da bolinhas é parecido em ambas as fases, o que muda é só alguns parêmetros (como velocidade, acelaração, ângulo etc). Se tiver alguma dúvida específica, poste trecho(s) do código que você já tem, e o que está causando dificuldade.
Comment: Não dá para você colocar um pouco de código aqui para tentarmos entender exatamente como você estruturou isso?
Comment: A pergunta está meio troncha mas falando muito genericamente parece melhor implementar o comportamento de cada fase numa classe diferente
Comment: Seria essa questão um trabalho de escola?
Comment: O título da sua pergunta está um pouco esquisito mesmo, talvez porque você esteja misturando na pergunta uma ideia de solução que você já tem. Talvez se vc mudar o título (e talvez até mesmo o texto, não sei) mais para o que você quer fazer, a questão atraia mais pessoas interessadas em responder.
Answer: Você não "acessa" uma thread. Você inicia ela, e ela continua executando. Diga-se de passagem, o seu programa já está rodando em uma thread -- o que você faz é iniciar novas threads.
É possível coordenar threads usando diversos recursos: sincronização, semáforos, objetos compartilhados, etc. Mas para saber o que é mais apropriado no seu caso, é necessário definir  porque você deseja uma thread para cada fase e o que isso vai trazer de benefício?
Também seria útil que você mostrasse detalhes da classe já existente, para sabermos como essa thread é criada e utilizada.
Answer: Como o @rdllopes já mencionou na resposta dele, não é uma boa prática fazer os seus objetos serem executados em threads diferentes, pois é muito comum que jogos tenham muitos objetos e fica bastante custoso para o sistema operacional fazer o escalonamento de muitas threads.
Em jogos é mais comum ter apenas uma ou duas threads, como por exemplo uma para gerenciar a interface do usuário (a thread principal, digamos) e outra para gerenciar o game loop do jogo.
Você não mencionou se está fazendo um jogo só pra aprender programação em Java ou para produzir um jogo realmente. Se não for para aprendizado, muito provavelmente será mais fácil (e produtivo) se você utilizar um Motor de Jogo pronto. Tais ferramentas facilitam muitíssimo o desenvolvimento de jogos por que já incluem o game loop, funções de áudio e de tratamento de entrada, e (em muitos casos) até mesmo bibliotecas para a simulação da física e da inteligência artificial. No caso do Java, um motor bastante famoso é o JMonkeyEngine.
Além do assunto da thread a sua questão também é sobre como ter comportamentos distintos em um objeto de jogo (uma bola). Por isso, eu preparei um exemplo para sugerir uma forma de implementação.
Antes de começar, é importante que você se familiarize com vetores e com a classe Vector2D (de autoria de Jadrian Miles). Vetores são importantes no código porque são utilizados para representar a posição das bolas e sua velocidade.
import java.awt.geom.Point2D;
import java.lang.Math;

/**
 * An extension to the relatively impotent java.awt.geom.Point2D.Double,
 * Vector2D allows mathematical manipulation of 2-component vectors.
 *
 * @author Jadrian Miles
 * @version 20031122
 */
public class Vector2D extends Point2D.Double {

    /*
     * (non-Javadoc)
     *
     * @see java.awt.geom.Point2D.Double#Point2D.Double()
     */
    public Vector2D() {
        super();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.awt.geom.Point2D.Double#Point2D.Double()
     */
    public Vector2D(double x, double y) {
        super(x, y);
    }

    /**
     * Copy constructor
     */
    public Vector2D(Vector2D v) {
        x = v.x;
        y = v.y;
    }

    /**
     * @return the radius (length, modulus) of the vector in polar coordinates
     */
    public double getR() {
        return Math.sqrt(x * x + y * y);
    }

    /**
     * @return the angle (argument) of the vector in polar coordinates in the
     *         range [-pi/2, pi/2]
     */
    public double getTheta() {
        return Math.atan2(y, x);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.awt.geom.Point2D.Double#setLocation(double, double)
     */
    public void set(double x, double y) {
        super.setLocation(x, y);
    }

    /**
     * Sets the vector given polar arguments.
     *
     * @param r
     *            The new radius
     * @param t
     *            The new angle, in radians
     */
    public void setPolar(double r, double t) {
        super.setLocation(r * Math.cos(t), r * Math.sin(t));
    }

    /** Sets the vector's radius, preserving its angle. */
    public void setR(double r) {
        double t = getTheta();
        setPolar(r, t);
    }

    /** Sets the vector's angle, preserving its radius. */
    public void setTheta(double t) {
        double r = getR();
        setPolar(r, t);
    }

    /** The sum of the vector and rhs */
    public Vector2D plus(Vector2D rhs) {
        return new Vector2D(x + rhs.x, y + rhs.y);
    }

    /** The difference of the vector and rhs: this - rhs */
    public Vector2D minus(Vector2D rhs) {
        return new Vector2D(x - rhs.x, y - rhs.y);
    }

    public boolean equals(Vector2D rhs) {
        return x == rhs.x && y == rhs.y;
    }

    /** Product of the vector and scalar */
    public Vector2D scalarMult(double scalar) {
        return new Vector2D(scalar * x, scalar * y);
    }

    /** Dot product of the vector and rhs */
    public double dotProduct(Vector2D rhs) {
        return x * rhs.x + y * rhs.y;
    }

    /**
     * Since Vector2D works only in the x-y plane, (u x v) points directly along
     * the z axis. This function returns the value on the z axis that (u x v)
     * reaches.
     *
     * @return signed magnitude of (this x rhs)
     */
    public double crossProduct(Vector2D rhs) {
        return x * rhs.y - y * rhs.x;
    }

    /** Product of components of the vector: compenentProduct( <x y>) = x*y. */
    public double componentProduct() {
        return x * y;
    }

    /** Componentwise product: <this.x*rhs.x, this.y*rhs.y> */
    public Vector2D componentwiseProduct(Vector2D rhs) {
        return new Vector2D(x * rhs.x, y * rhs.y);
    }

    /**
     * An alias for getR()
     * @return the length of this
     */
    public double length() {
        return getR();
    }

    /**
     * Returns a new vector with the same direction as the vector but with
     * length 1, except in the case of zero vectors, which return a copy of
     * themselves.
     */
    public Vector2D unitVector() {
        if (getR() != 0) {
            return new Vector2D(x / getR(), y / getR());
        }
        return new Vector2D(0,0);
    }

    /** Polar version of the vector, with radius in x and angle in y */
    public Vector2D toPolar() {
        return new Vector2D(Math.sqrt(x * x + y * y), Math.atan2(y, x));
    }

    /** Rectangular version of the vector, assuming radius in x and angle in y*/
    public Vector2D toRect() {
        return new Vector2D(x * Math.cos(y), x * Math.sin(y));
    }

    /** @return Standard string representation of a vector: "<x, y>" */
    public String toString() {
        return "<" + x + ", " + y + ">";
    }
}

A classe mais importante do exemplo que eu preparei se chama simplemenge Game. Eu fiz ela como uma Applet, mas você pode construir uma janela em Swing, por exemplo. O princípio é o mesmo: ela implementa a interface Runnable porque ela é quem implementa a thread do game loop! O código está a seguir:
import java.awt.BorderLayout;

import javax.swing.JApplet;

/**
 * Classe principal, de implementação do jogo.
 * Exemplo para ilustração no SOPT.
 * @author Luiz C. Vieira
 */
@SuppressWarnings("serial")
public class Game extends JApplet implements Runnable {

    /** Thread de execução da applet. */
    private Thread m_oMainThread;

    /** Indicador de que o jogo está em execução. */
    private boolean m_bRunning;

    /** Taxa de quadros por segundo (framerate) ideal do jogo. */
    private static float FPS = 1000f / 60f;

    /**
     * Método de inicialização da applet do jogo.
     */
    @Override
    public void init() {
        super.init();

        // Define tamanho da janela de jogo
        setSize(800, 600);

        // Adiciona a cena ao jogo
        setLayout(new BorderLayout());
        add(GameScene.instance);

        // Cria e inicia a thread de execução do jogo
        m_bRunning = true;
        m_oMainThread = new Thread(this);
    }

    /**
     * Método de início da applet do jogo.
     */
    @Override
    public void start() {
        super.start();
        m_oMainThread.start();
    }

    /**
     * Método de interrupção da applet do jogo.
     */
    @Override
    public void stop() {
        super.stop();
        m_bRunning = false;
    }

    /**
     * Método de execução da thread da applet do jogo.
     * Basicamente implementa o game loop, atualizando na cena
     * todos os componentes a cada quadro (cada iteração).
     */
    @Override
    public void run() {

        long lPrevious = System.nanoTime() / 1000000;
        long lLag = 0;

        // Gameloop do jogo
        while(m_bRunning) {

            // Contabilização de tempo
            long lCurrent = System.nanoTime() / 1000000;
            long lElapsed = lCurrent - lPrevious;
            lPrevious = lCurrent;
            lLag += lElapsed;

            // Processamento de entrada (teclado, mouse, etc) vai aqui!
            // TODO

            // Atualização do mundo!
            // Faz chamadas de update enquanto o número desejado de quadros
            // por segundo não tiver sido atingido
            while(lLag >= Game.FPS)
            {
                GameScene.instance.update();
                lLag -= Game.FPS;
            }

            // Renderização do jogo!
            GameScene.instance.repaint();

        }
    }
}

Essa classe funciona assim:

Na inicialização, ela adiciona o objeto singleton da classe GameScene (o cenário do jogo) sob um layout.
Então, cria uma thread que executará o método run do próprio objeto (this).
O método run contém propriamente o game loop. O que ele faz é continuamente executar GameScene.instance.update(); (a simulação do mundo) e GameScene.instance.repaint(); (a atualização da tela do jogo), buscando controlar a taxa de atualização dos quadros do jogo (procure ler mais sobre framerate e gameloop na Internet se já não souber do que se trata, pois vale a pena).

A outra classe chama-se GameScene e se trata meramente de uma classe que herda de JComponent para ser adicionada à Applet, mas que especialmente contém todos os objetos do jogo. Note que eu fiz essa classe um singleton, mas idealmente você pode ter diferentes instâncias dela para cada fase. Ou seja, a ideia é que essa classe representa a cena ou fase atual do jogo. Aqui está o código:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JComponent;

/**
 * Classe de implementação de cenas de jogo.
 * @author Luiz C. Vieira
 */
@SuppressWarnings("serial")
public class GameScene extends JComponent {

    /** Referência estática do vetor da gravidade. */
    public static Vector2D GRAVITY = new Vector2D(0, 1);

    /** Referência estática dos limites do mundo. */
    public static Rectangle BOUNDS = new Rectangle(0, 0, 800, 600);

    /** Matriz com as bolas instanciadas na cena. */
    private ArrayList<Ball> m_lsBalls;

    /** Instância singleton da cena. */
    public static GameScene instance = new GameScene();

    /**
     * Construtor protegido.
     */
    protected GameScene() {
        // Cria 10 bolas aleatoriamente
        m_lsBalls = new ArrayList<Ball>();

        Color aColors[] = { Color.white, Color.blue, Color.red, Color.green, Color.orange, Color.cyan };
        Random oRnd = new Random();

        for(int i = 1; i <= 5; i++) {

            int iRadius = oRnd.nextInt(50) + 10;
            Color oColor = aColors[oRnd.nextInt(aColors.length)];

            Ball oBall = new Ball(iRadius, oColor);

            oBall.setPosition(new Vector2D(oRnd.nextDouble() * 800, oRnd.nextDouble() * 600));
            oBall.setVelocity(new Vector2D(oRnd.nextDouble() * 10, oRnd.nextDouble() * 10));

            // A primeira bola não perde velocidade!
            if(i == 1) {
                oBall.setBounciness(1);
                oBall.setVelocity(new Vector2D(5, 0));
            }

            // A terceira bola não tem gravidade!
            else if(i == 3) {
                oBall.setOwnGravity(new Vector2D(0, 0));
                oBall.setOwnGravityEnabled(true);
            }

            // A quinta bola tem a gravidade invertida (isto é, "cai pra cima")!
            else if(i == 5) {
                oBall.setOwnGravity(new Vector2D(0, -1));
                oBall.setOwnGravityEnabled(true);
            }

            m_lsBalls.add(oBall);
        }
    }

    /**
     * Método de atualização da cena. É chamado a cada quadro do jogo.
     */
    public void update() {
        // Atualiza todos os objetos em cena
        for(Ball oBall: m_lsBalls) {
            oBall.update();
        }
    }

    /**
     * Método de pintura da cena.
     * @param g Intância com o objeto Graphics da applet para pintura.
     */
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Pinta o fundo da cena (simplesmente todo branco nesse exemplo)
        g.setColor(Color.black);
        g.fillRect(0, 0, GameScene.BOUNDS.width, GameScene.BOUNDS.height);

        // Faz a repintura de cada um dos objetos em cena
        for(Ball oBall: m_lsBalls) {
            oBall.paint(g);
        }
    }

    /**
     * Getter de acesso aos objetos em cena.
     * @return ArrayList com os objetos na cena.
     */
    public ArrayList<Ball> getBalls() {
        return m_lsBalls;
    }
}

O método principal dessa classe é o update, que é chamado lá no game loop a cada quadro do jogo. O que esse método faz parece bem simples, mas é fundamental: ele chama o método update de cada objeto em cena, de forma que eles possam se atualizar de maneira apropriada. O método paintComponent é também importante porque é onde se implementa a renderização (desenho) da cena. Note que ele também executa o método paint de cada objeto para que eles possam se desenhar na tela.

IMPORTANTE: A cena do jogo é herdada de JComponent porque essa classe
  (assim como JPanel, por exemplo) já implementa
  um controle de pintura chamado double buffering. Sem esse
  controle, a repintura da tela a cada quadro (controlada pelo game loop)
  faz a tela piscar (efeito conhecido como flickering).

Você vai notar que no construtor dessa classe eu crio 5 bolas com tamanho e cores aleatórias. Mas, mais importante (e relacionado à sua questão) eu configuro as bolas 1, 3 e 5 com "comportamentos" distintos que eu defini, como por exemplo fazer com que uma não obedeça a gravidade do mundo e que outra não perca velocidade ao colidir. Dá pra você brincar ai como quiser, e a grande sacada é controlar as especificidades de cada bola por meio de atributos e alterações na classe Ball.
Aliás (e finalmente!), eis aqui o código da classe Ball:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.util.ArrayList;

    /**
     * Classe bola para exemplificação no SOPT.
     * Ela não implementa thread! Esse controle fica por parte das classes
     * Game e GameScene que executam o método update.
     * @author Luiz C. Vieira
     */
    public class Ball {

        /** Vetor com a posição atual da bola. */
        private Vector2D m_vPosition;

        /** Vetor velocidade (direção de movimentação + velocidade do movimento) da bola. */
        private Vector2D m_vVelocity;

        /** Raio da bola pixels. */
        private int m_iRadius;

        /** Cor da bola. */
        private Color m_oColor;

        /** Indicador a respeito da bola usar a própria gravidade. */
        private boolean m_bOwnGravity;

        /** Vetor de gravidade específico para a bola. */
        private Vector2D m_vOwnGravity;

        /** Indicação de modo de depuração, para desenho do vetor velocidade. */
        private static boolean DEBUG = true;

        /**
         * Fator de ressalto da bola, indicando qual proporção da velocidade a bola deve
         * perder ao se chocar (colidir) com outro objeto no mundo. Valores válidos são
         * no intervalo [0, 1]. O valor 0 indica que a bola simplesmente não quica (isto é,
         * para completamente ao se chocar com algo). O valor 1 indica que a bola quica totalmente
         * (isto é, não perde velocidade alguma ao se chocar).
         */
        private float m_fBounciness;

        /**
         * Construtor padrão. Inicializa a bola com valores predefinidos.
         */
        public Ball() {
            m_iRadius = 25;
            m_fBounciness = 0.8f;
            m_vPosition = new Vector2D(0, 0);
            m_vVelocity = new Vector2D(0, 0);
            m_oColor = Color.red;
            m_bOwnGravity = false;
            m_vOwnGravity = new Vector2D(0, 1);
        }

        public Ball(int iRadius, Color oColor) {
            m_iRadius = iRadius;
            m_fBounciness = 0.8f;
            m_vPosition = new Vector2D(0, 0);
            m_vVelocity = new Vector2D(0, 0);
            m_oColor = oColor;
            m_bOwnGravity = false;
            m_vOwnGravity = new Vector2D(0, 1);
        }

        /**
         * Getter da posição atual da bola.
         * @return Vetor com a posição atual da bola.
         */
        public Vector2D getPosition() {
            return m_vPosition;
        }

        /**
         * Setter da posição atual da bola.
         * @param vPosition Vetor com a nova posição para a bola.
         */
        public void setPosition(Vector2D vPosition) {
            m_vPosition = vPosition;
        }

        /**
         * Getter da velocidade da bola.
         * @return Vetor com a velocidade atual da bola.
         */
        public Vector2D getVelocity() {
            return m_vVelocity;
        }

        /**
         * Setter da velocidade da bola.
         * @param vVelocity Vetor com a nova velocidade da bola.
         */
        public void setVelocity(Vector2D vVelocity) {
            m_vVelocity = vVelocity;
        }

        /**
         * Getter do raio da bola.
         * @return Raio da bola em pixels.
         */
        public int getRadius() {
            return m_iRadius;
        }

        /**
         * Setter do raio da bola.
         * @param iRadius Novo raio da bola, em pixels.
         */
        public void setRadius(int iRadius) {
            m_iRadius = iRadius;
        }

        /**
         * Getter do fator de ressalto da bola.
         * @return Float com o fator de ressalto da bola, no intervalo [0, 1].
         */
        public float getBounciness() {
            return m_fBounciness;
        }

        /**
         * Setter do fator de ressalto da bola.
         * @param fBounciness Float com o fator de ressalto da bola, no intervalo [0, 1].
         * Valores fora do intervalo são ajustados para a extremidade limitante.
         */
        public void setBounciness(float fBounciness) {
            if (fBounciness < 0.0f)
                m_fBounciness = 0.0f;
            else if(fBounciness > 1.0f)
                m_fBounciness = 1.0f;
            else
                m_fBounciness = fBounciness;
        }

        /**
         * Getter da indicação de gravidade específica da bola habilitada.
         * @return Booleano indicando se está ou não habilitada.
         */
        public boolean getOwnGravityEnabled() {
            return m_bOwnGravity;
        }

        /**
         * Setter da indicação de gravidade específica da bola habilitada.
         * @param bEnable Booleano indicando se deve ou não habilitar.
         */
        public void setOwnGravityEnabled(boolean bEnabled) {
            m_bOwnGravity = bEnabled;
        }

        /**
         * Getter da gravidade específica da bola.
         * @return Vetor com a gravidade específica da bola.
         */
        public Vector2D getOwnGravity() {
            return m_vOwnGravity;
        }

        /**
         * Setter da gravidade específica da bola.
         * @param vOwnGravity Vetor com a nova gravidade específica da bola.
         */
        public void setOwnGravity(Vector2D vOwnGravity) {
            m_vOwnGravity = vOwnGravity;
        }

        /**
         * Método de desenho da bola. É chamado pela cena sempre que for necessário
         * repintar a bola.
         * @param g Instância do objeto Graphics para pintura da bola.
         */
        public void paint(Graphics g) {
            // Simplesmente desenha no Graphics uma bola (mas poderia copiar uma
            // imagem ou um quadro de uma animação).
            Vector2D vTopLeft = new Vector2D(m_vPosition.x - m_iRadius, m_vPosition.y - m_iRadius);
            int iDiameter = 2 * m_iRadius;
            g.setColor(m_oColor);
            g.fillOval((int) vTopLeft.x, (int) vTopLeft.y, iDiameter, iDiameter);

            // Se a depuração está ligada, desenha o vetor velocidade
            if(Ball.DEBUG) {
                g.setColor(Color.yellow);
                Vector2D vVel = m_vVelocity.scalarMult(10); // Escala x10 para facilitar a visualização
                Vector2D vAux = m_vPosition.plus(vVel);
                g.drawLine((int) m_vPosition.x, (int) m_vPosition.y, (int) vAux.x, (int) vAux.y);
            }
        }

        /**
         * Método de atualização do objeto. É chamado a cada quadro do jogo.
         */
        public void update() {
            // Adiciona a gravidade à velocidade da bola
            // Ou seja: Velocidade = Velocidade + Gravidade
            if(!m_bOwnGravity)
                m_vVelocity = m_vVelocity.plus(GameScene.GRAVITY);
            else
                m_vVelocity = m_vVelocity.plus(m_vOwnGravity);

            // Atualiza a posição da bola de acordo com a velocidade (direção e valor)
            m_vPosition = m_vPosition.plus(m_vVelocity);

            // Trata colisões com o mundo e com outras bolas
            handleCollisions();
        }

        /**
         * Método de tratamento das colisões. Simplesmente inverte o vetor nos eixos x e y quando
         * a bola se choca com as bordas do mundo, e calcula o vetor inverso à direção em que as bolas
         * se chocam umas com as outras.
         * OBSERVAÇÃO: É apenas um exemplo BEM SIMPLES, não inclui cálculos da física relativos à quantidade
         * de movimento, coeficientes de restituição, energia elástica, etc.
         */
        protected void handleCollisions() {
            boolean bCollided = false;

            // Primeiro, trata a colisão com os limites do mundo, simplesmente invertendo
            // a velocidade de acordo com a borda com que a bola colidir.
            Rectangle oBounds = GameScene.BOUNDS;
            if(m_vPosition.x - m_iRadius <= oBounds.x) {
                m_vPosition.x = oBounds.x + m_iRadius;
                m_vVelocity.x *= -1;
                bCollided = true;
            }
            else if(m_vPosition.x + m_iRadius >= oBounds.width) {
                m_vPosition.x = oBounds.width - m_iRadius;
                m_vVelocity.x *= -1;
                bCollided = true;
            }

            if(m_vPosition.y - m_iRadius <= oBounds.y) {
                m_vPosition.y = oBounds.y + m_iRadius;
                m_vVelocity.y *= -1;
                bCollided = true;
            }
            else if(m_vPosition.y + m_iRadius >= oBounds.height) {
                m_vPosition.y = oBounds.height - m_iRadius;
                m_vVelocity.y *= -1;
                bCollided = true;
            }

            // Agora, trata a colisão da bola com as demais bolas
            ArrayList<Ball> lsBalls = GameScene.instance.getBalls();
            for(Ball oOtherBall: lsBalls) {
                if(!oOtherBall.equals(this)) { // Naturalmente, ignora a si próprio

                    // Checar colisão entre círculos é beeeeemmmm fácil!
                    // Duas bolas estão em colisão se a distância entre seus pontos
                    // centrais for menor ou igual do que a soma de seus raios.
                    double dDistance = m_vPosition.distance(oOtherBall.getPosition());
                    if(dDistance <= m_iRadius + oOtherBall.getRadius()) {

                        // Obtém o vetor unitário (normalizado) que aponta para a direção em que a bola colidou com a outra.
                        // Simples aritmética de vetores: http://pt.wikipedia.org/wiki/Vetor_(matem%C3%A1tica)#Subtra.C3.A7.C3.A3o
                        Vector2D vForceDir = m_vPosition.minus(oOtherBall.getPosition()).unitVector();

                        // Ajusta a posição da bola atual para que ela fique garantidamente "fora"
                        // da outra bola
                        Vector2D vAway = new Vector2D(vForceDir.x, vForceDir.y);
                        vAway.setR(m_iRadius + oOtherBall.getRadius());
                        m_vPosition = oOtherBall.getPosition().plus(vAway);

                        // A "força" com que a bola será ricocheteada é igual à soma das velocidades das duas bolas
                        double dSpeed = m_vVelocity.length() + oOtherBall.getVelocity().length();
                        Vector2D vForce = new Vector2D(vForceDir.x, vForceDir.y);
                        vForce = vForce.scalarMult(dSpeed);

                        // Soma o vetor força com a velocidade da bola
                        m_vVelocity = m_vVelocity.plus(vForce);
                        bCollided = true;
                    }
                }
            }

            // Aplica o fator de ressalto à bola se ela colidiu com algo
            if(bCollided)
                m_vVelocity = m_vVelocity.scalarMult(m_fBounciness);
        }
    }

Essa classe usa e abusa de vetores, e eu honestamente espero que os comentários te ajudem a entender (caso você já não entenda bastante do assunto - caso você entenda, desculpe por eu ser tão didático). Mas o mais importante ai é que você vai notar que ela não herda de nada! O ponto-chave são, novamente, os métodos update e paint. No método update, a velocidade da bola é atualizada com a gravidade e as colisões são verificadas (para diminuir uma pequena parte da velocidade a cada colisão e para alterar a direção da velocidade conforme as colisões). Já no método paint a bola é simplesmente desenhada. Fiz um exemplo bem bobo, mas você pode desenhar uma imagem ou mesmo uma animação (desenhando um quadro por vez a cada chamada de paint, por exemplo).
A "simulação de física" (se é que ela pode ser assim chamada) é beeeemmmm inocente, mas serve para exemplificar (e pra tornar tudo mais divertido!). O resultado final é uma janela com 5 bolas que se movem e se chocam umas com as outras, algo como ilustra a figura abaixo:

As linhas amarelas são de depuração e indicam os vetores de velocidade. Desligue fazendo Ball.DEBUG = false;.
E é isso ai. Boa sorte com o seu jogo. :)
Comment: muito obrigado pessoal, juntei um pouco da resposta de cada um e implementei a thread na mesma classe,criei uma lógica aqui que deu certo, obrigado!
Answer: Bom, você não  "deveria", mas você pode sim fazer uma classe estender de Objeto e utilizá-la numa simulação.
Ex:
public class Bola
    extends Thread {

    private float directionX;
    private float posX = 0;
    private boolean should_run;

    Bola(float x, float posX) {
        directionX = x;
        should_run = true;
    }

    @Override
    public void run() {
        while (should_run) {
            posX = posX + directionX;
            System.out.println(this + "\tposX:" + posX);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                should_run = false;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Bola[] bolas =
            { new Bola(1, 0), new Bola(-1, 0) };
        for (Bola bola : bolas) {
            bola.start();
        }
        Thread.sleep(1000);
        bolas[0].should_run = false;
        bolas[1].should_run = false;
        Thread.sleep(100);
    }
}

E por que não deveria?
Imagine que sua simulação tenha um milhão de bolas (partículas). Apesar desse modelo de uma thread por objeto ser convenientemente simples, no final o impacto de ter um milhão de thread rodando seria enorme. Seria muito melhor utilizar um Pool de Threads (ou usar algum outro mecanismo mais avançados de paralelização) e implementar cada partícula como uma tarefa (Task).
Answer: Se você quer controlar independentemente cada Thread você deve guardar referência para cada objeto criado à partir de sua Runnable e usar os métodos padrão do Ciclo de Vida da Thread para controlá-la. Veja este PDF http://www.inf.puc-rio.br/~inf1621/java2.pdf que descreve bem como isso funciona.


How do I Insert an image into email body?

Question: I want to send a image in email body using go lang.
Used this package from github
https://github.com/scorredoira/email
    err := m.Attach("image.png")
    if err1 != nil {
        fmt.Println(err1)
    }

Now i am able to send image file as attachment but my need is to send a image file in email body.
Thanks in advance.
Comment: https://github.com/scorredoira/email/blob/master/email.go#L55
Comment: @JimB, it won't also properly encode filename of the attached file, should it contain characters outside of the US-ASCII repertoire. A seemilgly more popular alternative, `gomail`, won't do that either but at least it has hooks allowing the programmer to arrange for providing the correct headers theirselves. I guessed dumping this on the OP would be a bit over the top though: I suppose it's better to solve one problem at a time.
Comment: how to use those function? @kostix
Comment: Why not just try it? The function signature is the same a Attach. Though, it's been a while since I read the specs, but the code doesn't look right to me, as it only sets a Content-Type of "message/rfc822", and no Content-Transfer-Encoding. (maybe email clients just figure it out on their own even if it's not correct per the RFCs)
Answer: You can use Gomail (I'm the author). Have a look at the Embed method which allow you to embed images in the email body:
package main

import "gopkg.in/gomail.v2"

func main() {
    m := gomail.NewMessage()
    m.SetHeader("From", "firstname.lastname@example.com")
    m.SetHeader("To", "firstname.lastname@example.com")
    m.SetHeader("Subject", "Hello!")
    m.Embed("image.png")
    m.SetBody("text/html", `<img src="cid:image.png" alt="My image" />`)

    d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")

    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
}

Comment: how to set `default dimension` for that image.?? @Ale
Comment: As you would in an HTML page: use the `width` HTML attribute or the `width` CSS property.
Comment: Awesome :-)...This package is very useful for me.
Comment: @Ale Im attempting to do something similar using your `Gomail`, mind checking out my question?...http://stackoverflow.com/questions/41113598/how-to-add-image-to-html-body-of-an-email-go


Problem with validating form function (Uncaught TypeError: Cannot read property 'value' of null)

Question: I'm doing an exercise on form validation in javascript, and I'm getting an error that I don't know how to fix in my function to validate if the user has chosen two hobbies before submitting the form:

"Uncaught TypeError: Cannot read property 'value' of null"

from:
var user = document.getElementById("idHobby").value;

I have tried several things, remove the .value, instead of innerHTML do textContent ...
This is my html code.

    My hobbies:
    <select name="hobbies" id="hobby" multiple>
      <option value="Programming">Programming</option>
      <option value="Reading">Reading</option>
      <option value="Singing">Singing</option>
      <option value="Dancing">Dancing</option>
      <element id="idHobby">
     </select>

And this is my JS function to validate that part of the form.
function validateHobbies(){

    let correct = true;
    let form = document.forms["form"];
    hobbies = document.getElementById("hobby").selectedIndex;
    var user = document.getElementById("idHobby").value;
    if (hobbies >=2){
        user.innerHTML= "Ok.";
        user.style.background="green";

    }
    else{
        user.textContent= "Choose two." ;
        user.style.background="red";
        correct = false;
    }

    return correct;
}

What i'm doing wrong?
Comment: Probably run the code before `#idHobby` element exists.
Comment: What is `` inside a select???
Comment: Hello mates, I did not realize that  was inside a select, sorry!!!
Answer: select element contains option elements. So you need to move your "element" outside. Now, this "element" doesn't have any value attribute, and since you want to style it 2 lines under it, you should omit that.
In this working snippet i used onchange event in order to invoke the function:

function validateHobbies(){

    let correct = true;
    let form = document.forms["form"];
    hobbies = document.getElementById("hobby").selectedIndex;
    var user = document.getElementById("idHobby");
    if (hobbies >=2){
        user.innerHTML= "Ok.";
        user.style.background="green";

    }
    else{
        user.textContent= "Choose two." ;
        user.style.background="red";
        correct = false;
    }

    return correct;
}

  My hobbies:
  <select name="hobbies" id="hobby" multiple onchange="validateHobbies()">
      <option value="Programming">Programming</option>
      <option value="Reading">Reading</option>
      <option value="Singing">Singing</option>
      <option value="Dancing">Dancing</option>
  </select>

Comment: Oh really, thank you very much !!! Also, I did not realize that  was inside a select, my apologies...


How do I use Topshelf with a .NET Core 2.1 application?

Question: I have an console application on .NET Core 2.1. I have used top-shelf to have it configure it as a windows service.
Has anyone successfully ,installed a .NET Core console application as a windows services using top-shelf.
Any documentation leading to that, would be helpful
Thanks
Answer: I've written a small library that allows you to run IHostedServices as a Windows service. The service is configured and run using Topshelf.
https://github.com/erizet/TopshelfHosting
Answer: This discussion can be useful: https://github.com/Topshelf/Topshelf/issues/455
TLDR: There is no stable version for the .NETCore 2.1 and even when it will be available you need to use self-contained application.
Answer: Was sucessfully able to install it using NSSM - the Non-Sucking Service Manager


Way to convert claims tokens to Kerberos that SP2010 accepts

Question: I'm hoping there is an F5 way to do what is described in this article:
http://blog.auth360.net/2010/12/03/the-triumvirate-uag-2010sp1-ad-fs-2-0-and-kerberos/
Users login to a mobile app using claims-based authentication at the front-end and need to connect to SharePoint 2010 using Kerberos at the back-end. SharePoint 2010 in this case does NOT support claims. A user will logon via AD FS and then need F5 to request a Kerberos ticket on behalf of the user and use that ticket to authenticate to SharePoint 2010. We're mixing authentication using claims-based authentication at the edge and then Kerberos for authenticating to SharePoint 2010.
Update:
I know SharePoint 2010 can support claims. In this case I am not allowed to modify the existing SharePoint 2010 environment.
Answer: You can use the Claims to Windows Token Service available with AD FS 2 to take a claims principal issued by AD FS and turn it into a constrained Kerberos ticket.
That being said, SharePoint 2010 definitely supports native Claims authentication used with the client object model.  It is not easy, but it is possible.
Further, if you have a SharePoint add-in which is what is really requiring use of Kerberos, SharePoint will automatically use C2WTS.
Comment: I know SharePoint can support claims. In this case I am not allowed to modify SharePoint. Updated my question with this. I will look into C2WTS. Thanks!


Como fazer este programa se repetir?

Question: Que comando é útil pra fazer o programa rodar desde o início ao chegar ao final??
f=float(input("Digite 0 para retânglo, 1 para triângulo:"))

if f==0:
    a=float(input("valor da altura:"))
    b=float(input("valor da base:"))
    print(a*b/2)
else:
    a=float(input("valor da altura:"))
    b=float(input("valor da base:"))
    print(a*b)

Comment: Você quer que programa rode pra sempre, é isso?
Comment: acho que vc ainda ñ viu a linguagem por completo, while talvez seja oq vc quer
Answer: Utilize o bloco de repetição while. A sintanxe do bloco é while bool:, onde, ele irá repetir o código enquanto a condição for True. Logo o seu programa pode ficar dessa forma:
stop = False

while not stop:

    f=float(input("Digite 0 para retângulo, 1 para triângulo:"))

    if f==0:
        a=float(input("valor da altura:"))
        b=float(input("valor da base:"))
        print(a*b/2)
    else:
        a=float(input("valor da altura:"))
        b=float(input("valor da base:"))
        print(a*b)

    if input("Deseja sair (Y/N) ? ").lower() == "y":
        stop = True

Como o valor inicialmente da variável stop é False e eu declarei um not, ela terá o valor True na sintaxe do while.
Caso o usuário digite "y" ou "Y", a variável stop terá o valor True, e na sintaxe do whileele terá o valor False. Dessa forma ele sai do bloco while e fecha o programa caso não exista mais código abaixo.

Como fazer este programa se repetir?


What exactly is meant by bias in this context?

Question: I'm working through an example of survival-time analysis with censored and un-censored data.
We're given the survival times of 94 patients.
Some of these survival times are censored i.e.in this context a censored survival time represents the "last time point when the patient was known to be alive."
We don't know whether and if so when a patient actually died. (could be that patient dropped out of the study, death by other causes etc.)
The textbook then goes on to say the following:
"we now now consider the $n=47$ non-censored survival times and assume they are exponentially distributed.
We emphasize that this approach is not generally acceptable as ignoring the censored observations will introduce bias if the distributions of censored and uncensored events differ."
My questions are:

What exactly do we mean by bias in this context?
(do we simply mean that we might be missing out on getting a better idea of what the true distribution of the survival times might be?)
Comment: I agree with your idea in the parenthesis. The survival time you're analyzing may have different distributions between two events (censored, uncensored), which can lead to bias in any further estimation (e.g. coefficients of covariates, etc).
Answer: As you mentioned we do not know what happens with the censored individuals. Let's say the event in question is death. In this case, censorship means we have not observed the patient die, therefore that information is unavailable. Censored patients may die in the near or far future, but the important thing is that we do not know when they will die (or whether they already did).
If we drop censored individuals from our study, we remove some information from our model. The only situation in which it would be ok to do this is if the distribution of time-of-death for censored and uncensored individuals is the same, otherwise, our analysis is biased.
Example: If we drop all censored individuals and they all actually died much later on after the last time they were observed our model estimates will be higher (higher rate ratio or hazard ratio, everyone appears to die faster than in reality) than it would actually be had we observed these individuals we have dropped.
As it may say in your book this is not good, assuming an exponential distribution corresponds to a Poisson regression approach, which in its standard format cannot deal with censoring. To deal with censoring it is better to use Cox regression. If you use R, have a look at the survival package.
Please let me know if anything is not clear.
Answer: It just means that as you increase your sample size (i.e. number of non-censored survival times available to you gets very large), the distribution you observe will not get closer and closer to the "true" distribution of survival times. That is, it will be biased, even as the variance is reduced by increasing your sample size.


Popular Content with statistics module incorrect

Question: So I wrote a custom module for displaying popular nodes, that is based on the buzzworthy module, but with a few tweaks. Buzzworthy has dependencies with the core statistics module.
The results are inaccurate, because when I compare with google analytics, GA yields different results. I know that GA has a latency issue, so it's like comparing apples and oranges, but another reason I know the list that my custom module displays is incorrect, is because it shows a blog post having waaaaaay more page views than it does normally.
Has anybody else had trouble with the accuracy produced by the statistics module? Is there a reason why my counts are incorrect?
Answer: There are many reasons the counts from different web counters are off (I had a former boss drive me nuts with that back in 1998 ...):

statistics module increments page counts on every reload
when a page is cached it might not increase the statistics counter, depending on the caching used. GA does increase because it's based on browser page loads
GA doesn't increase when bots are visiting your site (because they don't execute javascript)

I usually rely on GA for my business reports and just use statistics to show counts for my users.
You could also use the Google Analytics module to import GA numbers back into Drupal.


Find all solution of the following equation : $3^{m}-2^{n}=1$

Question: problem :
Find all solution of the following equation :

$$3^{m}-2^{n}=1$$

Where $m,n\in\mathbb{N}$
My try but not complete :
In first we see that $m=n=1$ is a solution
Also: $m=2,n=3$ a solution
But I don't know if have another solution or no
Is this equation has many solution ?
Comment: $m=1,n=1$? But $m=n=0 \implies 3^m-2^n = 1-1 = 0$
Comment: Yes sir thank you very much
Answer: This is a special case of Catalan's conjecture. The only solution is $m=2, n=3$
Comment: I see but how we prove that ? 2,3 are only a solution ?
Comment: Welcome! Would you mind giving a link/tutorial (instead of just a name)?
Comment: https://en.wikipedia.org/wiki/Catalan%27s_conjecture if you don't mind.


Complex Functions: Integrability

Question: Let $\Omega$ be a measure space with measure $\lambda$.
Denote the space of simple functions by:
$$\mathcal{S}:=\{s:\Omega\to\mathbb{C}:s=\sum_{k=1}^{K<\infty}s_k\chi_{A_k:\lambda(A_k)<\infty}\}$$
Denote the positive and negative part of the real and imaginary part by:
$$f=\Re_+f-\Re_-f+i\Im_+f-i\Im_-f=:\sum_{\alpha=0\ldots3}i^\alpha f_\alpha$$
Define for positive functions:
$$\int fd\lambda:=\sup_{s\in\mathcal{S}:s\leq f}\int sd\lambda\quad(f\geq 0)$$
and for complex functions:
$$\int fd\lambda:=\sum_{\alpha=1\ldots3}i^\alpha\int f_\alpha d\alpha$$
as long as all terms of the sum are finite.
(Note, measurability is not required here!)
Then a direct consequence is:
$$|\int fd\lambda|\leq\int|f|d\lambda$$
which shows that the a suitable integrability condition will be:
$$\int|f|d\lambda<\infty\implies\int f_\alpha d\lambda<\infty\quad(\alpha=0\ldots3)$$
Now, is it possible for the converse to actually fail:
$$\int|f|d\lambda<\infty\impliedby\int f_\alpha d\lambda<\infty\quad(\alpha=0\ldots3)$$
and what would be a demonstrative example?
Answer: Exploiting the estimates:
$$f_\alpha\leq|f|$$
$$|f|\leq\sum_{\alpha=0\ldots3}f_\alpha$$
one has by additivity and monotonicity of the integral:
$$\int f_\alpha d\lambda\leq\int|f|d\lambda$$
$$\int|f|d\lambda\leq\sum_{\alpha=0\ldots3}\int f_\alpha d\lambda$$
Concluding that:
$$f\in L(\lambda)\iff f_\alpha\in L(\lambda)\quad(\alpha=0\ldots3)$$

Complex Functions: Integrability


Object not instantiating properly

Question: I am currently using VS2015 for this.
I am trying to create a binary search tree in c++ so that I can learn both the language and the data structure while trying to see if I can follow good practices. However, I am coming through a problem where I am not properly instantiating the object properly in the driver file.
BSTHeader.h
#pragma once

/*
    Properties of Binary Search Tree:

    1.) Elements less than root will go to the left child of root
    2.) Elements greater than root will go to the right child of root
*/

#include <memory>

// Binary Search Tree handler class
class BSTHeader {

    /*
        Naive implementation of BSTNode (non-generic version)

        Nested class is private, but it's internal fields and member functions
        are public to outer class: BSTHeader
    */
    class BSTNode {
    public:
        int data;
        std::unique_ptr<BSTNode> left;
        std::unique_ptr<BSTNode> right;

        BSTNode(int val) {
            data = val;
            left = NULL;
            right = NULL;
        }
        ~BSTNode() {}
    };

    std::unique_ptr<BSTNode> root;           // Root of BST
    unsigned int size;                       // Total amount of nodes in tree from root

public:
    BSTHeader();
    BSTHeader(int val);
    ~BSTHeader();
    bool insert(std::unique_ptr<BSTNode>& root, int val);
}

BSTHeader.cpp
#include "BSTHeader.h"

/*
    Constructors:
*/
BSTHeader::BSTHeader() {
    root = NULL;
    size = 0;
}

BSTHeader::BSTHeader(int val) {
    root = std::unique_ptr<BSTNode>(new BSTHeader::BSTNode(val));       // Smart pointer to an internal BSTNode
    size = 1;
}

BSTHeader::~BSTHeader() {}                                              // Empty destructor from use of smart pointer

/*
    Member functions:
*/
bool BSTHeader::insert(std::unique_ptr<BSTNode>& root, int val) {
    if (root == NULL) {                                                 // Place new element here
        root = std::unique_ptr<BSTNode>(new BSTHeader::BSTNode(val));
        size++;
        return true;
    }

    if (val < root.get()->data) {                                       // val < root
        insert(root.get()->left, val);
    }

    else if (val > root.get()->data) {                                  // val > root
        insert(root.get()->right, val);
    }

The issue I get is here, where I believe I am trying to instantiate a BSTHeader object.
Program.cpp
#include "BSTHeader.h"

int main()
{
    BSTHeader::BSTHeader bst();   // <----- ERROR
    return 0;
}

The error I am getting is cannot determine which instance of overloaded function "BSTHeader:BSTHeader" is intended
However, whenever I do:
BSTHeader bst()
I am not able to access the insert(..., ...) function for the object doing bst.insert(..., ...) due to expression must have class type even though the error above does not appear.
Yet everything works fine and I am able to access all the member methods by doing this: BSTHeader bst(5) by using the overloaded constructor.
I am not sure whether its a namespace issue or not. I feel as though I am missing something.
Comment: Your error line is the _Most Vexing Parse_.  It looks like a function prototype, so that's what it is interpreted as.  Remove the `()`.
Comment: That fixed it, but does this mean that I should never include a () for accessing the default constructor?
Comment: @Naz Yep. You may use `{}` instead if you want to. but you should probably just leave it out.
Comment: Don't use `NULL` in modern C++. Use `nullptr` instead.
Comment: @JesperJuhl I was debating that, but I chose `NULL` only because I thought that the smartpointer object itself isn't actually a pointer to a smartpointer. Wasn't sure that `nullptr` also works for non-pointer objects. But thanks for that reference, will read up on this!
Answer: The line
BSTHeader::BSTHeader bst();   // <----- ERROR

is a declaration of a function named bst that takes no arguments and returns a BSTHeader::BSTHeader.
This is known as the "most vexing parse", and often described in less polite language.
If you want to instantiate an instance, giving the constructor no arguments, remove the ().

Object not instantiating properly


Question about interpreting correlations

Question: When reporting a positive correlation, I typically see things worded in the positive sense of the term... For example, for a positive correlation between eating vegetables and health outcomes you typically read something like: eating more vegetables was linked to better health outcomes. But would it be just as fine to report a correlation in the negative sense of the term? So for the same example of a positive correlation between eating vegetables and health outcomes would it be just as ok to say that eating less vegetables was linked to worse health outcomes? Or is it standard practice to always report in the positive sense of the term?
Thanks.
Answer: Yes, you can always reverse any variable and call it the opposite.
It usually helps the reader if you keep things positive, using the name that's usually used for the quantity. So you could say less vegetables is negatively associated with  health (or less vegetables is positively associated with more poor health), but you put some work onto the reader when you do that.
It's easier to talk about having stuff (intelligence, money, vegetables) than not having it.
Some variables have a clear description at each end, and you can choose the end that makes more sense:

happiness - sadness
extraversion - introversion
mobility - disability
Illiteracy - literacy

It doesn't make a difference (from a statistical point of view) which end you choose to be positive, but it can help with interpretation if you pick one or the other.
People often have problems with 'larger/smaller' vs 'higher/lower' correlations. 0.3 is higher and larger than 0.2. -0.3 is lower and larger than -0.2, so it can help to keep things positive (if you can).


Inserir na tabela da base de dados com o segundo formulário

Question: Tenho este menu:

Produtos de Higiene

Novo

Entrada

Depois tenho estes dois formulários:

<form class="form-validate" id="feedback_form">

        <fieldset>

                <legend>

                        Produtos de Higiene

        <fieldset class="grupo">

            Nome do Produto
            <input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">

        Unidade
            <input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">

        </fieldset>
        <button class="btn btn-success btn_contact" type="button">Registo</button>

sucessso

erro

</form>

<form name="form1" id="form1" class="form-validate" id="feedback_form">

         <fieldset>

                <legend>

                        Entrada de Produtos de Higiene

        <fieldset class="grupo">

            Data Entrada
            <input id="DataEntrada" type="date" name="DataEntrada" required="" style="width:180px" value="<?php echo date("Y-m-d");?>">

        </fieldset>
        <fieldset class="grupo">

        Produto
        <select id="first_dd" name="Produto" style="width:250px" required>
            <option></option>
            <?php
                $sql = "SELECT * FROM centrodb.ProdHigieneteste WHERE Ativo = 1 ORDER BY DescricaoProd ASC";
                $qr = mysqli_query($conn, $sql);
                while($ln = mysqli_fetch_assoc($qr)){
                    echo '<option value="'.$ln['IDProd'].'"> '.$ln['DescricaoProd'].'</option>';
                    $valencia[$ln['IDProd']]=array('DescricaoUnid'=>$ln['DescricaoUnid'],'DescricaoUnid'=>$ln['DescricaoUnid']);
                }
            ?>
        </select>
        Unidade
        <select id="second_dd" name="Unid" style="width:150px" required>
            <option></option>
            <?php
                foreach ($valencia as $key => $value) {
                    echo '<option data-id="'.$key.'" value="'.$value['DescricaoUnid'].'">'.$value['DescricaoUnid'].'</option>';
                }
            ?>
        </select>

        </fieldset>
        <fieldset class="grupo">

        Quantidade
            <input type="text" id="Quantidade" name="Quantidade" style="width:80px" required="" size="40">
        Preço
            <input type="text" id="Preco" name="Preco" style="width:100px" value="0.00">

    </fieldset>
        <button class="btn btn-success btn_contact" type="button">Registo</button>

sucessso

erro

    </form>

tenho este script para enviar os dados para a página onde tem o código php para
inserir na tabela:

Depois tenho a página onde tenho o código php para inserir:
Código 1º formulário:
<?php

$name = isset($_POST["DescricaoProd"]) ? $_POST["DescricaoProd"] : '';
$unid = isset($_POST["DescricaoUnid"]) ? $_POST["DescricaoUnid"] : '';

if (!empty($name) && !empty($unid)) {
   echo json_encode("true");
} else {
    echo json_encode("false");
}

$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql)) { // check for === TRUE is not necessary
   // either put the second query in here, or just enjoy the success
} else {
   // get the error, throw a message...
}

$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";

$query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

if ($conn->query($sql1) === TRUE) {
    //Count total number of rows
    $rowCount = $query->num_rows;
} else {
    // get the error, throw a message...
}

$conn->close();
?>

Código 2º formulário:
<?php

$data = isset($_POST["DataEntrada"]) ? $_POST["DataEntrada"] : '';
$produto = isset($_POST["Produto"]) ? $_POST["Produto"] : '';
$unidade = isset($_POST["Unid"]) ? $_POST["Unid"] : '';
$quantidade = isset($_POST["Quantidade"]) ? $_POST["Quantidade"] : '';
$preco = isset($_POST["Preco"]) ? $_POST["Preco"] : '';

if (!empty($data) && !empty($produto) && !empty($unidade) && !empty($quantidade) && !empty($preco)) {
   echo json_encode("true");
} else {
    echo json_encode("false");
}

$sql2 = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco)
VALUES ('$data','$produto','$unidade','$quantidade','$preco')";

if ($conn->query($sql2)) { // check for === TRUE is not necessary
   // either put the second query in here, or just enjoy the success
} else {
   // get the error, throw a message...
}

$sql3 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;

 $query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

if ($conn->query($sql3) === TRUE) {
    //Count total number of rows
    $rowCount = $query->num_rows;
} else {
    // get the error, throw a message...
}

$conn->close();
?>

O problema que tenho, é que quando faço registo no primeiro formulário funciona tudo bem, insere na tabela e limpa o formulário, mas quando tento fazer registo no segundo formulário não insere na tabela nem limpa o formulário, e faz o registo nas tabelas do primeiro formulário e em branco.
Comment: seus forms não tem nenhuma action?
Comment: @MatheusReis Não precisa, porque tem o `ajax` para enviar os dados para a página onde tem o php, tem na pergunta essa parte do código
Answer:  Ajax()
Primeiramente o ajax() precisa enviar uma informação para distinguir no PHP qual ação vc quer tomar:
$(document).ready(function(){
    $(".btn_contact").click(function () {
        var id = $(this).closest("section").attr("id");
        var serialize = $("#"+id+" form").serialize();
        serialize += "&type="+id;
        $.ajax({
            type: "POST",
            url: "./inserir",
            data: serialize,
            dataType: "json",
            success: function (data)
            {
                $(".success_messages").removeClass('hide'); // success message
            },
            error: function(data)
                {
                    $(".error_message").removeClass('hide'); // error message
                },
            complete: function()
                {
                    $("#feedback_form").find('input').val(''); //clear text
                }
        });
    });
});

var id = $(this).closest("section").attr("id"); pega o id da section do formulário que será enviado
var serialize = $("#"+id+" form").serialize(); serializa o formulário
serialize += "&type="+id; aqui ele adiciona um novo campo à var serialize que é o mesmo id da section, ele quem vai te ajudar a separar as ações no PHP

 PHP
Agora o PHP tem um identificador único para você conseguir separar as ações, que é o $_POST['type']:
$_POST['type']=='produto_1':
if($_POST['type']=='produto_1'):
    $name = isset($_POST["DescricaoProd"]) ? $_POST["DescricaoProd"] : '';
    $unid = isset($_POST["DescricaoUnid"]) ? $_POST["DescricaoUnid"] : '';

    if (!empty($name) && !empty($unid)) {
       echo json_encode("true");
    } else {
        echo json_encode("false");
    }

    $sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid)
    VALUES ('$name','$unid')";
    if ($conn->query($sql)) { // check for === TRUE is not necessary
       // either put the second query in here, or just enjoy the success
    } else {
       // get the error, throw a message...
    }

    $sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid)
    VALUES ('$name','$unid')";

    $query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

    if ($conn->query($sql1) === TRUE) {
        //Count total number of rows
        $rowCount = $query->num_rows;
    } else {
        // get the error, throw a message...
    }
    $conn->close();
endif;

$_POST['type']=='produto_2':
if($_POST['type']=='produto_2'):
    $data = isset($_POST["DataEntrada"]) ? $_POST["DataEntrada"] : '';
    $produto = isset($_POST["Produto"]) ? $_POST["Produto"] : '';
    $unidade = isset($_POST["Unid"]) ? $_POST["Unid"] : '';
    $quantidade = isset($_POST["Quantidade"]) ? $_POST["Quantidade"] : '';
    $preco = isset($_POST["Preco"]) ? $_POST["Preco"] : '';

    if (!empty($data) && !empty($produto) && !empty($unidade) && !empty($quantidade) && !empty($preco)) {
       echo json_encode("true");
    } else {
        echo json_encode("false");
    }

    $sql2 = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco)
    VALUES ('$data','$produto','$unidade','$quantidade','$preco')";

    if ($conn->query($sql2)) { // check for === TRUE is not necessary
       // either put the second query in here, or just enjoy the success
    } else {
       // get the error, throw a message...
    }

    $sql3 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;

     $query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

    if ($conn->query($sql3) === TRUE) {
        //Count total number of rows
        $rowCount = $query->num_rows;
    } else {
        // get the error, throw a message...
    }
    $conn->close();
endif;

Não é a pratica mais adequada, pois acredito que possa ser feito de uma maneira com menos cara de gambiarra, mas como seu sistema já funciona, e você quer solucionar o problema, isso resolve.
Answer: Ambos os seus forms tem um mesmo id, e essa é uma péssima prática. Seu form está inserindo dados vazios porque, quando você dá um submit, ele pega os dados do primeiro form, que estão vazios, e insere no banco de dados.
Experimente preencher os dois forms, e veja quais dados serão inseridos na tabela. Certamente serão os do primeiro form, que tem o primeiro id feedback_form. Altere os id's, para que eles sejam diferentes, e altere também a lógica, para que o submit deles seja "independente".
Answer: Pelo que vi você detecta o click no .btn_contact, um botão que está nas duas forms, até aí nada de errado. Mas na hora de puxar os dados da form você só puxa de um ID #feedback_form. Então sempre vai puxar os dados de um formulário só.
Alterando um pouco o seu código eu fiz com que o script buscasse a form por conta própria para sempre pegar aquela em que o .btn_contact está dentro:

Creio que isso deve resolver, testa lá e me diz como foi!
Comment: @Iniciante Lembre-se que a responsabilidade para fazer funcionar é sua, não de quem responde, então comentários como "*não funcionou*" não trazem nenhum benefício para a discussão ou para a comunidade. Ao invés de apenas copiar/colar a resposta e executar, busque entender o que foi descrito na resposta, reconheça qual foi o seu erro e busque corrigi-lo com as dicas dadas.
Comment: Um dúvida @Iniciante, os dois formulários devem enviar para **"./inserir"** mesmo?
Comment: sim, é onde tenho o código php
Comment: Testei o código (tirando a parte do registro PHP) e ele está passando os dados para o AJAX então agora deve ser algo no PHP mesmo, ele chega a dar algum erro ao registrar? Talvez algum erro no SQL?
Comment: @Henrique Pauli, no php não recebo nenhum erro, o problema é que ao inserir com o segundo formulário ele utiliza sempre o código de inserção do primeiro formulário. Ao fazer registo com o segundo formulário, devia ignorar o primeiro código de inserção e inserir com o segundo...eu penso que o problema está no lado do php, porque envia os dados, mas não sei como resolver
Comment: @Iniciante, tente criar um input hidden com o nome **"acao"** (por exemplo) nos dois formulários, no primeiro você define o valor de **"acao"** como "inserir" e no outro como "entrada". No seu código PHP você verifica, se **$_POST['acao']=="inserir"** então use o código do inserir, caso contrário use o outro código PHP.


Perfect pitch inside a scale?

Question: I was reading how a very small amount of people have perfect pitch and how it's very hard for adults to develop it.
So I was wondering if maybe there's a hack where I can only limit the notes to a scale and then instead of having to choose between 12 notes I could just limit the choices to the 7 notes of a scale.
Is it fairly easy to achieve that with enough practice? also, is it still called perfect pitch to do that or is it called relative pitch?
Comment: Perfect pitch isn't "choosing between 12 notes." A person with perfect pitch can hear a single note and say something like "that is about 1/4 of a semitone sharper than a C", or whatever it might be.
Comment: Does this answer your question? [What are some useful and effective exercises for training absolute pitch?](https://music.stackexchange.com/questions/203/what-are-some-useful-and-effective-exercises-for-training-absolute-pitch)
Comment: "So I was wondering if maybe there's a hack" - are you looking for a way to "cheat" and pretend you have perfect pitch when you don't? What's the point of doing that?
Comment: @alephzero hah no. I meant hack as in "can I make it easier on myself by doing this". also I find it more applicable to what I'm doing anyway since most of the music I play is diatonic.
Answer: First, I should pass along that people who have more experience with perfect pitch than I do emphatically state that true perfect pitch (hearing a note and instantly knowing what pitch it is) cannot be learned as an adult.  There may be agreement or disagreement, but that is what I'm told, and being in the field of music for years, I've never met anyone who's learned it as an adult.
Second, perfect pitch is not really necessary, and the only real benefit I can see between having absolute pitch and having 100% relative pitch is that perfect pitch makes a great party trick.  It is just as useful to learn relative pitch (knowing all intervals and knowing all scale degrees by ear), and that can be learned.  It sounds like the 7-note scale "hack" you're recommending is similar to learning scale degrees, which is extremely useful and doable.
Lastly, to qualify my statement, what you could learn is pitch memory. This is best learned by learning an intro/beginning of a song for each key and drilling yourself on it until you can hear it in that key in your head. Then when asked to sing a C, for instance, you play the beginning of your "C" song in your head, and you can hear and reproduce it.  This is not true perfect pitch, and in my experience requires more work than it is useful. Also if you stop drilling the songs, your pitch memory will start to go -- it's not a one-and-done thing.
Bottom line, train yourself on relative pitch. I have completely accurate relative pitch, and I've never run across something that I absolutely needed perfect pitch to do.
Hope this helps!
Answer: Yes, it's conceivable that this could be a good training strategy.  Start by trying to learn a limited range of pitches.  Makes sense.
Of course, once you've got ONE pitch right, you're going to find it hard to seperate Perfect Pitch from Relative Pitch.
I suggest you don't worry too much about developing Perfect Pitch.  Work on your Relative Pitch - recognising intervals from a known starting point rather than plucking notes out of thin air. It's 99% as musically useful.
 A degree of Perfect Pitch will probably emerge.
Comment: I'm guessing that 'known starting point' would be the tonic of the scale.
Comment: Not necessarily. But that would make it easier for a start.   The eventual aim is to, having 'got your bearings' from any reference note, to recognise ANY other one.   The small step to Perfect Pitch simply requires you to work from your own internal reference.

Perfect pitch inside a scale?


Paramterising an SQL SELECT statement

Question: I've been working with paramaterising my SQL statements lately, and have managed to do so for my INSERT, UPDATE and DELETE queries. However, I am struggling to do so with SELECT... Is anybody able to help me? I feel it's because I'm using OleDbDataAdapter, rather than OleDbCommand?
    Public Shared Function getPerson(ByVal personID As Integer, m_cn As OleDbConnection)

    Dim Dt As New DataTable

    Dim Da As New OleDbDataAdapter
    Da = New OleDbDataAdapter("SELECT * FROM tblPerson WHERE personID = " & personID, m_cn)

    Da.Fill(Dt)

    Return Dt

End Function

Answer: The OleDbDataAdapter.SelectCommand has the parameters for the SQL statement (or stored procedure) used to select records:
Using da = New OleDbDataAdapter("SELECT * FROM tblPerson WHERE personID = @PersonID", m_cn)
    da.SelectCommand.Parameters.Add("@PersonID", OleDbType.Integer).Value = personID
    Da.Fill(Dt)
End Using

I suggest to not reuse the connection(or make it even static/shared) since that can cause various  issues. Instead create, open and use it wherever you need it, so in this method, best by using the Using statement to ensure that it gets closed even in case of an error.
Comment: Hi Tim, I put this statement between the lines `Dim Da As New OleDbAdapter` and `Da.Fill(Dt)` (after taking out the original SQL line), and I get an error saying `Variable 'Da' hides a variable in an enclosing block` in `Using Da`... Any ideas?
Comment: @Joe: you don't need to declare the adapter anymore since it's created in the `Using`statement. It is closed and disposed at the the end of it. All you want to do with it belongs into the `Using`. Remember to use the `Using`-statement for anything that implements `IDisposable`(with few exceptions like `DataTable`/`DataSet`) which don't hold unmanaged resources.
Comment: 'Must declare the scalar variable "@PersonID".' is the new error after changing it this way?
Comment: @Joe: have you seen that i've modified your query?
Comment: Yes, the one I copied and pasted directly from your answer (Just done it again now), still returns the same error
Comment: @joe: you have also added this line: `da.SelectCommand.Parameters.Add("@PersonID", SqlDbType.Int).Value = personID`? Maybe you need to use the question mark syntax: http://stackoverflow.com/a/5870248/284240 because named parameters are not supported by your DB
Comment: Hi Tim, yes I had added that line and it was just the question mark syntax that was causing it to fail, so thank you for your help!
Comment: You have `SqlDbType` rather than `OleDbType`
Comment: @Plutonix: fixed, but since he can't use named parameters there's still something to fix above
Comment: Tim - doesn't your example run counter to your recommendation to not reuse a connection? m_cn seems to be a reused connection to me.
Comment: My suggestion is to create the connection here by using the using statement. I have just left out the code

Paramterising an SQL SELECT statement


How would one show that $\textbf{Z}$ is countable?

Question: I am trying to show that the set of all integers $\mathbb{Z}$ is indeed countable which would mean that $|\mathbb{N}|=|\mathbb{Z}|$.
This would further imply that I have to find a bijection between the two sets, but I do not really know how to do that.
I have tried with a function $f:\mathbb{N}\longrightarrow \mathbb{Z}$ such that all the odd numbers are mapped to the positive subset of $\mathbb{Z}$, and all even numbers are mapped to the negative numbers.
I think that this will produce a valid solution but I don't have the details yet, and I also do not really know how to account for zero in all of this.
Any help on the matter would be much appreciated.
Comment: $0, -1, 1, -2,2, -3,3,...$
Answer: To show that a set is countable, you literally count the elements in some order
$$0_1,-1_2,1_3,-2_4,2_5,-3_6,3_7,-4_8,4_9,\cdots$$
without omission.
It is an easy matter to show that for all $m\ge 0$,  $m$ comes $2m+1^{th}$ and $-m$ comes $2m^{th}$.

Technical note:
A counting scheme where the same elements are counted more than once is acceptable, because you can in principle renumber to skip the duplicates and restore a bijection. But all element must be counted at least once.
Answer: Another possible bijection (likely similar to one you were thinking of) would be:
$$f(x)=\begin{cases}
\frac n2 &\text{$n$ is even}\\
-\frac {n+1}{2}\quad &\text{$n$ is odd}
\end{cases}$$


java_home on centos

Question: I am using a centos virtual machine instance.
I have edited the /root/.bash_profile and set the JAVA_HOME path.
the changes are saved but when I type echo $JAVA_HOME, the command executes but show nothing.
typing which java shows some other folder, which doesnt exist.
please help me out
Answer: Command from .bash_profile will be applied where user log on, try to logoff and logon or restart computer.
Do you use SUN JDK or Open JDK ?
Answer: You could also set JAVA_HOME by creating a shell script in /etc/profile.d/ directory, for example:
create file: /etc/profile.d/java.sh
with following contents:
<code>JAVA_HOME=/usr/java/default
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH
</code>
Please note that directory should target place were java was installed. One above should be proper when you install Oracle JDK.
Following variables will be set during system start.

java_home on centos