text:
<file_sep>ruby_benchmarks
===============
Stupid benchmarks
<file_sep>### Method calls

```ruby
module A
  def a; :a end
end

module B
  include A
  def b; :b end
end

module C
  include B
  def c; :c end
end

module D
  include C
  def d; :d end
end

module E
  include D
  def e; :e end
end

class MyClass
  include E
  def f; :f end
end

Benchmark.bm do |b|
  b.report { 1_000_000.times { MyClass.new.a } }
  b.report { 1_000_000.times { MyClass.new.b } }
  b.report { 1_000_000.times { MyClass.new.c } }
  b.report { 1_000_000.times { MyClass.new.d } }
  b.report { 1_000_000.times { MyClass.new.e } }
  b.report { 1_000_000.times { MyClass.new.f } }
end
```

##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
   0.310000   0.000000   0.310000 (  0.312143)
   0.300000   0.000000   0.300000 (  0.302222)
   0.300000   0.000000   0.300000 (  0.304557)
   0.290000   0.000000   0.290000 (  0.304814)
   0.310000   0.000000   0.310000 (  0.306702)
   0.280000   0.000000   0.280000 (  0.301384)

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.250000   0.010000   0.260000 (  0.253295)
   0.230000   0.000000   0.230000 (  0.231801)
   0.240000   0.000000   0.240000 (  0.236016)
   0.240000   0.000000   0.240000 (  0.235877)
   0.240000   0.000000   0.240000 (  0.248153)
   0.250000   0.000000   0.250000 (  0.242689)
```

```ruby
class A
  def a; :a end
end

class B < A
  def b; :b end
end

class C < B
  def c; :c end
end

class D < C
  def d; :d end
end

class E < D
  def e; :e end
end

class MyClass < E
  def f; :f end
end

Benchmark.bm do |b|
  b.report { 1_000_000.times { MyClass.new.a } }
  b.report { 1_000_000.times { MyClass.new.b } }
  b.report { 1_000_000.times { MyClass.new.c } }
  b.report { 1_000_000.times { MyClass.new.d } }
  b.report { 1_000_000.times { MyClass.new.e } }
  b.report { 1_000_000.times { MyClass.new.f } }
end
```

##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
   0.290000   0.000000   0.290000 (  0.296654)
   0.290000   0.000000   0.290000 (  0.289507)
   0.290000   0.000000   0.290000 (  0.290083)
   0.280000   0.000000   0.280000 (  0.292860)
   0.290000   0.000000   0.290000 (  0.293749)
   0.290000   0.000000   0.290000 (  0.288914)

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.240000   0.000000   0.240000 (  0.246034)
   0.230000   0.000000   0.230000 (  0.231503)
   0.240000   0.000000   0.240000 (  0.232060)
   0.220000   0.000000   0.220000 (  0.229448)
   0.230000   0.000000   0.230000 (  0.230160)
   0.240000   0.000000   0.240000 (  0.233843)
```

### send vs explicid method call

```ruby
class B
  def a; end
end

Benchmark.bm do |x|
  x.report { obj = B.new; 1_000_000_000.times {obj.a} }
  x.report { obj = B.new; 1_000_000_000.times {obj.send :a} }
end
```

##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
  95.690000   0.000000  95.690000 ( 95.876045)
 111.440000   0.100000 111.540000 (111.837126)

explicit calls is 14.1% than send

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
  76.520000   0.000000  76.520000 ( 76.650600)
 102.940000   0.000000 102.940000 (103.093323)

explicit calls is 25.6% than send
```

### def vs define_method
```ruby
class A
  def a; end
  define_method(:b) {}
end

# For single method call
Benchmark.bm do |x|
  x.report { 100_000_000.times { A.new.b  } }
  x.report { 100_000_000.times {A.new.a} }
end
```
##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
  39.320000   0.000000  39.320000 ( 39.418881)
  28.160000   0.010000  28.170000 ( 28.230322)

def is 28.4% faster than define_method

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
  31.420000   0.000000  31.420000 ( 32.021655)
  25.480000   0.000000  25.480000 ( 25.547244)

def if 20.4% faster than define_method
```

```ruby
# For multiple method calls
Benchmark.bm do |x|
  x.report { obj = A.new; 100_000_000.times {obj.b} }
  x.report { obj = A.new; 100_000_000.times {obj.a} }
end
```
##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

          user     system      total        real
  17.720000   0.050000  17.770000 ( 17.815660)
   9.280000   0.020000   9.300000 (  9.307244)

def is 47.6% faster than define_method

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
  12.770000   0.000000  12.770000 ( 12.823291)
   7.890000   0.000000   7.890000 (  7.910796)

def is 38.2 % faster than define_method
```

### #send vs Proc#call
```ruby
Benchmark.bm do |x|
  obj = 'string'
  lmbd = ->(obj) { obj.to_s }
  proc = Proc.new { |obj| obj.to_s }

  x.report { 1_000_000.times { obj.send(:to_s) } }
  x.report { 1_000_000.times { lmbd.call(obj) } }
  x.report { 1_000_000.times { proc.call(obj) } }
end
```
##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
   0.110000   0.000000   0.110000 (  0.108591)
   0.170000   0.000000   0.170000 (  0.171853)
   0.170000   0.000000   0.170000 (  0.177797)

#send is 35.7% faster, lambda and proc are equal

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.110000   0.000000   0.110000 (  0.109724)
   0.170000   0.000000   0.170000 (  0.169154)
   0.170000   0.000000   0.170000 (  0.173261)

#send is 35.7% faster, proc and lambda are equal
```

### method_missing with and without method definition
```ruby
class A
  def method_missing(method_name, *args, &block)
    if method_name.match /\Amethod_([\d])+\Z/
      $1
    else
      super method_name, *args, &block
    end
  end
end

class B
  def method_missing(method_name, *args, &block)
    if method_name.match /\Amethod_([\d])+\Z/
      B.class_eval <<-METHOD
        def #{method_name}
          $1
        end
      METHOD
    else
      super method_name, *args, &block
    end
  end
end

Benchmark.bm do |x|
  x.report {1_000_000.times { A.new.method_100500 }}
  x.report {1_000_000.times { B.new.method_100500 }}
end
```
##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
   1.930000   0.010000   1.940000 (  1.941696)
   0.360000   0.000000   0.360000 (  0.364693)

#method_missing with method definition is 81.2% faster.

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   2.090000   0.000000   2.090000 (  2.104916)
   0.330000   0.000000   0.330000 (  0.331562)

#method_missing with method definition is 84.3% faster.
It's faster because #method_missing have been called only once.
```

<file_sep># classic syntax vs %w vs %i
```ruby
Benchmark.bm do |b|
  b.report { 1_000_000.times { ['a', 'b', 'c', 'd', 'e'] } }
  b.report { 1_000_000.times { [:a, :b, :c, :d, :e] } }
  b.report { 1_000_000.times { %w{a b c d e} } }
  b.report { 1_000_000.times { %i{a b c d e} } }
end
```

##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.840000   0.000000   0.840000 (  0.850846)
   0.240000   0.000000   0.240000 (  0.234213)

   0.870000   0.000000   0.870000 (  0.870216)
   0.230000   0.000000   0.230000 (  0.233701)
```

### '#concat' VS '+='
```ruby
Benchmark.bm do |b|
  # #concat
  b.report { array = [1, 2, 3]; 10_000.times { array.concat [4] } }
  b.report { array = [1, 2, 3]; 100_000.times { array.concat [4] } }
  b.report { 10_000.times { array = [1, 2, 3]; array.concat [4] } }
  b.report { 100_000.times { array = [1, 2, 3]; array.concat [4] } }

  # +=
  b.report { array = [1, 2, 3]; 10_000.times { array += [4] } }
  b.report { array = [1, 2, 3]; 100_000.times { array += [4] } }
  b.report { 10_000.times { array = [1, 2, 3]; array += [4] } }
  b.report { 100_000.times { array = [1, 2, 3]; array += [4] } }
end
```

##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.000000   0.000000   0.000000 (  0.001897)
   0.030000   0.000000   0.030000 (  0.027551)
   0.000000   0.000000   0.000000 (  0.005046)
   0.060000   0.010000   0.070000 (  0.054393)

   0.170000   0.000000   0.170000 (  0.177127)
  20.060000   0.380000  20.440000 ( 20.495631)
   0.000000   0.000000   0.000000 (  0.002617)
   0.050000   0.000000   0.050000 (  0.051487)
```

<file_sep># #to_s VS #to_sym

```ruby
Benchmark.bm do |b|
# #to_s
b.report { s = :symbol;  100_000_000.times { s.to_s } }
b.report { s = 'string'; 100_000_000.times { s.to_s } }
# #to_sym
b.report { s = :symbol;  100_000_000.times { s.to_sym } }
b.report { s = 'string'; 100_000_000.times { s.to_sym } }
end
```

##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
  18.970000   0.000000  18.970000 ( 19.010987)
   7.190000   0.000000   7.190000 (  7.201850)

   6.620000   0.000000   6.620000 (  6.633185)
  15.330000   0.000000  15.330000 ( 15.353015)
```

### '<<' VS '#concat' VS '+='

"#<<" и "#concat" - один и тот же метод

```c
    /* string.c */
    rb_define_method(rb_cString, "concat", rb_str_concat, 1);
    rb_define_method(rb_cString, "<<", rb_str_concat, 1);
```

```ruby
Benchmark.bm do |b|
  # <<
  b.report { string = "string"; 100_000.times { string << "e" } }
  b.report { string = "string"; 1_000_000.times { string << "e" } }
  b.report { 100_000.times { string = "s";  string << "e" } }
  b.report { 1_000_000.times { string = "s"; string << "e" } }
  # #concat
  b.report { string = "string"; 100_000.times { string.concat "e" } }
  b.report { string = "string"; 1_000_000.times { string.concat "e" } }
  b.report { 100_000.times { string = "s";  string.concat "e" } }
  b.report { 1_000_000.times { string = "s"; string.concat "e" } }
  # +=
  b.report { string = "string"; 100_000.times { string += "e" } }
  b.report { string = "string"; 1_000_000.times { string += "e" } }
  b.report { 100_000.times { string = "s"; string += "e" } }
  b.report { 1_000_000.times { string = "s"; string += "e" } }
end
```

##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.030000   0.000000   0.030000 (  0.034561)
   0.240000   0.000000   0.240000 (  0.235563)
   0.030000   0.000000   0.030000 (  0.038720)
   0.370000   0.000000   0.370000 (  0.367721)

   0.030000   0.000000   0.030000 (  0.025119)
   0.240000   0.000000   0.240000 (  0.248420)
   0.040000   0.000000   0.040000 (  0.038987)
   0.380000   0.000000   0.380000 (  0.374734)

   1.880000   0.000000   1.880000 (  1.884921)
 194.760000   3.720000 198.480000 (198.951135)
   0.050000   0.000000   0.050000 (  0.047692)
   0.440000   0.000000   0.440000 (  0.442454)
```

### '<<' VS interpolation
```ruby
Benchmark.bm do |b|
  # <<
  b.report { 100_000.times { "string" << "string" } }
  b.report { 1_000_000.times { "string" << "string" } }

  # interpolation
  b.report { 100_000.times { "string #{"string"}" } }
  b.report { 1_000_000.times { "string #{"string"}" } }
end
```

##### Results

```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.050000   0.000000   0.050000 (  0.046931)
   0.360000   0.000000   0.360000 (  0.365020)

   0.010000   0.000000   0.010000 (  0.017804)
   0.170000   0.000000   0.170000 (  0.165179)
