using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BreadthFirst
{
class Program
{
public class Person
{
public Person(string name)
{
this.name = name;
}
public string name { get; set; }
public List<Person> Friends
{
get
{
return FriendsList;
}
}
public void isFriendOf(Person p)
{
FriendsList.Add(p);
}
List<Person> FriendsList = new List<Person>();
public override string ToString()
{
return name;
}
}
public class BreadthFirstAlgorithm
{
public Person BuildFriendGraph()
{
Person Aaron = new Person("Aaron");
Person Betty = new Person("Betty");
Person Brian = new Person("Brian");
Aaron.isFriendOf(Betty);
Aaron.isFriendOf(Brian);
Person Catherine = new Person("Catherine");
Person Carson = new Person("Carson");
Person Darian = new Person("Darian");
Person Derek = new Person("Derek");
Betty.isFriendOf(Catherine);
Betty.isFriendOf(Darian);
Brian.isFriendOf(Carson);
Brian.isFriendOf(Derek);
return Aaron;
}
//http://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode
public Person Search(Person root, string nameToSearchFor)
{
Queue<Person> Q = new Queue<Person>();
HashSet<Person> S = new HashSet<Person>();
Q.Enqueue(root);
S.Add(root);
while (Q.Count > 0)
{
Person p = Q.Dequeue();
if (p.name == nameToSearchFor)
return p;
foreach (Person friend in p.Friends)
{
if (!S.Contains(friend))
{
Q.Enqueue(friend);
S.Add(friend);
}
}
}
return null;
}
public void Traverse(Person root)
{
Queue<Person> traverseOrder = new Queue<Person>();
Queue<Person> Q = new Queue<Person>();
HashSet<Person> S = new HashSet<Person>();
Q.Enqueue(root);
S.Add(root);
while (Q.Count > 0)
{
Person p = Q.Dequeue();
traverseOrder.Enqueue(p);
foreach (Person friend in p.Friends)
{
if (!S.Contains(friend))
{
Q.Enqueue(friend);
S.Add(friend);
}
}
}
while (traverseOrder.Count > 0)
{
Person p = traverseOrder.Dequeue();
Console.WriteLine(p);
}
}
}
static void Main(string[] args)
{
BreadthFirstAlgorithm b = new BreadthFirstAlgorithm();
Person root = b.BuildFriendGraph();
Console.WriteLine("Traverse\n------");
b.Traverse(root);
Console.WriteLine("\nSearch\n------");
Person p = b.Search(root, "Catherine");
Console.WriteLine(p == null ? "Person not found" : p.name);
p = b.Search(root, "Alex");
Console.WriteLine(p == null ? "Person not found" : p.name);
}
}
}
Simple multithreaded server/client in Java
Server.java
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
public void Start()
{
try {
ServerSocket serverSocket = new ServerSocket(5000);
ExecutorService service = Executors.newFixedThreadPool(20);
while(true)
{
final Socket socket = serverSocket.accept();
service.submit(new Runnable() {
@Override
public void run() {
try {
StringBuilder sb = new StringBuilder();
InputStreamReader br = new InputStreamReader(socket.getInputStream());
int c;
while((c = br.read()) != 0)
{
sb.append((char)c);
}
System.out.println("rec: " + sb.toString());
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
Date date = new Date();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
String outStr = dateFormat.format(date) + '\0';
os.write(outStr.getBytes());
socket.close();
System.out.println("sent: " + sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server s = new Server();
s.Start();
}
}
Client.java
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Client {
public void Start()
{
final int NUMBER_OF_THREADS = 2000;
ExecutorService service = Executors.newFixedThreadPool(20);
for(int i = 0; i < NUMBER_OF_THREADS; i++)
{
service.submit(new Runnable() {
@Override
public void run() {
try {
StringBuilder sb = new StringBuilder();
Socket s = new Socket("127.0.0.1", 5000);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outStr = dateFormat.format(date) + '\0';
os.write(outStr.getBytes());
System.out.println("sent: " + outStr);
InputStreamReader br = new InputStreamReader(s.getInputStream());
int c;
while((c = br.read()) != 0)
{
sb.append((char)c);
}
System.out.println("rec: " + sb.toString());
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
public static void main(String[] args) {
Client c = new Client();
c.Start();
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Simple multithreaded server/client in C#
Server Code
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace server
{
public class server
{
ManualResetEvent tcpClientConnected = new ManualResetEvent(false);
void ProcessIncomingData(object obj)
{
TcpClient client = (TcpClient)obj;
StringBuilder sb = new StringBuilder();
using (NetworkStream stream = client.GetStream())
{
int i;
while ((i = stream.ReadByte()) != 0)
{
sb.Append((char)i);
}
string reply = "ack: " + sb.ToString() + '\0';
stream.Write(Encoding.ASCII.GetBytes(reply), 0, reply.Length);
}
Console.WriteLine(sb.ToString());
}
void ProcessIncomingConnection(IAsyncResult ar)
{
TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
ThreadPool.QueueUserWorkItem(ProcessIncomingData, client);
tcpClientConnected.Set();
}
public void start()
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000);
TcpListener listener = new TcpListener(endpoint);
listener.Start();
while (true)
{
tcpClientConnected.Reset();
listener.BeginAcceptTcpClient(new AsyncCallback(ProcessIncomingConnection), listener);
tcpClientConnected.WaitOne();
}
}
}
class Program
{
static void Main(string[] args)
{
server s = new server();
s.start();
}
}
}
Client Code
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace client
{
class Program
{
const int NUMBER_OF_THREADS = 2000;
void Work(object obj)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000);
TcpClient client = new TcpClient();
client.Connect(ep);
StringBuilder sb = new StringBuilder();
using (NetworkStream stream = client.GetStream())
{
string request = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt") + '\0';
Console.WriteLine("sent: " + request);
stream.Write(Encoding.ASCII.GetBytes(request), 0, request.Length);
int i;
while ((i = stream.ReadByte()) != 0)
{
sb.Append((char)i);
}
}
client.Close();
Console.WriteLine(sb.ToString());
}
void start()
{
for (int i = 0; i < NUMBER_OF_THREADS; i++)
{
ThreadPool.QueueUserWorkItem(Work);
}
}
static void Main(string[] args)
{
Program p = new Program();
p.start();
//press any key to exit
Console.ReadKey();
Environment.Exit(0);
}
}
}
Simple Form in Ruby on Rails (all code)
config/routes.rb
RegistrationForm::Application.routes.draw do get "registration/index" post "registration/index" => "registration#register" get "registration/list" => "registration#list" get "registration/delete" => "registration#delete" get "registration/edit/:regid" => "registration#edit" post "registration/edit/:regid" => "registration#update" end
app/models/registration.rb
class Registration < ActiveRecord::Base
attr_accessible :fname, :lname
validates :fname, :length => { :maximum => 10 }, presence:true
validates :lname, :length => { :maximum => 10 }, presence:true
end
app/controllers/registration_controller.rb
class RegistrationController < ApplicationController
def index
end
def register
@reg = params[:reg]
@fname = params[:reg][:fname]
@lname = params[:reg][:lname]
@registration = Registration.create(params[:reg])
@registration.save
end
def list
@allReg = Registration.all
end
def delete
@recDeleted = Registration.delete(params[:regid])
if(@recDeleted == 0)
flash[:message] = "Error: No record deleted!"
else
flash[:message] = "Successfully deleted"
end
redirect_to :action => "list"
end
def edit
begin
@reg = Registration.find(params[:regid])
rescue ActiveRecord::RecordNotFound => e
flash[:message] = "Record Not Found!!!"
redirect_to :action => "list"
end
end
def update
begin
@reg = Registration.find(params[:regid])
rescue
flash[:message] = "Error saving! Record Not found!"
redirect_to :action => "list"
end
@reg.fname = params[:registration][:fname]
@reg.lname = params[:registration][:lname]
@reg.save
redirect_to :action => "list"
end
end
app/views/registration/index.html.erb
<%= form_for(:reg) do |r| %> <%= r.label :fname, "First Name" %>: <%= r.text_field :fname, :maxlength => 20 %><br> <%= r.label :lname, "Last Name" %>: <%= r.text_field :lname, :maxlength => 20 %><br> <%= r.submit "Register" %> <% end %>
app/views/registration/register.html.erb
JSON string:<br>
<%= @reg %>
<br>
<br>
First Name: <br>
<%= @fname %>
<br>
<br>
Last Name: <br>
<%= @lname %>
<br><br>
<% if @registration.errors.messages.any? %>
Errors:<br>
<%= @registration.errors.messages %>
<br><br>
<% @registration.errors.full_messages.each do |msg| %>
<%= msg %><br>
<% end %>
<% else %>
No errors! <br>
Record saved
<% end %>
app/views/registration/list.html.erb
<html>
<body>
<% @message = flash[:message] %>
<% if (@message != nil and @message.length > 0) %>
<%= @message %> <br><br>
<% end %>
<table border = "1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<% @allReg.each do |r| %>
<tr>
<td>
<%= r.fname %>
</td>
<td>
<%= r.lname %>
</td>
<td>
<%= link_to "Delete", action: "delete", regid: r.id %>
</td>
<td>
<%= link_to "Edit", action: "edit", regid: r.id %>
</td>
</tr>
<% end %>
</table>
</body>
</html>
app/views/registration/edit.html.erb
<%= form_for @reg, url:params[:regid], method: :post do |r| %> <%= r.label :fname, "First Name" %>: <%= r.text_field :fname %> <br> <%= r.label :lname, "Last Name" %>: <%= r.text_field :lname %><br> <%= r.submit "Update" %> <% end %>
Simple Form with updating records in Ruby on Rails
Continued from Simple Form with deleting records in Ruby on Rails
config/routes.rb
RegistrationForm::Application.routes.draw do get "registration/index" post "registration/index" => "registration#register" get "registration/list" => "registration#list" get "registration/delete" => "registration#delete" get "registration/edit/:regid" => "registration#edit" post "registration/edit/:regid" => "registration#update" end
app/views/registration/list.html.erb
<html>
<body>
<% @message = flash[:message] %>
<% if (@message != nil and @message.length > 0) %>
<%= @message %> <br><br>
<% end %>
<table border = "1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<% @allReg.each do |r| %>
<tr>
<td>
<%= r.fname %>
</td>
<td>
<%= r.lname %>
</td>
<td>
<%= link_to "Delete", action: "delete", regid: r.id %>
</td>
<td>
<%= link_to "Edit", action: "edit", regid: r.id %>
</td>
</tr>
<% end %>
</table>
</body>
</html>
app/controllers/registration_controller.rb
class RegistrationController < ApplicationController
def index
end
def register
@reg = params[:reg]
@fname = params[:reg][:fname]
@lname = params[:reg][:lname]
@registration = Registration.create(params[:reg])
@registration.save
end
def list
@allReg = Registration.all
end
def delete
@recDeleted = Registration.delete(params[:regid])
if(@recDeleted == 0)
flash[:message] = "Error: No record deleted!"
else
flash[:message] = "Successfully deleted"
end
redirect_to :action => "list"
end
def edit
begin
@reg = Registration.find(params[:regid])
rescue ActiveRecord::RecordNotFound => e
flash[:message] = "Record Not Found!!!"
redirect_to :action => "list"
end
end
def update
begin
@reg = Registration.find(params[:regid])
rescue
flash[:message] = "Error saving! Record Not found!"
redirect_to :action => "list"
end
@reg.fname = params[:registration][:fname]
@reg.lname = params[:registration][:lname]
@reg.save
redirect_to :action => "list"
end
end
app/views/registration/edit.html.erb
<%= form_for @reg, url:params[:regid], method: :post do |r| %> <%= r.label :fname, "First Name" %>: <%= r.text_field :fname %> <br> <%= r.label :lname, "Last Name" %>: <%= r.text_field :lname %><br> <%= r.submit "Update" %> <% end %>
Simple Form with deleting records in Ruby on Rails
Continued from Simple Form with listing records in Ruby on Rails
config/routes.rb
RegistrationForm::Application.routes.draw do get "registration/index" post "registration/index" => "registration#register" get "registration/list" => "registration#list" get "registration/delete" => "registration#delete" end
app/controllers/registration_controller.rb
class RegistrationController < ApplicationController
def index
end
def register
@reg = params[:reg]
@fname = params[:reg][:fname]
@lname = params[:reg][:lname]
@registration = Registration.create(params[:reg])
@registration.save
end
def list
@allReg = Registration.all
end
def delete
@recDeleted = Registration.delete(params[:regid])
if(@recDeleted == 0)
flash[:message] = "Error: No record deleted!"
else
flash[:message] = "Successfully deleted"
end
redirect_to :action => "list"
end
end
app/views/registration/list.html.erb
<html>
<body>
<% @message = flash[:message] %>
<% if (@message != nil and @message.length > 0) %>
<%= @message %> <br><br>
<% end %>
<table border = "1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<% @allReg.each do |r| %>
<tr>
<td>
<%= r.fname %>
</td>
<td>
<%= r.lname %>
</td>
<td>
<%= link_to "Delete", action: "delete", regid: r.id %>
</td>
</tr>
<% end %>
</table>
</body>
</html>
Simple Form with listing records in Ruby on Rails
Continued from Simple Form with saving record in Ruby on Rails
config/routes.rb
RegistrationForm::Application.routes.draw do get "registration/index" post "registration/index" => "registration#register" get "registration/list" => "registration#list" end
app/controllers/registration_controller.rb
class RegistrationController < ApplicationController
def index
end
def register
@reg = params[:reg]
@fname = params[:reg][:fname]
@lname = params[:reg][:lname]
@registration = Registration.create(params[:reg])
@registration.save
end
def list
@allReg = Registration.all
end
end
app/views/registration/list.html.erb
<html>
<body>
<table border = "1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<% @allReg.each do |r| %>
<tr>
<td>
<%= r.fname %>
</td>
<td>
<%= r.lname %>
</td>
</tr>
<% end %>
</table>
</body>
</html>
Simple Form with saving record in Ruby on Rails
Continued from Simple Form with Validation in Ruby on Rails
app/controllers/registration_controller.rb
class RegistrationController < ApplicationController
def index
end
def register
@reg = params[:reg]
@fname = params[:reg][:fname]
@lname = params[:reg][:lname]
@registration = Registration.create(params[:reg])
@registration.save
end
end
app/views/registration/register.html.erb
JSON string:<br>
<%= @reg %>
<br>
<br>
First Name: <br>
<%= @fname %>
<br>
<br>
Last Name: <br>
<%= @lname %>
<br><br>
<% if @registration.errors.messages.any? %>
Errors:<br>
<%= @registration.errors.messages %>
<br><br>
<% @registration.errors.full_messages.each do |msg| %>
<%= msg %><br>
<% end %>
<% else %>
No errors! <br>
Record saved
<% end %>
Simple Form with Validation in Ruby on Rails
Continued from Simple Form in Ruby on Rails
1) rails generate model Registration fname:string lname:string
2) rake db:migrate
3) app/models/registration.rb
class Registration < ActiveRecord::Base
attr_accessible :fname, :lname
validates :fname, :length => { :maximum => 10 }, presence:true
validates :lname, :length => { :maximum => 10 }, presence:true
end
4) app/controllers/registration_controller.rb
class RegistrationController < ApplicationController
def index
end
def register
@reg = params[:reg]
@fname = params[:reg][:fname]
@lname = params[:reg][:lname]
@registration = Registration.create(params[:reg])
end
end
5) app/views/registration/register.html.erb
JSON string:<br>
<%= @reg %>
<br>
<br>
First Name: <br>
<%= @fname %>
<br>
<br>
Last Name: <br>
<%= @lname %>
<br><br>
<% if @registration.errors.messages.any? %>
Errors:<br>
<%= @registration.errors.messages %>
<br><br>
<% @registration.errors.full_messages.each do |msg| %>
<%= msg %><br>
<% end %>
<% else %>
No errors!
<% end %>
Simple Form in Ruby on Rails
1) rails new RegistrationForm
2) cd RegistrationForm
3) rails generate controller registration index register
4) app/controllers/registration_controller.rb
class RegistrationController < ApplicationController
def index
end
def register
@reg = params[:reg]
@fname = params[:reg][:fname]
@lname = params[:reg][:lname]
end
end
5) app/views/registration/index.html.erb
<%= form_for(:reg) do |r| %> <%= r.label :fname, "First Name" %>: <%= r.text_field :fname, :maxlength => 20 %><br> <%= r.label :lname, "Last Name" %>: <%= r.text_field :lname, :maxlength => 20 %><br> <%= r.submit "Register" %> <% end %>
6) app/views/registration/register.html.erb
JSON string:<br> <%= @reg %> <br> <br> First Name: <br> <%= @fname %> <br> <br> Last Name: <br> <%= @lname %>
7) config/routes.rb
RegistrationForm::Application.routes.draw do get "registration/index" post "registration/index" => "registration#register" end
8) rails s
9) http://localhost:3000/registration/index