```

### '+' VS '+=' VS interpolation
```ruby
Benchmark.bm do |b|
  # +
  b.report { 100_000.times { s = "string"; s = s + "string" } }
  b.report { 1_000_000.times { s = "string"; s = s + "string" } }
  b.report { 10_000_000.times { s = "string"; s = s + "string" } }

  # +=
  b.report { 100_000.times { s = "string"; s += "string" } }
  b.report { 1_000_000.times { s = "string"; s += "string" } }
  b.report { 10_000_000.times { s = "string"; s += "string" } }

  # interpolation
  b.report { 100_000.times { s = "string"; s = "#{s} string" } }
  b.report { 1_000_000.times { s = "string"; s = "#{s} string" } }
  b.report { 10_000_000.times { s = "string"; s = "#{s} string" } }
end
```

##### Results

```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   0.050000   0.000000   0.050000 (  0.050247)
   0.440000   0.000000   0.440000 (  0.447004)
   4.520000   0.000000   4.520000 (  4.529093)

   0.040000   0.000000   0.040000 (  0.047300)
   0.450000   0.000000   0.450000 (  0.445441)
   4.430000   0.000000   4.430000 (  4.448898)

   0.040000   0.000000   0.040000 (  0.037083)
   0.350000   0.000000   0.350000 (  0.348501)
   3.440000   0.000000   3.440000 (  3.449518)
```

<file_sep>### Precompiled regexp vs non-precompiled
```ruby
Benchmark.bm do |x|
  x.report { regexp = /my_string[0-9]+/; 10_000_000.times { |t| "my_string_#{t}" =~ regexp } }
  x.report { 10_000_000.times { |t| "my_string_#{t}" =~ /my_string[0-9]+/ } }
end
```
##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448
       user     system      total        real
   7.990000   0.000000   7.990000 (  8.011321)
   7.640000   0.010000   7.650000 (  7.673300)

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   7.850000   0.000000   7.850000 (  7.872886)
   7.400000   0.000000   7.400000 (  7.423450)

So Ruby does not precompile regexp like JS does.
```

### =~ vs #match
```ruby
Benchmark.bm do |x|
  x.report { 10_000_000.times { |t| "my_string_#{t}" =~ /my_string[0-9]+/ } }
  x.report { 10_000_000.times { |t| "my_string_#{t}".match /my_string[0-9]+/ } }
end
```
##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
   7.680000   0.000000   7.680000 (  7.710648)
   9.120000   0.000000   9.120000 (  9.146549)

=~ is 15.8% faster than #match

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   7.390000   0.000000   7.390000 (  7.416702)
   9.520000   0.000000   9.520000 (  9.554610)

=~ 22.4% faster than #match
```

### \A and \Z vs ^ and $
```ruby
Benchmark.bm do |x|
  x.report { 10_000_000.times { |t| "my_string_#{t}" =~ /my_string[\d]+/ } }
  x.report { 10_000_000.times { |t| "my_string_#{t}" =~ /\Amy_string[\d]+\Z/ } }
  x.report { 10_000_000.times { |t| "my_string_#{t}" =~ /^my_string[\d]+$/ } }
end
```
##### Results
```
# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 1.9.3-p448

       user     system      total        real
   7.430000   0.000000   7.430000 (  7.445127)
   7.410000   0.000000   7.410000 (  7.438655)
   7.460000   0.000000   7.460000 (  7.481719)

# Ubuntu 13.04 64-bit
# Intel® Core™ i5-2450M CPU @ 2.50GHz × 4
# RAM 7,7 GiB
# Ruby 2.0.0-p247

       user     system      total        real
   7.560000   0.000000   7.560000 (  7.593032)
   7.650000   0.000000   7.650000 (  7.675099)
   7.530000   0.040000   7.570000 (  7.575124)
```


text:
<repo_name>nenik234/test<file_sep>/README.txt
task0
Ничего необычного, простой Hello world

branch_name: refs/heads/master

repo_language: Text


text:
<repo_name>beerbank3/rhythmgame<file_sep>/src/rhythm_game_1/Login.java
package rhythm_game_1;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Login extends JFrame{
	private Image screenImage;
	private Graphics screenGraphic;

	public Image background = new ImageIcon(Main.class.getResource("../images/Login.gif")).getImage();
	public Image loginBase = new ImageIcon(Main.class.getResource("../images/loginbasic.png")).getImage();

	private ImageIcon exitButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/Button.png"));
	private ImageIcon exitButtonBasicImage = new ImageIcon(Main.class.getResource("../images/Button2.png"));

	private JButton exitButton = new JButton(exitButtonBasicImage);
	private JButton loginButton=new JButton("LOGIN");
	private JButton signupButton=new JButton("SIGNUP");
	private JLabel user=new JLabel("ID"), Password =new JLabel("<PASSWORD>");
	private JTextField username = new JTextField();
	private JPasswordField password = new JPasswordField();
	private Socket socket;

	public Login(Socket socket) {
		this.socket=socket;
		setUndecorated(true);
		setTitle("Rhythm Game-Login");
		setSize(400, 600);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		setBackground(new Color(0, 0, 0, 0));
		setLayout(null);
		user.setFont(new Font("함초롱돋음",Font.BOLD,40));
		Password.setFont(new Font("함초롱돋음",Font.BOLD,25));
		user.setBounds(80, 170, 150, 40);
		Password.setBounds(80, 240, 150, 40);
		username.setBounds(230, 175, 100, 25);
		password.setBounds(230, 245, 100, 25);
		username.setOpaque(false);
		password.setOpaque(false);
		add(user);
		add(Password);
		add(username);
		add(password);

		exitButton.setBounds(365, 0, 30, 30);
		exitButton.setBorderPainted(false);
		exitButton.setContentAreaFilled(false);
		exitButton.setFocusPainted(false);

		exitButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				exitButton.setIcon(exitButtonEnteredImage);
				exitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				exitButton.setIcon(exitButtonBasicImage);
				exitButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Boom.mp3", false);
				buttonEnteredMusic.start();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
				System.exit(0);
			}
		});
		add(exitButton);

		loginButton.setFont(new Font("함초롱돋음",Font.BOLD,70));
		loginButton.setBounds(77, 350, 255, 70);
	    loginButton.setBorderPainted(false);
	    loginButton.setContentAreaFilled(false);
	    loginButton.setFocusPainted(false);
	    loginButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				//loginButton.setIcon(hardEnteredButton);
				loginButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				//loginButton.setIcon(hardbasicButton);
				loginButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				String ID=username.getText();
				String PW=String.valueOf(password.getPassword());
				dispose();
				new RhythmGame(ID,socket);
				/*if(ID.equals("root")&&PW.equals("root")) {
				dispose();
				new RhythmGame(ID,socket);
				}*/
			}
		});
	    add(loginButton);

	    signupButton.setFont(new Font("함초롱돋음",Font.BOLD,20));
	    signupButton.setBounds(240, 470, 120, 20);
	    signupButton.setBorderPainted(false);
	    signupButton.setContentAreaFilled(false);
	    signupButton.setFocusPainted(false);
	    signupButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				//loginButton.setIcon(hardEnteredButton);
				signupButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				//loginButton.setIcon(hardbasicButton);
				signupButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				dispose();
				new Signup(socket);
				database.xox = 0;
			}
		});
	    add(signupButton);
	}

    public void paint(Graphics g) {
		screenImage = createImage(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
		screenGraphic = screenImage.getGraphics();
		screenDraw((Graphics2D) screenGraphic);
		g.drawImage(screenImage, 0, 0, null);
	}
    public void screenDraw(Graphics2D g) {
		g.drawImage(background, 0, 0, null);
		g.drawImage(loginBase, 50, 100, null);
		paintComponents(g);
		this.repaint();
    }
}
<file_sep>/src/rhythm_game_1/KeyListener2.java
package rhythm_game_1;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

public class KeyListener2 extends KeyAdapter {
	Socket socket;
	String ID;
	BufferedReader in;
	BufferedWriter out;
	Game2 game;
	int i=0;
	public KeyListener2(Socket socket,String ID) {
		this.socket=socket;
		this.ID = ID;
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
			// in: 서버메시지 읽기객체 서버-----msg------>클라이언트
			out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void sendMsg(String msg) {// 서버에게 메시지 보내기
		try {
			out.write((msg + "\n"));
			out.newLine();
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}// sendMsg
	public void comboevent() {
		sendMsg("903|"+ID);
	}
	@Override
	public void keyPressed(KeyEvent e) {
		if (ChatClient.game == null) {
			return;
		}
		if (e.getKeyCode() == KeyEvent.VK_S) {
			ChatClient.game.PressS();
			sendMsg("801|"+ID);
			sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
		} else if (e.getKeyCode() == KeyEvent.VK_D) {
			ChatClient.game.PressD();
			sendMsg("802|"+ID);
			sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
		} else if (e.getKeyCode() == KeyEvent.VK_F) {
			ChatClient.game.PressF();
			sendMsg("803|"+ID);
			sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
		} else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
			ChatClient.game.PressSpace();
			sendMsg("804|"+ID);
			sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
		} else if (e.getKeyCode() == KeyEvent.VK_J) {
			ChatClient.game.PressJ();
			sendMsg("805|"+ID);
			sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
		} else if (e.getKeyCode() == KeyEvent.VK_K) {
			ChatClient.game.PressK();
			sendMsg("806|"+ID);
			sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
		} else if (e.getKeyCode() == KeyEvent.VK_L) {
			ChatClient.game.PressL();
			sendMsg("807|"+ID);
			sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
		}else if(e.getKeyCode() == KeyEvent.VK_U && game.comboevent>0) {
			sendMsg("900|"+ID);
		}else if(e.getKeyCode() == KeyEvent.VK_I && game.imageevent>0) {
			sendMsg("901|"+ID);
		}else if(e.getKeyCode() == KeyEvent.VK_O && game.scoreevent>0) {
			sendMsg("902|"+ID);
		}
		if(i==0) {
			i++;
		Timer Timer = new Timer();
		TimerTask Task = new TimerTask(){
			@Override
			public void run() {
				sendMsg("888|"+ID+"#"+game.score+"#"+game.Combo);
			}
		};
		Timer.schedule(Task, 3000,2000);
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		if (ChatClient.game == null) {
			return;
		}
		if (e.getKeyCode() == KeyEvent.VK_S) {
			ChatClient.game.releaseS();
			sendMsg("811|"+ID);
		} else if (e.getKeyCode() == KeyEvent.VK_D) {
			ChatClient.game.releaseD();
			sendMsg("812|"+ID);
		} else if (e.getKeyCode() == KeyEvent.VK_F) {
			ChatClient.game.releaseF();
			sendMsg("813|"+ID);
		} else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
			ChatClient.game.releaseSpace();
			sendMsg("814|"+ID);
		} else if (e.getKeyCode() == KeyEvent.VK_J) {
			ChatClient.game.releaseJ();
			sendMsg("815|"+ID);
		} else if (e.getKeyCode() == KeyEvent.VK_K) {
			ChatClient.game.releaseK();
			sendMsg("816|"+ID);
		} else if (e.getKeyCode() == KeyEvent.VK_L) {
			ChatClient.game.releaseL();
			sendMsg("817|"+ID);
		}
	}

}
<file_sep>/src/rhythm_game_1/StartServer.java
package rhythm_game_1;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class StartServer implements Runnable {
	public static final int PORT = 8080;
	Vector<ChatProcess> allV;//모든 사용자(대기실사용자 + 대화방사용자)
	Vector<ChatProcess> waitV;//대기실 사용자
	Vector<Room> roomV;//개설된 대화방 Room-vs(Vector) : 대화방사용자
	Vector<ChatProcess> waituser;
	Vector<Room> Roomuser;
	public StartServer() {
		allV = new Vector<>();
		waitV = new Vector<>();
		roomV = new Vector<>();
		new Thread(this).start();
	}
	@Override
	public void run() {
		try {
			// 1. 서버 소켓 생성
			ServerSocket serverSocket = new ServerSocket();
			// 2. 바인딩
			String hostAddress = InetAddress.getLocalHost().getHostAddress();
			serverSocket.bind(new InetSocketAddress(hostAddress, PORT));
			consoleLog("연결 기다림 - " + hostAddress + ":" + PORT);

			// 3. 요청 대기
			while (true) {
				Socket socket = serverSocket.accept();
				ChatProcess ser = new ChatProcess(socket,this);
				//new ChatServerProcessThread(socket, this).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		new StartServer();
	}
	private static void consoleLog(String log) {
		System.out.println("[server " + Thread.currentThread().getId() + "] " + log);
	}
}<file_sep>/src/rhythm_game_1/RhythmGame.java
package rhythm_game_1;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class RhythmGame extends JFrame {
	private Image screenImage;
	private Graphics screenGraphic;

	public Image background = new ImageIcon(Main.class.getResource("../images/Rhythm.png")).getImage();
	private JLabel menuBar = new JLabel(new ImageIcon(Main.class.getResource("../images/menuBar.png")));

	private ImageIcon exitButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/Button.png"));
	private ImageIcon exitButtonBasicImage = new ImageIcon(Main.class.getResource("../images/Button2.png"));
	private ImageIcon startbasicButton = new ImageIcon(Main.class.getResource("../images/startbutton2.png"));
	private ImageIcon startEnteredButton = new ImageIcon(Main.class.getResource("../images/startbutton.png"));
	private ImageIcon exitbasicButton = new ImageIcon(Main.class.getResource("../images/exitbutton2.png"));
	private ImageIcon exitEnteredButton = new ImageIcon(Main.class.getResource("../images/exitbutton.png"));

	private ImageIcon easybasicButton = new ImageIcon(Main.class.getResource("../images/Easy.png"));
	private ImageIcon normalbasicButton = new ImageIcon(Main.class.getResource("../images/Normal.png"));
	private ImageIcon hardbasicButton = new ImageIcon(Main.class.getResource("../images/Hard.png"));
	private ImageIcon easyEnteredButton = new ImageIcon(Main.class.getResource("../images/Easy2.png"));
	private ImageIcon normalEnteredButton = new ImageIcon(Main.class.getResource("../images/Normal2.png"));
	private ImageIcon hardEnteredButton = new ImageIcon(Main.class.getResource("../images/Hard2.png"));

	private ImageIcon LeftbasicButton = new ImageIcon(Main.class.getResource("../images/left.png"));
	private ImageIcon LeftEnteredButton = new ImageIcon(Main.class.getResource("../images/left2.png"));
	private ImageIcon RightbasicButton = new ImageIcon(Main.class.getResource("../images/right.png"));
	private ImageIcon RightEnteredButton = new ImageIcon(Main.class.getResource("../images/right2.png"));

	private static ImageIcon backbasicButton = new ImageIcon(Main.class.getResource("../images/Back.png"));
	private static ImageIcon backEnteredButton = new ImageIcon(Main.class.getResource("../images/Back2.png"));

	private ImageIcon StopButton = new ImageIcon(Main.class.getResource("../images/stop.png"));
	private ImageIcon reStartButton = new ImageIcon(Main.class.getResource("../images/restart.png"));
	private static ImageIcon EndButton = new ImageIcon(Main.class.getResource("../images/gameend.png"));

	public static Image gameendInfo = new ImageIcon(Main.class.getResource("../images/gameendInfo.png")).getImage();
	public static Image scoreBase = new ImageIcon(Main.class.getResource("../images/scoreBase.png")).getImage();
	public static ImageIcon main = new ImageIcon(Main.class.getResource("../images/main.png"));
	public static ImageIcon main2 = new ImageIcon(Main.class.getResource("../images/Main2.png"));

	private Image GreatImage = new ImageIcon(Main.class.getResource("../images/Great.png")).getImage();
	private Image MissImage = new ImageIcon(Main.class.getResource("../images/Miss.png")).getImage();
	private Image LateImage = new ImageIcon(Main.class.getResource("../images/Late.png")).getImage();
	private Image GoodImage = new ImageIcon(Main.class.getResource("../images/Good.png")).getImage();
	private Image PerfectImage = new ImageIcon(Main.class.getResource("../images/Perfect.png")).getImage();
	private Image EarlyImage = new ImageIcon(Main.class.getResource("../images/Early.png")).getImage();
	private Image SCOREImage = new ImageIcon(Main.class.getResource("../images/SCORE.png")).getImage();
	private Image COMBOImage = new ImageIcon(Main.class.getResource("../images/COMBO.png")).getImage();
	private Image scoreBaseLineImage = new ImageIcon(Main.class.getResource("../images/scoreBaseLine.png")).getImage();

	private ImageIcon multiplayEnteredButton = new ImageIcon(Main.class.getResource("../images/multiplay1.png"));
	private ImageIcon multiplaybasicButton = new ImageIcon(Main.class.getResource("../images/multiplay2.png"));
	private JButton multiplayButton = new JButton(multiplaybasicButton);

	private JButton exitButton = new JButton(exitButtonBasicImage);
	private JButton startButton = new JButton(startbasicButton);
	private JButton quitButton = new JButton(exitbasicButton);
	private JButton rightButton = new JButton(RightbasicButton);
	private JButton leftButton = new JButton(LeftbasicButton);

	private JButton easyButton = new JButton(easybasicButton);
	private JButton normalButton = new JButton(normalbasicButton);
	private JButton hardButton = new JButton(hardbasicButton);

	private JButton stopButton = new JButton(StopButton);
	private JButton restartButton = new JButton(reStartButton);
	private static JButton endButton = new JButton(EndButton);
	private static JButton backButton = new JButton(backbasicButton);
	private static JButton Homemain = new JButton(main);
	private int mouseX, mouseY;
	private Music introMusic = new Music("intromusic.mp3", true);

	private boolean isMainScreen = false;
	static boolean isGameScreen = false; // private
	static boolean isEndScreen = false;
	static boolean isMultiScreen = false;

	private JButton up = new JButton("UP");
	private JButton down = new JButton("DOWN");

	ArrayList<Track> trackList = new ArrayList<Track>();

	private Image titleImage;
	private Image selectedImage;
	private Music selectedMusic;
	private int nowSelected = 0;

	private JPanel panelMain;
	private String name;
	private Socket socket;
	public static Game game;
	public static Multigame multi;

	public RhythmGame(String ID, Socket socket) {
		trackList.add(new Track("We Are name.png", "We are(intro).png", "We are main.png", "We Are Cut.mp3",
				"We Are.mp3", "We Are - <NAME> & S<NAME>"));
		trackList.add(new Track("Cradles.png", "Cradles (intro).png", "Cradles main.png", "Cradles Cut.mp3",
				"Cradles.mp3", "Cradles - Sub Urban"));
		trackList.add(new Track("Light It Up.png", "Light It Up(intro).png", "Light It Up main.png",
				"Light It Up Cut.mp3", "Light It Up.mp3", "Light It Up - <NAME>ustin x TobiMorrow"));
		trackList.add(new Track("FlashLight name.png", "FlashLight(intro).jpg", "FlashLight main.png",
				"FlashLight Cut.mp3", "FlashLight.mp3", "FlashLight - DJ Fresh (feat. <NAME>)"));

		this.socket = socket;
		this.name = ID;
		setUndecorated(true);
		setTitle("Rhythm Game");
		setSize(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		setBackground(new Color(0, 0, 0, 0));
		setLayout(null);

		addKeyListener(new KeyListener());
		introMusic.start();

		exitButton.setBounds(1245, 0, 30, 30);
		exitButton.setBorderPainted(false);
		exitButton.setContentAreaFilled(false);
		exitButton.setFocusPainted(false);

		exitButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				exitButton.setIcon(exitButtonEnteredImage);
				exitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				exitButton.setIcon(exitButtonBasicImage);
				exitButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Boom.mp3", false);
				buttonEnteredMusic.start();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
				System.exit(0);
			}
		});
		add(exitButton);

		startButton.setBounds(30, 520, 250, 70);
		startButton.setBorderPainted(false);
		startButton.setContentAreaFilled(false);
		startButton.setFocusPainted(false);

		startButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				startButton.setIcon(startEnteredButton);
				startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				startButton.setIcon(startbasicButton);
				startButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				enterMain();
				// ���ӽ����̺�Ʈ
			}
		});
		add(startButton);

		quitButton.setBounds(30, 600, 250, 70);
		quitButton.setBorderPainted(false);
		quitButton.setContentAreaFilled(false);
		quitButton.setFocusPainted(false);

		quitButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				quitButton.setIcon(exitEnteredButton);
				quitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				quitButton.setIcon(exitbasicButton);
				quitButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("No.mp3", false);
				buttonEnteredMusic.start();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
				System.exit(0);
			}
		});
		add(quitButton);

		leftButton.setVisible(false);
		leftButton.setBounds(140, 310, 60, 60);
		leftButton.setBorderPainted(false);
		leftButton.setContentAreaFilled(false);
		leftButton.setFocusPainted(false);

		leftButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				leftButton.setIcon(LeftEnteredButton);
				leftButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				leftButton.setIcon(LeftbasicButton);
				leftButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				selectLeft();//
			}
		});
		add(leftButton);

		rightButton.setVisible(false);
		rightButton.setBounds(1080, 310, 60, 60);
		rightButton.setBorderPainted(false);
		rightButton.setContentAreaFilled(false);
		rightButton.setFocusPainted(false);

		rightButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				rightButton.setIcon(RightEnteredButton);
				rightButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				rightButton.setIcon(RightbasicButton);
				rightButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				selectRight();//
			}
		});
		add(rightButton);

		easyButton.setVisible(false);
		easyButton.setBounds(600, 580, 250, 50);
		easyButton.setBorderPainted(false);
		easyButton.setContentAreaFilled(false);
		easyButton.setFocusPainted(false);

		easyButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				easyButton.setIcon(easyEnteredButton);
				easyButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				easyButton.setIcon(easybasicButton);
				easyButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				gameStart(nowSelected, "Easy");
			}
		});
		add(easyButton);

		normalButton.setVisible(false);
		normalButton.setBounds(750, 580, 250, 50);
		normalButton.setBorderPainted(false);
		normalButton.setContentAreaFilled(false);
		normalButton.setFocusPainted(false);

		normalButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				normalButton.setIcon(normalEnteredButton);
				normalButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				normalButton.setIcon(normalbasicButton);
				normalButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				gameStart(nowSelected, "Normal");
			}
		});
		add(normalButton);

		hardButton.setVisible(false);
		hardButton.setBounds(925, 580, 250, 50);
		hardButton.setBorderPainted(false);
		hardButton.setContentAreaFilled(false);
		hardButton.setFocusPainted(false);

		hardButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				hardButton.setIcon(hardEnteredButton);
				hardButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				hardButton.setIcon(hardbasicButton);
				hardButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				gameStart(nowSelected, "Hard");
			}
		});
		add(hardButton);

		backButton.setVisible(false);
		backButton.setBounds(20, 50, 60, 30);
		backButton.setBorderPainted(false);
		backButton.setContentAreaFilled(false);
		backButton.setFocusPainted(false);

		backButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				backButton.setIcon(backEnteredButton);
				backButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				backButton.setIcon(backbasicButton);
				backButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				BackMain();
			}
		});
		add(backButton);

		Homemain.setVisible(false);
		Homemain.setBounds(20, 640, 100, 60);
		Homemain.setBorderPainted(false);
		Homemain.setContentAreaFilled(false);
		Homemain.setFocusPainted(false);

		Homemain.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				Homemain.setIcon(main2);
				Homemain.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				Homemain.setIcon(main);
				Homemain.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				HomeMain();
			}
		});
		add(Homemain);

		endButton.setVisible(false);
		endButton.setBounds(20, 100, 60, 30);
		endButton.setBorderPainted(false);
		endButton.setContentAreaFilled(false);
		endButton.setFocusPainted(false);

		endButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				endButton.setIcon(EndButton);
				endButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				endButton.setIcon(EndButton);
				endButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				gameEnd();
			}
		});
		add(endButton);

		menuBar.setBounds(0, 0, 1280, 30);
		menuBar.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				mouseX = e.getX();
				mouseY = e.getY();
			}
		});
		menuBar.addMouseMotionListener(new MouseMotionAdapter() {
			public void mouseDragged(MouseEvent e) {
				int x = e.getXOnScreen();
				int y = e.getYOnScreen();
				setLocation(x - mouseX, y - mouseY);
			}
		});
		add(menuBar);

		multiplayButton.setBounds(900, 520, 300, 100);
		multiplayButton.setBorderPainted(false);
		multiplayButton.setContentAreaFilled(false);
		multiplayButton.setFocusPainted(false);
		multiplayButton.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseEntered(MouseEvent e) {
				multiplayButton.setIcon(multiplayEnteredButton);
				multiplayButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				multiplayButton.setIcon(multiplaybasicButton);
				multiplayButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				gameMulti();
			}

		});
		add(multiplayButton);
		up.setFont(new Font("함초롱돋음", Font.BOLD, 10));
		up.setForeground(Color.WHITE);
		up.setBounds(0, 130, 100, 30);
		up.setBorderPainted(false);
		up.setContentAreaFilled(false);
		up.setFocusPainted(false);
		up.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				up.setForeground(Color.LIGHT_GRAY);
			}
			public void mouseExited(MouseEvent e) {
				up.setForeground(Color.WHITE);
			}
			public void mousePressed(MouseEvent e) {
				setvolume.volume += 0.01;
				try {
					setvolume.setvolume(setvolume.volume);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				System.out.println("볼륨 업");
			}
		});
		add(up);
		down.setFont(new Font("함초롱돋음", Font.BOLD, 10));
		down.setForeground(Color.WHITE);
		down.setBounds(0, 160, 100, 30);
		down.setBorderPainted(false);
		down.setContentAreaFilled(false);
		down.setFocusPainted(false);
		down.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				down.setForeground(Color.LIGHT_GRAY);
			}
			public void mouseExited(MouseEvent e) {
				down.setForeground(Color.WHITE);
			}
			public void mousePressed(MouseEvent e) {
				setvolume.volume -= 0.01;
				try {
					setvolume.setvolume(setvolume.volume);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				System.out.println("볼륨 다운");
			}
		});
		add(down);

		up.setVisible(true);
		down.setVisible(true);
	}

	// multiplayButton
	// multiplayEnteredButton
	public void paint(Graphics g) {
		screenImage = createImage(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
		screenGraphic = screenImage.getGraphics();
		screenDraw((Graphics2D) screenGraphic);
		g.drawImage(screenImage, 0, 0, null);
	}

	public void screenDraw(Graphics2D g) {
		g.drawImage(background, 0, 0, null);
		if (isMainScreen) {
			g.drawImage(selectedImage, 320, 150, null);
			g.drawImage(titleImage, 320, 100, null);
		}
		if (isGameScreen) {
			game.screenDraw(g);
		}
		if (isEndScreen) {
			EndGame(g);
		}
		if (isMultiScreen) {
			Multigame.screenDraw(g);
		}
		paintComponents(g);
		try {
			Thread.sleep(5);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.repaint();
	}

	public void selectTrack(int nowSelected) {
		if (selectedMusic != null)
			selectedMusic.close();
		titleImage = new ImageIcon(Main.class.getResource("../images/" + trackList.get(nowSelected).getTitleImage()))
				.getImage();//
		selectedImage = new ImageIcon(Main.class.getResource("../images/" + trackList.get(nowSelected).getStartImage()))
				.getImage();
		selectedMusic = new Music(trackList.get(nowSelected).getStartMusic(), true);
		selectedMusic.start();
	}

	public void selectLeft() {
		if (nowSelected == 0)
			nowSelected = trackList.size() - 1;
		else
			nowSelected--;
		selectTrack(nowSelected);//
	}

	public void selectRight() {
		if (nowSelected == trackList.size() - 1)
			nowSelected = 0;
		else
			nowSelected++;
		selectTrack(nowSelected);//
	}

	public void gameStart(int nowSelected, String difficulty) {
		if (selectedMusic != null)
			selectedMusic.close();
		isMainScreen = false;
		leftButton.setVisible(false);
		rightButton.setVisible(false);
		easyButton.setVisible(false);
		normalButton.setVisible(false);
		hardButton.setVisible(false);
		backButton.setVisible(true);
		endButton.setVisible(true);
		background = new ImageIcon(Main.class.getResource("../images/" + trackList.get(nowSelected).getGameImage()))
				.getImage();
		isGameScreen = true;
		game = new Game(trackList.get(nowSelected).getTitleName(), difficulty,
				trackList.get(nowSelected).getGameMusic());
		game.start();
		setFocusable(true);
		requestFocus();
		game.score = 0;
		game.Combo = 0;
	}

	public void BackMain() {
		isMainScreen = true;
		leftButton.setVisible(true);
		rightButton.setVisible(true);
		easyButton.setVisible(true);
		normalButton.setVisible(true);
		hardButton.setVisible(true);
		backButton.setVisible(false);
		endButton.setVisible(false);
		background = new ImageIcon(Main.class.getResource("../images/background.jpg")).getImage();
		selectTrack(nowSelected);
		isGameScreen = false;

		game.close();
		game.score = 0;
		game.Combo = 0;
		for (int i = 0; i < 6; i++) {
			Note.combo[i] = 0;
		}
	}

	public void HomeMain() {
		isMainScreen = true;
		leftButton.setVisible(true);
		rightButton.setVisible(true);
		easyButton.setVisible(true);
		normalButton.setVisible(true);
		hardButton.setVisible(true);
		backButton.setVisible(false);
		endButton.setVisible(false);
		Homemain.setVisible(false);
		background = new ImageIcon(Main.class.getResource("../images/background.jpg")).getImage();
		selectTrack(nowSelected);
		isEndScreen = false;
		isMultiScreen = false;
		Note.MaxCombo = 0;
		for (int i = 0; i < 6; i++) {
			Note.combo[i] = 0;
		}
		database.xox = 0;
	}

	public void enterMain() {
		startButton.setVisible(false);
		quitButton.setVisible(false);
		background = new ImageIcon(Main.class.getResource("../images/background.jpg")).getImage();
		isMainScreen = true;
		leftButton.setVisible(true);
		rightButton.setVisible(true);
		easyButton.setVisible(true);
		normalButton.setVisible(true);
		hardButton.setVisible(true);
		endButton.setVisible(false);
		multiplayButton.setVisible(false);
		introMusic.close();
		selectTrack(0);
		game.score = 0;
		game.Combo = 0;
	}

	public static void gameEnd() {
		isGameScreen = false;
		backButton.setVisible(false);
		Homemain.setVisible(true);
		game.close();
		endButton.setVisible(false);
		isEndScreen = true;
	}

	public void EndGame(Graphics2D g) {
		background = new ImageIcon(Main.class.getResource("../images/Endbackground.jpg")).getImage();
		g.drawImage(background, 0, 0, null);
		g.drawImage(scoreBase, 100, 150, null);
		g.drawImage(gameendInfo, 0, 0, null);
		g.drawImage(scoreBaseLineImage, 100, 225, null);
		g.drawImage(scoreBaseLineImage, 100, 459, null);

		g.drawImage(SCOREImage, 25, 150, null);
		g.drawImage(COMBOImage, 25, 465, null);

		g.drawImage(PerfectImage, 0, 220, null);
		g.drawImage(GreatImage, 290, 220, null);
		g.drawImage(GoodImage, -20, 300, null);
		g.drawImage(EarlyImage, 290, 300, null);
		g.drawImage(LateImage, -30, 380, null);
		g.drawImage(MissImage, 290, 380, null);

		g.setFont(new Font("Elephant", Font.BOLD, 30));
		g.setColor(Color.LIGHT_GRAY);
		g.drawString("" + Note.combo[0], 280, 278);
		g.drawString("" + Note.combo[1], 550, 278);
		g.drawString("" + Note.combo[2], 280, 358);
		g.drawString("" + Note.combo[3], 550, 358);
		g.drawString("" + Note.combo[4], 280, 438);
		g.drawString("" + Note.combo[5], 550, 438);
		g.drawString("" + Game.score, 450, 200);
		g.drawString("" + Note.MaxCombo, 450, 515);

		g.setColor(Color.LIGHT_GRAY);
		g.setFont(new Font("Arial", Font.BOLD, 50));
		g.drawString(trackList.get(nowSelected).getTitleName(), 20, 90);
		g.drawString(game.difficulty, 1150, 90);

		if (database.xox == 0)
			database.insertScore(trackList.get(nowSelected).getTitleName(), game.difficulty, Game.score, Note.MaxCombo,
					Note.combo[0], Note.combo[1], Note.combo[2], Note.combo[3], Note.combo[4], Note.combo[5],name);

		g.setFont(new Font("궁서체", Font.PLAIN, 80));
		g.setColor(Color.WHITE);
		g.drawString("게임 결과", 900, 200);

		// getTitleName()

		// String name,String difficulty,int score,int combo,int perfect,int great,int
		// good,int early,int late,int miss
	}

	public void gameMulti() {
		introMusic.close();
		background = new ImageIcon(Main.class.getResource("../images/multibasic.jpg")).getImage();
		startButton.setVisible(false);
		quitButton.setVisible(false);
		isMainScreen = false;
		leftButton.setVisible(false);
		rightButton.setVisible(false);
		backButton.setVisible(false);
		Homemain.setVisible(false);
		endButton.setVisible(false);

		isMultiScreen = true;
		multiplayButton.setVisible(false);
		MainChat p = new MainChat(socket, name,this);
		p.setBounds(0, 0, 1280, 720);
		add(p);
		multi = new Multigame(name, socket);
	}
}
<file_sep>/src/rhythm_game_1/Signup.java
package rhythm_game_1;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.Socket;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Signup extends JFrame{

	private Image screenImage;
	private Graphics screenGraphic;

	public Image signupBase = new ImageIcon(Main.class.getResource("../images/signupbase.png")).getImage();
	private Image background = new ImageIcon(Main.class.getResource("../images/signupbasic.jpg")).getImage();
	private ImageIcon exitButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/Button.png"));
	private ImageIcon exitButtonBasicImage = new ImageIcon(Main.class.getResource("../images/Button2.png"));
	private JButton exitButton = new JButton(exitButtonBasicImage);

	private Socket socket;
	private JLabel user=new JLabel("아이디");
	private JLabel Password =new JLabel("<PASSWORD>");
	private JLabel Password2 =new JLabel("비밀번호 확인");
	private JLabel nickname =new JLabel("닉네임");
	private JLabel E_mail =new JLabel("이메일");
	private JTextField username = new JTextField();
	private JTextField password = new JTextField();
	private JPasswordField password1 = new JPasswordField();
	private JTextField nick = new JTextField();
	private JTextField e_mail = new JTextField();
	private JPasswordField password2 = new JPasswordField();

	private JButton mainButton=new JButton("메인화면");
	private JButton signupButton=new JButton("SIGNUP");

	public Signup(Socket socket) {
		this.socket=socket;
		setUndecorated(true);
		setTitle("Rhythm Game-Signup");
		setSize(400, 600);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		setBackground(new Color(0, 0, 0, 0));
		setLayout(null);
		//폰트수정
		user.setFont(new Font("함초롱돋음",Font.BOLD,20));
		Password.setFont(new Font("<PASSWORD>",Font.BOLD,20));
		Password2.setFont(new Font("<PASSWORD>",Font.BOLD,20));
		nickname.setFont(new Font("함초롱돋음",Font.BOLD,20));
		E_mail.setFont(new Font("함초롱돋음",Font.BOLD,20));
		//폰트 색상
		user.setForeground(Color.WHITE);
		Password.setForeground(Color.WHITE);
		Password2.setForeground(Color.WHITE);
		nickname.setForeground(Color.WHITE);
		E_mail.setForeground(Color.WHITE);
		//위치선정
		user.setBounds(60, 120, 150, 40);
		Password.setBounds(60, 190, 150, 40);
		Password2.setBounds(60, 260, 165, 40);
		nickname.setBounds(60, 330, 150, 40);
		E_mail.setBounds(60, 400, 150, 40);
		username.setBounds(200, 120, 150, 30);
		password.setBounds(200, 190, 150, 30);
		password1.setBounds(200, 260, 150, 30);
		nick.setBounds(200, 330, 150, 30);
		e_mail.setBounds(200, 400, 150, 30);
		//텍스트 박스배경색 제거
		username.setOpaque(false);
		password.setOpaque(false);
		password1.setOpaque(false);
		nick.setOpaque(false);
		e_mail.setOpaque(false);
		//추가
		add(user);
		add(Password);
		add(Password2);
		add(nickname);
		add(E_mail);
		add(username);
		add(password);
		add(password1);
		add(nick);
		add(e_mail);

		//종료
		exitButton.setBounds(365, 0, 30, 30);
		exitButton.setBorderPainted(false);
		exitButton.setContentAreaFilled(false);
		exitButton.setFocusPainted(false);

		exitButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				exitButton.setIcon(exitButtonEnteredImage);
				exitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				exitButton.setIcon(exitButtonBasicImage);
				exitButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Boom.mp3", false);
				buttonEnteredMusic.start();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
				System.exit(0);
			}
		});
		add(exitButton);

		mainButton.setFont(new Font("함초롱돋음",Font.BOLD,20));
		mainButton.setBounds(30, 510, 120, 20);
		mainButton.setBorderPainted(false);
		mainButton.setContentAreaFilled(false);
		mainButton.setFocusPainted(false);
		mainButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				//loginButton.setIcon(hardEnteredButton);
				mainButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				//loginButton.setIcon(hardbasicButton);
				mainButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				dispose();
				new Login(socket);
			}
		});
	    add(mainButton);

	    signupButton.setFont(new Font("함초롱돋음",Font.BOLD,30));
	    signupButton.setBounds(230, 500, 150, 30);
	    signupButton.setBorderPainted(false);
	    signupButton.setContentAreaFilled(false);
	    signupButton.setFocusPainted(false);
	    signupButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				//loginButton.setIcon(hardEnteredButton);
				signupButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
			}

			public void mouseExited(MouseEvent e) {
				//loginButton.setIcon(hardbasicButton);
				signupButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			}

			public void mousePressed(MouseEvent e) {
				Music buttonEnteredMusic = new Music("Click.mp3", false);
				buttonEnteredMusic.start();
				String ID=username.getText();
				String PW=password.getText();
				String PW1=String.valueOf(password1.getPassword());
				String Nick=nick.getText();
				String E_mail=e_mail.getText();
				System.out.println("실패");
				if (database.xox == 0) {
				database.insertAccount(ID,PW,Nick,E_mail);
				System.out.println("정상작동");
				dispose();
				new Login(socket);
				}
			}
		});
	    add(signupButton);
	}
    public void paint(Graphics g) {
		screenImage = createImage(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
		screenGraphic = screenImage.getGraphics();
		screenDraw((Graphics2D) screenGraphic);
		g.drawImage(screenImage, 0, 0, null);
	}
    public void screenDraw(Graphics2D g) {
		g.drawImage(background, 0, 0, null);
		g.drawImage(signupBase, 25, 50, null);
		paintComponents(g);
    }
}
<file_sep>/src/rhythm_game_1/Multigame.java
package rhythm_game_1;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.net.Socket;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JList;

public class Multigame {
	private Image screenImage;
	private Graphics screenGraphic;

	private static Image userinfobase = new ImageIcon(Main.class.getResource("../images/userinfo.png")).getImage();
	private static Image userlist = new ImageIcon(Main.class.getResource("../images/userlist.png")).getImage();
	private static Image gamemenu = new ImageIcon(Main.class.getResource("../images/gamemenu.png")).getImage();
	private static Image multiname = new ImageIcon(Main.class.getResource("../images/multiname.png")).getImage();
	private static Image userOn = new ImageIcon(Main.class.getResource("../images/userOn.png")).getImage();
	private static Image roomlistbase = new ImageIcon(Main.class.getResource("../images/roomlistbase.png")).getImage();
	private static Image roombase = new ImageIcon(Main.class.getResource("../images/roombase.png")).getImage();
	private Socket socket;
	static String name;
	JList<String> waituserlist;
	Multigame(String name, Socket socket) {
		this.socket = socket;
		this.name = name;
	}

	public static void screenDraw(Graphics2D g) {
		int usercount =MainChat.usercount;
		int roomcount =MainChat.roomcount;
		g.drawImage(userinfobase, 1030, 0, null);
		g.drawImage(userlist, 1030, 0, null);
		g.drawImage(gamemenu, 0, 0, null);
		g.drawImage(multiname, 20, 35, null);
		g.drawImage(roomlistbase, 100, 150, null);

		for(int i=0;i<usercount;i++)
			g.drawImage(userOn, 1038,110+(i*23), null);

		for(int i=0;i<roomcount;i++)
			g.drawImage(roombase, 100, 150+(i*38), null);

		g.setColor(Color.LIGHT_GRAY);
		g.setFont(new Font("Arial", Font.BOLD, 20));
		g.drawString(name, 1100, 80);

		g.setColor(Color.LIGHT_GRAY);
		g.setFont(new Font("Arial", Font.BOLD, 15));
	}

	public static void setUser(ArrayList<String> user) {
		user = user;
	}
}

branch_name: refs/heads/main

repo_language: Java


text:
<file_sep>#include <cuda.h>
#include <cuda_runtime.h>
#include "common.h"
#include "efficient.h"

# define blockSize 1024

namespace StreamCompaction {
	namespace Efficient {
		using StreamCompaction::Common::PerformanceTimer;
		PerformanceTimer& timer()
		{
			static PerformanceTimer timer;
			return timer;
		}

		int *dev_arr1;
		int *dev_arr2;
		int *dev_bools;
		int *dev_indices;
		int *dev_odata;

		void printArray(int n, int *a, bool abridged = false) {
			printf("    [ ");
			for (int i = 0; i < n; i++) {
				if (abridged && i + 2 == 15 && n > 16) {
					i = n - 2;
					printf("... ");
				}
				printf("%3d ", a[i]);
			}
			printf("]\n");
		}

		__global__ void kernUpSweep(int n, int valPower2D, int *data) {
			int index = threadIdx.x + (blockIdx.x * blockDim.x);
			if (index >= n)
				return;

			if (index % (2 * valPower2D) == 0 && (index + (2 * valPower2D) - 1 < n) && (index + valPower2D - 1 < n)) {
				data[index + (2 * valPower2D) - 1] += data[index + valPower2D - 1];
			}
		}

		__global__ void kernZeroPadding(int n, int N, int *data) {

			int index = threadIdx.x + (blockIdx.x * blockDim.x);
			if (index >= N - n)
				return;
			data[index + n] = 0;

		}
		__global__ void kernLastElement(int n, int *data) {
			int index = threadIdx.x + (blockIdx.x * blockDim.x);
			if (index == n - 1)
				data[index] = 0;
			else
				return;
		}
		__global__ void kernDownSweep(int n, int valPower2D, int *data) {
			int index = threadIdx.x + (blockIdx.x * blockDim.x);
			if (index >= n)
				return;

			if ((index % (2 * valPower2D) == 0) && (index + (2 * valPower2D) - 1 < n) && (index + valPower2D - 1 < n)) {
				int temp = data[index + valPower2D - 1];
				data[index + valPower2D - 1] = data[index + (2 * valPower2D) - 1];
				data[index + (2 * valPower2D) - 1] += temp;
			}
		}

		__global__ void treeScanSharedMem(int n, int *inData, int *outData) {

			int idx = threadIdx.x + (blockIdx.x * blockDim.x);
			int thid = threadIdx.x;
			if (idx >= n/2 )
				return;

			//printf("Index value id: %d\n", idx);

			extern __shared__ int sharedMem[];

			sharedMem[2 * thid] = inData[2 * idx];
			sharedMem[2 * thid + 1] = inData[2 * idx + 1];
			int ia;
			int ib;
			int multiplier;
			int offset = 1;
			//int numBlocks = n / (2 * blockDim.x);

			// Upsweep
			for (int d = 2*blockDim.x >> 1 ; d > 0; d = d >> 1) {
				//printf("For thread id: %d, the value of d is: %d\n", idx, d);
				__syncthreads();
				if (thid < d) {
					ia = offset * (2 * thid + 1) - 1;
					ib = offset * (2 * thid + 2) - 1;
					//printf("Access %d, %d, %d, %d \n", thid, idx, ia, ib);
					sharedMem[ib] += sharedMem[ia];
				}

				offset *= 2;
			}

			// Downsweep
			if (thid == 0)
				sharedMem[2*blockDim.x -1] = 0;

			int temp;
			//int d = n / 2;
			for (int i = 1; i < 2*blockDim.x; i = i << 1) {
				offset >>= 1;
				if (thid < i) {
					ia = offset * (2 * thid + 1) - 1;
					ib = offset * (2 * thid + 2) - 1;
					temp = sharedMem[ia];
					sharedMem[ia] = sharedMem[ib];
					sharedMem[ib] += temp;
				}
				__syncthreads();

			}

			__syncthreads();
			outData[2 * idx] = sharedMem[2 * thid];
			outData[2 * idx + 1] = sharedMem[2 * thid + 1];

		}

		__global__ void kernLastElementBlockSum(int N, int* indata,int* odata,int* buffer) {
			int idx = threadIdx.x + (blockIdx.x * blockDim.x);
			int thid = threadIdx.x;

			if (idx >= N)
				return;

			//printf("The value is: %d\n", idx);

			if (thid == blockDim.x - 1) {
				buffer[blockIdx.x] = odata[idx];
				buffer[blockIdx.x] += indata[idx];
			}

			//printf("The buffer data is %d \n", buffer[thid]);
		}

		__global__ void kernAddEachBlockElement(int N, int* buffer_data, int* odata) {
			int idx = threadIdx.x + (blockIdx.x * blockDim.x);
			if (idx >= N)
				return;

			odata[idx] += buffer_data[blockIdx.x];

		}
		/**
		 * Performs prefix-sum (aka scan) on idata, storing the result into odata.
		 */
		void oldscan(int n, int *dev_arr2, int *dev_arr1) {
			int diff = (1 << ilog2ceil(n)) - n;
			int N = n + diff;

			//int *dev_arr2;
			//int *dev_buffer;
			//int *dev_buffer_2;

			//cudaMalloc((void**)&dev_arr1, N * sizeof(int));
			//checkCUDAErrorFn("Malloc idata into arr1 failed");

			//cudaMalloc((void**)&dev_arr2, N * sizeof(int));
			//checkCUDAErrorFn("Malloc odata into arr2 failed");

			//cudaMemcpy(dev_arr1, idata, sizeof(int) * n, cudaMemcpyHostToDevice);
			//checkCUDAErrorFn("Copying idata to arr1 failed");

			dim3 fullBlocksPerGrid((N + blockSize - 1) / blockSize);

			bool stopTimer = false;
			try {
				timer().startGpuTimer();
			}
			catch (const std::runtime_error& exception) {
				stopTimer = true;
			}

			dim3 fullBlocksPerGrid2((N - n + blockSize - 1) / blockSize);
			if (diff) {
				kernZeroPadding << <fullBlocksPerGrid2, blockSize >> > (n, N, dev_arr1);
			}
			cudaDeviceSynchronize();

			for (int d = 0; d <= ilog2ceil(n) - 1; d++) {
				int valPower2D = 1 << d;
				kernUpSweep << <fullBlocksPerGrid, blockSize >> > (N, valPower2D, dev_arr1);
				checkCUDAErrorFn("Kernel Up Sweep Failed");
			}
			kernLastElement << <fullBlocksPerGrid, blockSize >> > (N, dev_arr1);
			for (int d = ilog2ceil(n) - 1; d >= 0; d--) {
				int valPower2D = 1 << d;
				kernDownSweep << <fullBlocksPerGrid, blockSize >> > (N, valPower2D, dev_arr1);
				checkCUDAErrorFn("Kernel Down Sweep Failed");
			}

			if (!stopTimer)
				timer().endGpuTimer();

			//printf("Hello 2\n");
			cudaMemcpy(dev_arr2, dev_arr1, sizeof(int) * N, cudaMemcpyDeviceToDevice);
			checkCUDAErrorFn("Copying back to Host failed");

			//printf("\n Output is \n");
			//printArray(N, odata, true);

			//cudaFree(dev_arr1);

		}
		void scan(int n, int *odata, const int *idata) {

			int diff = (1 << ilog2ceil(n)) - n;
			int N = n + diff;

			int *dev_arr2;
			int *dev_buffer;
			int *dev_buffer_2;

			cudaMalloc((void**)&dev_arr1, N * sizeof(int));
			checkCUDAErrorFn("Malloc idata into arr1 failed");

			cudaMalloc((void**)&dev_arr2, N * sizeof(int));
			checkCUDAErrorFn("Malloc odata into arr2 failed");

			cudaMemcpy(dev_arr1, idata, sizeof(int) * n, cudaMemcpyHostToDevice);
			checkCUDAErrorFn("Copying idata to arr1 failed");

			dim3 fullBlocksPerGrid((N + blockSize - 1) / blockSize);

			bool stopTimer = false;
			try {
				timer().startGpuTimer();
			}
			catch (const std::runtime_error& exception) {
				stopTimer = true;
			}

			dim3 fullBlocksPerGrid2((N - n + blockSize - 1) / blockSize);
			if (diff) {
				kernZeroPadding << <fullBlocksPerGrid2, blockSize >> > (n, N, dev_arr1);
			}
			cudaDeviceSynchronize();

			/*
			for (int d = 0; d <= ilog2ceil(n) - 1; d++) {
				int valPower2D = 1 << d;
				kernUpSweep << <fullBlocksPerGrid, blockSize >> > (N, valPower2D, dev_arr1);
				checkCUDAErrorFn("Kernel Up Sweep Failed");
			}
			kernLastElement << <fullBlocksPerGrid, blockSize >> > (N, dev_arr1);
			for (int d = ilog2ceil(n) - 1; d >= 0; d--) {
				int valPower2D = 1 << d;
				kernDownSweep << <fullBlocksPerGrid, blockSize >> > (N, valPower2D, dev_arr1);
				checkCUDAErrorFn("Kernel Down Sweep Failed");
			}
			*/

			//printf("Input Array \n");
			//printArray(N, idata, true);
			int blkSize = blockSize;
			int numBlocks = (N + blockSize -1 )/ blockSize;
			//dim3 fullBlocksPerGrid3((N / 2 + blkSize - 1) / blkSize);
			treeScanSharedMem << <numBlocks, blkSize/2, blkSize*sizeof(int) >> > (N, dev_arr1, dev_arr2);
			checkCUDAErrorFn("Tree scan Shared mem ghg");
			cudaDeviceSynchronize();

			/*
			int *temp0 = new int[N];

			cudaMemcpy(temp0, dev_arr2, sizeof(int) * N, cudaMemcpyDeviceToHost);
			checkCUDAErrorFn("Copying back to Host failed jfkgf");

			printf("\n Each block scan output is \n");
			printArray(N, temp0, true);
			*/

			cudaMalloc((void**)&dev_buffer, numBlocks * sizeof(int));
			checkCUDAErrorFn("Malloc odata into arr2 failed");

			kernLastElementBlockSum << <numBlocks, blkSize >> > (N, dev_arr1, dev_arr2, dev_buffer);
			checkCUDAErrorFn("Kernel last element failed");

			/*
			int *temp = new int[numBlocks];

			cudaMemcpy(temp, dev_buffer, sizeof(int) * numBlocks, cudaMemcpyDeviceToHost);
			checkCUDAErrorFn("Copying back to Host failed jfkgf");

			printf("\n Buffer output is \n");
			printArray(numBlocks, temp, true);

	        */
			cudaMalloc((void**)&dev_buffer_2, numBlocks * sizeof(int));
			checkCUDAErrorFn("Malloc odata into arr2 failed");

			oldscan(numBlocks,dev_buffer_2,dev_buffer);

			/*
			int *temp2 = new int[numBlocks];

			cudaMemcpy(temp2, dev_buffer_2, sizeof(int) * numBlocks, cudaMemcpyDeviceToHost);
			checkCUDAErrorFn("Copying back to Host failed jfkgf");

			printf("\n Scan of scan output is \n");
			printArray(numBlocks, temp2, true);
			*/

			kernAddEachBlockElement << < numBlocks, blkSize >> > (N,dev_buffer_2,dev_arr2);
			checkCUDAErrorFn("Adding Element to Each Block failed");

			/*
			int *temp2 = new int[numBlocks];

			cudaMemcpy(temp2, dev_buffer, sizeof(int) * numBlocks, cudaMemcpyDeviceToHost);
			checkCUDAErrorFn("Copying back to Host failed jfkgf");

			printf("\n Buffer output is \n");
			printArray(numBlocks, temp, true);
			*/

			/*
			kernLastElementBlockSum << <fullBlocksPerGrid3,blockSize >> > (N,dev_arr1,dev_arr2,dev_buffer);
			checkCUDAErrorFn("Kernel last element failed");

			do {

				treeScanSharedMem << <fullBlocksPerGrid3, blockSize, N * sizeof(int) >> > (N, dev_buffer, dev_buffer_out);
				checkCUDAErrorFn("Tree scan Shared mem failed");

				kernAddEachBlockElement << <fullBlocksPerGrid3, blockSize >> (dev_buffer_out,outdata);
				checkCUDAErrorFn("Kernel addition back failed");

			} while ();
			*/

			if (!stopTimer)
				timer().endGpuTimer();

			//printf("Hello 2\n");
			cudaMemcpy(odata, dev_arr2, sizeof(int) * N, cudaMemcpyDeviceToHost);
			checkCUDAErrorFn("Copying back to Host failed");

			//printf("\n Output is \n");
			//printArray(N, odata, true);

			cudaFree(dev_arr1);
			cudaFree(dev_arr2);

		}

		/**
		 * Performs stream compaction on idata, storing the result into odata.
		 * All zeroes are discarded.
		 *
		 * @param n      The number of elements in idata.
		 * @param odata  The array into which to store elements.
		 * @param idata  The array of elements to compact.
		 * @returns      The number of elements remaining after compaction.
		 */
		int compact(int n, int *odata, const int *idata) {

			dim3 fullBlocksPerGrid((n + blockSize - 1) / blockSize);

			cudaMalloc((void**)&dev_arr2, n * sizeof(int));
			checkCUDAErrorFn("Malloc idata into arr2 failed");

			cudaMalloc((void**)&dev_bools, n * sizeof(int));
			checkCUDAErrorFn("Malloc idata into arr3 failed");

			cudaMalloc((void**)&dev_indices, n * sizeof(int));
			checkCUDAErrorFn("Malloc idata into indices failed");

			cudaMalloc((void**)&dev_odata, n * sizeof(int));
			checkCUDAErrorFn("Malloc idata into odata failed");

			cudaMemcpy(dev_arr2, idata, sizeof(int) * n, cudaMemcpyHostToDevice);
			checkCUDAErrorFn("Copying idata to arr2 failed");

			timer().startGpuTimer();

			Common::kernMapToBoolean << <fullBlocksPerGrid, blockSize >> > (n, dev_bools, dev_arr2);
			checkCUDAErrorFn("Kernel Map indicator failed");

			int *indices = new int[n];
			int *bools = new int[n];

			cudaMemcpy(bools, dev_bools, sizeof(int) * n, cudaMemcpyDeviceToHost);
			checkCUDAErrorFn("Copying bools to host failed");

			scan(n, indices, bools);

			cudaMemcpy(dev_indices, indices, sizeof(int) * n, cudaMemcpyHostToDevice);
			checkCUDAErrorFn("Copying indices to device failed");

			Common::kernScatter << <fullBlocksPerGrid, blockSize >> > (n, dev_odata, dev_arr2, dev_bools, dev_indices);
			checkCUDAErrorFn("Kernel Scatter failed");

			timer().endGpuTimer();

			int length = indices[n - 1];

			if (idata[n - 1])
				length += 1;

			//printf("Length is %d \n", length);
			cudaMemcpy(odata, dev_odata, sizeof(int) * length, cudaMemcpyDeviceToHost);
			checkCUDAErrorFn("Copying back to the host failed");

			cudaFree(dev_arr2);
			cudaFree(dev_bools);
			cudaFree(dev_indices);
			cudaFree(dev_odata);
			return length;
		}
	}
}<file_sep>CUDA Path Tracer
================

**University of Pennsylvania, CIS 565: GPU Programming and Architecture, Project 3**

* <NAME>
  * [LinkedIn](https://www.linkedin.com/in/somanshu25)
* Tested on: Windows 10, i7-6700 @ 3.4GHz 16GB, Quadro P1000 4GB (Moore 100B Lab)

### What is Path Tracer and how it is different from Ray Tracing?

Path tracing is a realistic lighting algorithm that simulates light bouncing around a scene. it is based on Monte-Carlo based sampling technique and simulate realistic images through rendering. The path tracer is continually rendering, so the scene will start off grainy and become smoother over time. Path tracing is a similar rendering technique as ray tracing except the fact that path tracing uses random sampling to incrementally compute a final image. The side by side comparision below shows the importance of rendering the scene in iterations which removed the blurring of the image and noise.

    After 200 iterations            |           After 1500 iterations

The following features are enabled in the path tracer:

* Basic Features:
  * BSDF evaluation for Diffusion and Perfectly Specular Surfaces
  * Sort the rays after intersection with material ID type it intersected
  * Stream Compaction using Thrust
  * Cache First Bounce

* Adanced Features:
  * BSDF evaluation including Refraction, Fresnel Effect using Schlick's approximation
  * BSDF evaluation for Different Percentage Comnibations for Refraction and Reflection
  * Anit-aliasing
  * Work-Efficient Stream Compaction using Shared Memory
  * Motion Blur (attempted)

### BSDF Evaluation for Perfectly Specular, Diffusion Sufraces and Refraction Surfaces:
BSDF evaluation has been done for perfectly specular, diffusion and refractive surfaces. The evaluation was also done for specular surfaces where random combinations of reflection and refraction takes place. For reflection, I have used `glm::reflect` while for refraction, I have calculated the the value of index of refraction by assuming that one of the two medium will be air, caclulating the normal and using `glm::refract` function for caclulating the refracted ray. I'm also taking care of total internal reflection scenario. Also, the Fresnel effect is added into the shading using [Schlick's approximation](https://en.wikipedia.org/wiki/Schlick%27s_approximation).

    Perfectly Specular       |      Perfect Refraction      |     Diffusion

For diffusing, I have used the already defined cosign weighted distribution function for evaluating the new ray, which is the ransom permutation of the hemisphere. The images showing the effects of all these are:

For different combinations of relective and refractive probabilies, here are the effects shown in the images:

    Reflection:70%, Refract:30%            |           Reflection:30%, Refract:70%

In above, we can see for the material with more refract probabilty than reflect, the light is passing through and there is light in place of shadow.
### Sorting the rays by material ID

The rays after bouncing from the objects are sprted on the basis of the material ID, sicne, there is high chance that all these rays might strike the same object again and we have the rays at contigous memeory allocation in the memory which would quicken up the effect. In our cornell scene, we mostly observe that the sorting does not improve the performance that greatly because of lack of different materials in the scenes.

### Stream Compaction by using Thrust Library and Work Efficient using Shared memory

The stream compaction has benn done in the path tracer using Thrust library initially so that the basic working of the path tracer could be verified. After designing the basic path tracer, I worked on performing Stream Compaction using Shared Memory. The algorithm uses two stages of scanning where the first scanning happens using Shared Memory. The performace as shown in the graphs below. After performing the Work Efficient usign Shared memory algorithm across the blocks, we are getting the last element of each of the block and adding the last element in the original array in the block and performing again scan operation on the new array. Referred for the following reference for writing the code [GPU Gem Ch 39 ](https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch39.html)

The graph below shows the runtime for Work Efficient Shared memory vs Thrust library. It clearly indicated that the work efficent implementation with Shared Memory is much faster than Thrust.

### Caching the First Bounce

For each iteration, the rays are generated from the camera are likely to hit the same intersection material. Thus, computing the intersections every iteration would be costly and we can preserve that time by caching the first bounces that takes place in the first iteration and then later on just load those intersections for next iterations and prcess for the shading. The performance analysis for the caching and non-cahing as the function of depth in the first and second iteration is given below:

We can observe that for `depth = 0`, the runtime has increased drastically as we are not computing the intersections again.

### Anti-Aliasing

Anti-aliasing is the way of remove the jaggering happening during the rendering by sending out the rays from the camera and adding on the noise a little bit so that the smoothning effect could be seen the image. The effect of the anti-aliasing could be seen at the interections of the wall and the floor where the lines are more smoother as compared to the normal ones. The comparision of the effect is shown below:

    Without Anti-Aliasing           |           With Aliasing

Here, we can see that some of the jaggered lines in the left hand side which are not in the right hand side.

### Motion Blur

I have attemmpted to do motion blur n the path tracer and was going through lot of issues as the image is getting dark and lot of other stuff. The code for motion blur is in the code file "pathrace.cu".

### Bloopers

Some of the bloopers across all the experiments and features:

On the above blooper, my refraction was wrong as I was always refractive and then checking the condtiino for reflection.

When my stream cpoompaction Implementation was wrong with Work Efficient. I was not sorting in the last stage.

This when I didn't invert the normal vector for checking the refraction.

languages: Markdown Cuda

repo_language: Markdown


text:
<repo_name>tank-on-the-web/remote-camera<file_sep>/README.md
# カメラの動画を送受信する Firefox OS アプリ

- 送信側で getUserMedia で取得した Video stream を WebRTC で受信側に転送する。
- ハコスコで使うことを想定しているので Video stream の送信はあえて片方向。
- 使い方:
    1. 送信側/受信側それぞれに fxos-webrtc をインストール。
    2. webrtc-signalsvr を PC で起動。
    3. 受信側でインストールしたアプリを起動し、PC の IP アドレスを指定して "Wait video stream" を押す。
    4. 送信側もインストールしたアプリを起動し、PC の IP アドレスを指定して "Send video stream" を押す。

Firefox OS でなくても動くはず。

<file_sep>/fxos-webrtc/js/app.js
window.addEventListener("load", function() {
  var video = document.getElementById('remote-video');
  var control = document.getElementById('control');
  var viewer = document.getElementById('viewer');
  var indicator = document.getElementById('indicator');
  var localStream = null;

  // ---------------------- video handling -----------------------
  function startVideo(cb) {
    var callback = (cb || function() {});
    navigator.getUserMedia(
      { video: true, audio: false },
      streamSuccess,
      streamError
    );
    function streamSuccess(stream) {
      localStream = stream;
      video.src = window.URL.createObjectURL(stream);
      video.play();
      hide(control);
      show(viewer);
      callback(stream);
    }
    function streamError(error) {
      console.error('An error occurred: [CODE ' + error + ']');
      console.dir(error);
      return;
    }
  }

  // stop local video
  function stopVideo() {
    video.src = "";
    localStream.stop();
  }

  function hide(elm) {
    elm.style.display = 'none';
  }

  function show(elm) {
    elm.style.display = 'block';
  }

  var storedServer = window.localStorage.getItem('signalServer');
  if (storedServer) {
    document.getElementById('server').value = storedServer;
  }

  WebRTC.onAddStream = function onRemoteStreamAdded(event) {
    console.log("Remote stream added");
    video.src = window.URL.createObjectURL(event.stream);
    hide(indicator);
    show(viewer);
  };

  WebRTC.onRemoveStream = function onRemoteStreamRemoved(event) {
    console.log("Remote stream removed");
    video.src = "";
  };

  document.getElementById('start-listener').onclick = () => {
    var server = document.getElementById('server').value;
    window.localStorage.setItem('signalServer', server);
    WebRTC.init(server);
    hide(control);
    show(indicator);
  };

  document.getElementById('connect').onclick = () => {
    startVideo((stream) => {
      var server = document.getElementById('server').value;
      window.localStorage.setItem('signalServer', server);
      WebRTC.init(server, () => {
        WebRTC.setStream(localStream);
        WebRTC.connect();
      });
    });
  };
  // document.getElementById('stop-video').onclick = stopVideo;
  // document.getElementById('hang-up').onclick = () => { WebRTC.hangUp(); }
});
<file_sep>/fxos-webrtc/js/webrtc.js
(function() {
  var localStream = null;
  var peerConnection = null;
  var peerStarted = false;
  var mediaConstraints = {'mandatory': {'OfferToReceiveAudio':true, 'OfferToReceiveVideo':true }};
  if (navigator.mozGetUserMedia) {
    // Mandatory/optional in createOffer options is deprecated!
    // Use {"offerToReceiveAudio":true,"offerToReceiveVideo":true}
    // instead (note the case difference)!
    mediaConstraints = {'offerToReceiveAudio':false, 'offerToReceiveVideo':true };
  }

  // ---- socket ------
  // create socket
  var socketReady = false;
  var port = 9001;
  var socket;

  function openSocket(server, cb) {
    var callback = (cb || function () {});
    var url = 'http://' + server + '/';
    socket = io.connect(url);
    // socket: channel connected
    socket.on('connect', function (evt) {
      onOpened(evt);
      callback();
    }).on('message', onMessage);
  }

  function onOpened(evt) {
    console.log('socket opened.');
    socketReady = true;
  }

  // socket: accept connection request
  function onMessage(evt) {
    if (evt.type === 'offer') {
      console.log("Received offer, set offer, sending answer....")
      onOffer(evt);
    } else if (evt.type === 'answer' && peerStarted) {
      console.log('Received answer, settinng answer SDP');
      onAnswer(evt);
    } else if (evt.type === 'candidate' && peerStarted) {
      console.log('Received ICE candidate...');
      onCandidate(evt);
    } else if (evt.type === 'user dissconnected' && peerStarted) {
      console.log("disconnected");
      stop();
    }
  }

  // ----------------- handshake --------------
  var textForSendSDP;
  var textForSendICE;
  var textToReceiveSDP;
  var textToReceiveICE;
  var iceSeparator = '------ ICE Candidate -------';
  var CR = String.fromCharCode(13);

  function onSDP() {
    console.log("onSDP()");
    var text = textToReceiveSDP;
    var evt = JSON.parse(text);
    if (peerConnection) {
      onAnswer(evt);
    }
    else { // receiver
      onOffer(evt);
    }

    textToReceiveSDP = "";
  }

  //--- multi ICE candidate ---
  function onICE() {
    console.log("onICE()");
    var text = textToReceiveICE;
    var arr = text.split(iceSeparator);
    for (var i = 1, len = arr.length; i < len; i++) {
      var evt = JSON.parse(arr[i]);
      onCandidate(evt);
    }

    textToReceiveICE = "";
  }

  function onOffer(evt) {
    console.log("onOffer()")
    console.log(evt);
    setOffer(evt);
    sendAnswer(evt);
    peerStarted = true;
  }

  function onAnswer(evt) {
    console.log("onAnswer()")
    console.log(evt);
    setAnswer(evt);
  }

  function onCandidate(evt) {
    var candidate = new RTCIceCandidate({sdpMLineIndex:evt.sdpMLineIndex, sdpMid:evt.sdpMid, candidate:evt.candidate});
    console.log("onCandidate()")
    console.log(candidate);
    peerConnection.addIceCandidate(candidate);
  }

  function sendSDP(sdp) {
    var text = JSON.stringify(sdp);
    console.log("sendSDP()");
    console.log(text);

    textForSendSDP = text;
    // send via socket
    socket.json.send(sdp);
  }

  function sendCandidate(candidate) {
    var text = JSON.stringify(candidate);
    console.log("sendCandidate()");
    console.log(text);

    textForSendICE = (textForSendICE + CR + iceSeparator + CR + text + CR);

    // send via socket
    socket.json.send(candidate);
  }

  // ---------------------- connection handling -----------------------
  function prepareNewConnection() {
    console.log('prepareNewConnection()');
    var pc_config = {"iceServers":[]};
    var peer = null;
    try {
      peer = new RTCPeerConnection(pc_config);
    } catch (e) {
      console.log("Failed to create peerConnection, exception: " + e.message);
    }

    // send any ice candidates to the other peer
    peer.onicecandidate = function (evt) {
      console.log('*** onicecandidate ***');
      if (evt.candidate) {
        console.log(evt.candidate);
        sendCandidate(
          {
            type: "candidate",
            sdpMLineIndex: evt.candidate.sdpMLineIndex,
            sdpMid: evt.candidate.sdpMid,
            candidate: evt.candidate.candidate
          }
        );
      } else {
        console.log("End of candidates. ------------------- phase=" + evt.eventPhase);
      }
    };

    if (localStream) {
      console.log('Adding local stream...');
      peer.addStream(localStream);
    }
    peer.addEventListener("addstream", WebRTC.onAddStream, false);
    peer.addEventListener("removestream", WebRTC.onRemoveStream, false)

    return peer;
  }

  function sendOffer() {
    peerConnection = prepareNewConnection();
    peerConnection.createOffer(function (sessionDescription) { // in case of success
      peerConnection.setLocalDescription(sessionDescription);
      console.log("Sending: SDP");
      console.log(sessionDescription);
      sendSDP(sessionDescription);
    }, function (evt) { // in case of error
      console.log("Create Offer failed");
      alert("Create Offer failed: " + (evt.name ? evt.name : ""));
    }, mediaConstraints);
  }

  function setOffer(evt) {
    if (peerConnection) {
      console.error('peerConnection alreay exist!');
    }
    peerConnection = prepareNewConnection();
    peerConnection.setRemoteDescription(new RTCSessionDescription(evt));
  }

  function sendAnswer(evt) {
    console.log('sending Answer. Creating remote session description...' );
    if (! peerConnection) {
      console.error('peerConnection NOT exist!');
      return;
    }

    peerConnection.createAnswer(function (sessionDescription) { // in case of success
      peerConnection.setLocalDescription(sessionDescription);
      console.log("Sending: SDP");
      console.log(sessionDescription);
      sendSDP(sessionDescription);
    }, function () { // in case of error
      console.log("Create Answer failed");
    }, mediaConstraints);
  }

  function setAnswer(evt) {
    if (! peerConnection) {
      console.error('peerConnection NOT exist!');
      return;
    }
    peerConnection.setRemoteDescription(new RTCSessionDescription(evt));
  }

  // -------- handling user UI event -----
  function init(server, callback) {
    var cb = (callback || function () {});
    openSocket(server, cb);
  }

  function setStream(stream) {
    localStream = stream;
  }

  // start the connection upon user request
  function connect() {
    if (!peerStarted && localStream) {
      sendOffer();
      peerStarted = true;
    } else {
      alert("Local stream not running yet - try again.");
    }
  }

  // stop the connection upon user request
  function hangUp() {
    console.log("Hang up.");
    peerConnection.close();
    peerConnection = null;
    peerStarted = false;
  }

  // -------- export ---------
  window.WebRTC = (window.WebRTC || {});
  WebRTC.init = init;
  WebRTC.setStream = setStream;
  WebRTC.connect = connect;
  WebRTC.hangUp = hangUp;
  WebRTC.onAddStream = function() {};
  WebRTC.onRemoveStream = function() {};

})();

languages: Markdown JavaScript

repo_name: tank-on-the-web/remote-camera


text:
<file_sep># Plan5Day
A 5 day planner that opens to the current day and displays 5 days worth of plan-able activities. Time blocks are presented and color coded as to whether they are current, past, or present. Clicking on any time block allows for creation of an event on the planner, and whatever is input becomes saved for that time period on the calendar. Refreshing the page, or leaving and coming back, does not effect the saving, and it persists.


text:
<repo_name>raveena16046/Hidden-Markov-Model<file_sep>/hmm.py
from __future__ import division
import numpy as np
from math import log
import pickle
from pprint import pprint
file = open("Training set.txt" ,"r")
data = file.readlines()

# 3 tables to be maintained
#tag*tag = tag1 given tag2
#maintain count of tag
#iss word ke corresponding kitni baar tag hai word*tag
def createDict():
	tags = {}
	for line in data:
		if line not in ["\n" ,"\r\n"]:
			words = line.split("\t")
			#print len(words) ,
			tag = words[1]
			tag = tag.strip("\n")

			if  tag not in tags.keys():
				tags[tag ] = []
			if words[0] not in tags[tag]:
				tags[tag].append(words[0])
	return tags
mydict = createDict()

#print tags["PRP"]
output = open('Dictionary.pkl', 'wb')
pickle.dump(mydict, output)
output.close()

# read python dict back from the file
pkl_file = open('Dictionary.pkl', 'rb')
tags = pickle.load(pkl_file)
pkl_file.close()

transition = {}
for k in tags.keys():
	transition[k] = {}
transition["s"] = {}
for i in transition.keys():
	for j in transition.keys():
		transition[i][j] = 0

def createTagTable ():
	prev = "s"
	for line in data:
		if line not in ["\n" ,"\r\n"]:
			words = line.split("\t")
			#print len(words) ,
			tag = words[1]
			tag = tag.strip("\n")
			# print tag
			# print prev
			transition[tag][prev] += 1
			if tag == ".":
				prev = "s"
			else:
				prev = tag
createTagTable()
#do smoothing
def doSmoothing ():
	for i in transition.keys():
		for j in transition.keys():
			transition[i][j] += 1
doSmoothing()
output = open('TagTable.pkl', 'wb')
pickle.dump(transition, output)
output.close()

#read python dict back from the file
pkl_file = open('TagTable.pkl', 'rb')
transition = pickle.load(pkl_file)
pkl_file.close()
#print transition["NN"]
def createWordTag():
	tokens = []
	for i in tags.keys():
		for  j in tags[i]:
			tokens.append (j)
	tokens = list (set (tokens) )
	wordTag = {}
	for i in tokens:
		wordTag[i] = {}
	for i in tokens:
		for j in tags.keys():
			wordTag[i][j] = 0
	for line in data:
		if line not in ["\n" ,"\r\n"]:
			words = line.split("\t")
			#print len(words) ,
			tag = words[1]
			tag = tag.strip("\n")
			wordTag[words[0]][tag] += 1
	return wordTag
wordTag = createWordTag()
output = open('WordTagTable.pkl', 'wb')
pickle.dump(wordTag, output)
output.close()

#read python dict back from the file
pkl_file = open('WordTagTable.pkl', 'rb')
wordTag = pickle.load(pkl_file)
pkl_file.close()
#print len(wordTag)

def getCountOfTags ():
	countTag = {}
	for i in tags.keys():
		countTag[i] = 0
	for line in data:
		if line not in ["\n" ,"\r\n"]:
			words = line.split("\t")
			#print len(words) ,
			tag = words[1]
			tag = tag.strip("\n")
			countTag[tag] += 1
	return countTag

countTag = getCountOfTags()
#print countTag
countTag ["s" ] = countTag["."]
def calculateTransition ():
	for i in transition.keys():
		for j in transition.keys():
			transition[i][j] = transition[i][j]/( countTag[j]+ len(transition.keys() ) )

calculateTransition()
def calculateEmission ():
	N = len(countTag) -2
	for i in wordTag.keys():
		for j in wordTag[i]:
			wordTag [i][j] += 1
			wordTag[i][j] /= (countTag[j] + N)

calculateEmission()
#pprint (wordTag["yorkshire"])
# for i in transition.keys():
	# print i, transition["s"][i]

#print len(transition.keys())
#print len (wordTag["weekend"].keys() )
#print len ( countTag.keys() )'

def getTagCount():
	countTag = {}
	for k in transition.keys():
		if k not in ["." ,"s"]:
			countTag [k] = 0
	for line in data:
		if line not in ["\n" ,"\r\n"]:
			words = line.split("\t")
			#print len(words) ,
			tag = words[1]
			tag = tag.strip("\n")
			if tag not in ["." , ":"]:
				countTag [tag] += 1
	import operator

	sorted_x = sorted(countTag.items(), key=operator.itemgetter(1))
	print sorted_x

#getTagCount()

def viterbi(obs ):
	T = len( obs )
	N = len(wordTag)
	L = len(transition) - 2
	viterbi = {}
	for i in transition.keys():
		if i not in ["s"]:
			viterbi[i] = {}
			for j in range ( T ):
				viterbi[i][j] = []

	for s in viterbi.keys():
		if s not in ["s" , "."]:
			if obs[0] in wordTag.keys():
				viterbi[s][0].append( log (transition[s]["s"])+log (wordTag[obs[0]][s]) )
				viterbi[s][0].append("s")
			else:
				viterbi[s][0].append( log (transition[s]["s"])+log(1/N)) #probability
				viterbi[s][0].append("s")

	for t in range(1, T):
		for s in viterbi.keys():
			if s not in ["." ,"s"]:
				temp = []
				word = obs[t]

				for i in viterbi.keys() :
					if i not in ["." , "s"] :
						if word in wordTag.keys():
							b = wordTag[word][s] #emission prob
						else:
							if i in [ "NN" ,"VBP", "JJ", "RB" ]:
								b = 1/5
							else:
								b = (1/5)*(1/(L- 4))
								#print b #To be done for unknown words
						a = viterbi[i][t-1][0]+ log (transition[s][i]) + log (b)
						temp.append(a)
				m = max ( temp )
				ctr = 0
				for i in viterbi.keys() :
					if i not in ["." , "s"] :
						if temp[ctr] == m:
							#backpointer[s][t].append(i)
							viterbi[s][t].append(m)
							viterbi[s][t].append(i)
							break
						ctr += 1

	temp = []
	for i in viterbi.keys() :
		if i  not in ["." , "s"] :
			a = viterbi[i][T-1][0]+ log(transition["."][i])
			temp.append(a)
	m = max(temp)
	#backpointer[s][t] = []
	#m = max(temp)
	ctr = 0
	for i in viterbi.keys() :
		if i not in ["." , "s"] :
			if temp[ctr] == m:
				#backpointer[s][t].append(i)
				viterbi["."][T-1].append(m)
				viterbi["."][T-1].append(i)
			ctr += 1

	return  viterbi

#pprint (vit)
def do_viterbi( sentence):
	vit = viterbi(sentence)
	answer = []
	prev = vit["."][len(sentence) - 1][1]
	answer.insert( 0 , prev  )
	T = len (sentence)
	for t in range( T-2,-1, -1 ):
		prev = vit[prev][t+1][1]
		answer.insert(0 , prev )
	return answer
#vit = do_viterbi([ "she" , "like" , "weekend" ] )
#print vit
# for j in range(3):
	# max = 0.0
	# pos =""
	# for i in vit.keys():
		# print vit[i][j], "  ",
		# if max < vit [i][j]:
			# max = vit[i][j]
			# pos = i
	# print " max ", max ,"  ",pos ,"\n" ,

def doTest ():
	file = open("test_set.txt" ,"r")
	#output = open ()
	data = file.readlines()
	sentence =[]
	with open("Output.txt" , "w") as output:
		for line in data:
			#print line
			if line not in ["\n" ,"\r\n"]:
				#print "here"
				if "." in line:
					ans = do_viterbi (sentence)
					#print ans , sentence
					for i,j in zip(  sentence, ans):
						#print "hola"
						if i == "and\n":
							j = "CC"
						a = i.strip("\n")+"\t"+j
						#print a
						output.write(a+ '\n')
					output.write(".\t.\n\n")
					sentence =[]
				else:
					sentence.append(line)
	output.close()

doTest()
<file_sep>/README.md
# Hidden-Markov-Model
Here, the Hidden Markov Model for POS tagging (Part-of-Speech) has been implemented from scratch along with viterbi algorithm.
Given a sentence, it would do POS tagging of each word of the sentence.

languages: Markdown Python