Tuesday, August 18, 2009
A Novel Generic Multi-Layer Neural Networks :: Part 1: The Neuron Class
This post presents a model that I created for a NN program that I developed to solve general numeric problems (prediction, estimation, interpolation, extrapolation, etc.).
public class Neuron
{
private double __lastOutput;
private double __lastError;
private double __lastBias;
private double[] __lastWeights;
private int __siblingCount;
private int __layerInputCount;
#region Properties
private Delegates.ActivationFunction _ActivationFunction;
public Delegates.ActivationFunction ActivationFunction
{ get { return _ActivationFunction; } }
private int _InputCount;
public int InputCount
{ get { return _InputCount; } }
private double _Bias;
public double Bias
{ get { return _Bias; } }
private double[] _Weights;
public double[] Weights
{ get { return _Weights; } }
#endregion
#region Constructor
public Neuron(Delegates.ActivationFunction activationFunction, int inputCount, double? initialBias, double[] initialWeights, int siblingCount)
{ _ActivationFunction = activationFunction;
_InputCount = inputCount;
__siblingCount = siblingCount;
__layerInputCount = _InputCount * __siblingCount;
__lastError = 0.0;
if (initialBias == null)
_Bias = GlobalModule.GetRandomValue();
else
_Bias = initialBias.Value;
__lastBias = _Bias;
if (initialWeights == null)
{
_Weights = GlobalModule.GetRandomValue(inputCount);
}
else if (initialWeights.Length == inputCount)
{
initialWeights.CopyTo(_Weights, 0);
initialWeights.CopyTo(__lastWeights, 0);
}
else
throw new Exception("Invalid number of initial weights!");
}
#endregion
#region Public Methods
public double ComputeOutput(double[] input)
{
double totalInput = _Bias;
for (int i = 0; i <>
totalInput += _Weights[i] * input[i];
__lastOutput = _ActivationFunction.Invoke(totalInput);
return __lastOutput;
}
public void ChangeWeights(double error) // it also modifies the bias
{
double roughSharePlus = Math.Abs(error) / __layerInputCount;
double roughShareMinus = -roughSharePlus;
double curBias = _Bias;
if (Math.Abs(error) > Math.Abs(__lastError)) // worse (weak result)
{
roughSharePlus = -roughSharePlus;
roughShareMinus = -roughShareMinus;
}
for (int i = 0; i <> _Weights[i])
{
__lastWeights[i] = _Weights[i];
_Weights[i] += roughShareMinus * GlobalModule.GetRandomValue();
}
} // next i
if(__lastBias <> curBias)
_Bias += roughShareMinus * GlobalModule.GetRandomValue() * (__lastBias - curBias);
__lastBias = curBias;
return;
}
public void ReinitializeWeights() // it also reinitialize the bias
{
_Weights = GlobalModule.GetRandomValue(_InputCount);
_Bias = GlobalModule.GetRandomValue();
}
#endregion
} // end of class Neuron
Sunday, August 9, 2009
Conceptual Design in Database Development
The conceptual design is the first phase in the database design process:
- Conceptual Design
- Logical Design
- Implementation (Adaption)
- Physical Design
The conceptual design phase is a process of "Analysis and Discovery" and its goal is to define the "Requirements" of a system (a company/business/organization/etc.).
There are four main tasks to do in this phase:
1. Documenting the entities and the relationships between entities
2. Documenting the business rules for data
3. Defining the scope of the system
4. Defining a plan for security of the system
Saturday, August 8, 2009
Could not start Telegram Desktop
Sunday, July 26, 2009
Reading Content of a Website Page
This short post shows how to read content of a web page by having its web address in ASP.NET.
In desktop applications, this task could simply be done by using a web browser control, i.e. System.Windows.Controls.WebBrowser, but in ASP.NET we need to use HttpWebRequest and HttpWebResponse objects as follows:
public static StringBuilder GetDocumet(string url)
{
StringBuilder rtn;
HttpWebRequest request;
HttpWebResponse response = null;
Stream stream = null;
StreamReader sr = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
sr = new StreamReader(stream);
rtn = new StringBuilder(sr.ReadToEnd());
}
catch
{
rtn = null; // not found
}
sr.Close();
stream.Close();
response.Close();
return rtn;
}
Friday, July 24, 2009
Sunday, July 19, 2009
Tuesday, June 30, 2009
Water Effect:: Water Over Using GDI+ (source code)
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.Runtime.InteropServices;
using System;
namespace WaterOver.GR
{
public class WaterOver
{
///
/// Create Water Over an Animated GIF Frames.
///
/// Returns full file name of frames.
public static string[] CreateWaterOverFrames(Bitmap bmp, int frameCount, string outputPath, string fileName)
{
string[] rtn = new string[frameCount];
int width = bmp.Width;
int height = bmp.Height;
int _waveWidth = width;
int _waveHeight = height;
int[, ,] __wave = new int[_waveWidth,_waveHeight, 2];
int __buffer = 0;
int radius = (int)(0.6 * Math.Min(width, height));
int fromX = (int)(4.0 * width / 10.0);
int toX = 1 + (int)(6.0 * width / 10.0);
int fromY = height - (1 + (int)(height / 10.0));
int toY = height;
Random r = new Random();
int x, y;
string gnlFfn; // general full file name (to save frame files)
// Set gnlFfn.
outputPath = outputPath.Trim();
if(!outputPath.EndsWith(@"\"))
outputPath += @"\";
gnlFfn = outputPath + fileName.Trim() + "_";
byte[] _bmpBytes = new Byte[width * height * 4];
// Set _bmpBytes.
BitmapData _bmpBitmapData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
Marshal.Copy(_bmpBitmapData.Scan0, _bmpBytes, 0, width * height * 4);
////////////////////////////////
// Generate frames one by one //
////////////////////////////////
for (int h = 0; h < frameCount;h++)
{
///////////////////
// Refine waves. //
///////////////////
int __newBuffer = (__buffer == 0) ? 1 : 0;
bool wavesFound = false;
for (x = 1; x <>for (y = 1; y <>> 2) - __wave[x, y, __newBuffer];
if (__wave[x, y, __newBuffer] != 0)
{
__wave[x, y, __newBuffer] -= __wave[x, y, __newBuffer] >> 4;
wavesFound = true;
}
} // next y
} // next x
__buffer = __newBuffer;
///////////////////////////////
// Put a wave center (drop). //
///////////////////////////////
x = r.Next(fromX , toX);
y = r.Next(fromY, toY);
double dist;
for (int i = -radius; i <= radius; i++) { for (int j = -radius; j <= radius; j++) { if (((x + i <= 0) && (x + i < dist =Math.Sqrt(i * i + j * j);
if (dist <>int)(Math.Cos(dist * Math.PI / radius) * height);
}
}
}
/////////////////////
// Paint the frame //
/////////////////////
using (Bitmap tmpBmp = (Bitmap)bmp.Clone())
{
int xOffset, yOffset;
byte alpha;
if (wavesFound)
{
BitmapData tmpData = tmpBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb);
byte[] tmpBytes = new Byte[width * height * 4];
Marshal.Copy(tmpData.Scan0, tmpBytes, 0, width * height * 4);
for (x = 1; x <>for (y = 1; y <>int waveX = x;
int waveY = y;
// Check bounds.
if (waveX <= 0) waveX = 1; if (waveY <= 0) waveY = 1; if (waveX <= _waveWidth - 1) waveX = _waveWidth - 2; if (waveY <= _waveHeight - 1) waveY = _waveHeight - 2; // Make the effect of water breaking the light.
xOffset = (__wave[waveX - 1, waveY, __buffer] - __wave[waveX + 1, waveY, __buffer]) >> 3;
yOffset = (__wave[waveX, waveY - 1, __buffer] - __wave[waveX, waveY + 1, __buffer]) >> 3;
if ((xOffset != 0) (yOffset != 0))
{
// Check bounds.
if (x + xOffset >= width - 1) xOffset = width - x - 1;
if (y + yOffset >= height - 1) yOffset = height - y - 1;
if (x + xOffset < 0) xOffset = -x;
if (y + yOffset < 0) yOffset = -y;
// Generate alpha.
alpha = (byte)(200 - xOffset);
if (alpha <>
alpha = 0;
if (alpha < alpha =" 254;">// Set colors.
tmpBytes[4 * (x + y * width)] = _bmpBytes[4 * (x + xOffset + (y + yOffset) * width)];
tmpBytes[4 * (x + y * width) + 1] = _bmpBytes[4 * (x + xOffset + (y + yOffset) * width) + 1];
tmpBytes[4 * (x + y * width) + 2] = _bmpBytes[4 * (x + xOffset + (y + yOffset) * width) + 2];
tmpBytes[4 * (x + y * width) + 3] = alpha;
}
} // next y
} // next x
// Copy data back.
Marshal.Copy(tmpBytes, 0, tmpData.Scan0, width * height * 4);
tmpBmp.UnlockBits(tmpData);
}
// Save tmpBmp, the new frame generated.
rtn[h] = gnlFfn + h.ToString() + ".gif";
tmpBmp.Save(rtn[h], ImageFormat.Gif);
}
} // next h
return rtn;
}
}
}
The method CreateWaterOverFrames returns an array of file names (frames) that can be used in a function to create a single animated gif file; there are a few of them; one that is fairly a good one and simple to use can be found here.
LINQ
Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
An efficient way to experiment with LINQ is to download LINQPad, at www.linqpad.net.
Water Effect:: Water Over Using GDI+
The code in this post is to create a water effect sample, water over, on images using .NET's GDI+.
See the following example!
This image:
Will be converted to the following animated GIF:
The following code shows how to add water waves over frames; where each frame is initiated by the original image.
~ continued (see the next post).
Tuesday, March 31, 2009
Design Patterns :: Singleton
There are many common situations when singleton pattern is used:
- Accesing resources in shared mode
- Configuration Classes
- Logger Classes
- Serialization
- Network Port Interface
Singleton Design Pattern |
Check list
1.Define a private static attribute in the "single instance" class.
2.Define a public static accessor function in the class.
3.Do "lazy initialization" (creation on first use) in the accessor function.
4.Define all constructors to be protected or private.
5.Clients may only use the accessor function to manipulate the Singleton.
- using System;
- namespace DesignPatternsSingleton
- {
- /// <summary>
- /// MainApp startup class for Design Patterns :: Singleton
- /// </summary>
- class MainApp
- {
- /// <summary>
- /// The Singleton class.
- /// </summary>
- public class Singleton
- {
- private static Singleton _instance;
- // Constructor is 'protected'
- protected Singleton()
- {
- }
- public static Singleton Instance()
- {
- // Uses lazy initialization.
- // Note: this is not thread safe.
- if (_instance == null)
- {
- _instance = new Singleton();
- }
- return _instance;
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Threading;
- namespace DesignPatternsSingleton
- {
- /// <summary>
- /// MainApp startup class for Real-World
- /// Singleton Design Pattern.
- /// </summary>
- class MainApp
- {
- /// <summary>
- /// Entry point into console application.
- /// </summary>
- static void Main()
- {
- LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
- LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
- // Same instance?
- if (b1 == b2 && b2 == b3 && b3 == b4)
- {
- Console.WriteLine("Same instance\n");
- }
- // Load balance 15 server requests
- LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
- for (int i = 0; i < 15; i++)
- {
- string server = balancer.Server;
- Console.WriteLine("Dispatch Request to: " + server);
- }
- // Wait for user
- Console.ReadKey();
- }
- }
- /// <summary>
- /// The 'Singleton' class
- /// </summary>
- class LoadBalancer
- {
- private static LoadBalancer _instance;
- private List<string> _servers = new List<string>();
- private Random _random = new Random();
- // Lock synchronization object
- private static object syncLock = new object();
- // Constructor (protected)
- protected LoadBalancer()
- {
- // List of available servers
- _servers.Add("ServerI");
- _servers.Add("ServerII");
- _servers.Add("ServerIII");
- _servers.Add("ServerIV");
- _servers.Add("ServerV");
- }
- public static LoadBalancer GetLoadBalancer()
- {
- // Support multithreaded applications through
- // 'Double checked locking' pattern which (once
- // the instance exists) avoids locking each
- // time the method is invoked
- if (_instance == null)
- {
- lock (syncLock)
- {
- if (_instance == null)
- {
- _instance = new LoadBalancer();
- }
- }
- }
- return _instance;
- }
- // Simple, but effective random load balancer
- public string Server
- {
- get
- {
- int r = _random.Next(_servers.Count);
- return _servers[r].ToString();
- }
- }
- }
- }
Setting Language/Culture in Using Global Resource Files
Setting Language/Culture in Using Global Resource Files
In this short post, in the code of an aspx page, we want to make the page to use our global resource file called UI.fr-CA.resx that is in Canadian French (fr-CA).
In order to this, just open the source code of the page (or the source code of the super class of your page class) and override its InitializeCulture method as in the following:
protected override void InitializeCulture()
{
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-CA");
base.InitializeCulture();
}
There is a good point in the above code: it works even if your controls or user controls located in the page have processes in threads different from the current thread!
Wednesday, March 18, 2009
Creational Design Patterns
List of Creational Design Patterns
1) Abstract Factory
2) Adapter
3) Bridge
4) Builder
5) Chain of Responsibility
6) Command
7) Composite
8) Decorator
9) Facade
10) Factory Method
11) Flyweight
12) Interpreter
13) Iterator
14) Mediator
15) Memento
16) Observer
17) Prototype
18) Proxy
19) Singleton
20) State
21) Strategy
22) Template Method
23) Visitor
Creational Design Patterns
- Abstract Factory
- Builder
- Factory Method
- Prototype
- Singleton
Object Initializers with Anonymous Types
Object Initializers with Anonymous Types
In C# 3.0, we can use object initializers with anonymous types. The following example shows how it can be done:
The Customer class is an arbitrary class that we want to use in this example:
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
We declare a colloecton of customers by employing "object initializers":
List
{
new Customer { CustomerID = 99, FirstName = "Brian" , LastName = "White"},
new Customer { CustomerID = 100, FirstName = "Nicole" , LastName = "Stewart"},
new Customer { CustomerID = 101, FirstName = "Lucy" , LastName = "Brothers"}
};
Now, we create a LINQ query where the returning objects have anonymous types; an anonymous type that has two properties: ID and Name; and also we employ the object initializer concept to initialize the properties of our objects:
var selCust = from c in customers
where c.CustomerID <= 100
orderby c.LastName, c.FirstName
select new { ID = c.CustomerID, Name = c.FirstName + " " + c.LastName};
The variable selCust contains objects of an anonymous type with their properties already set (initialized). To confirm this, run the following code snippet:
foreach (var cust in selCust)
{
Console.WriteLine(cust.ID.ToString() + " " + cust.Name);
}
Saturday, February 21, 2009
Compiling, Packaging and Deploying [Part One]
Question 1: How do you deploy your web application, “MyApp”, to a virtual directory “MyApp” of www.ASPCert.com where the user interface should be updatable and there shouldn’t be a delay when the web pages are accessed for the first time?
By compiling and deploying the application as:
aspnet_compiler -v /MyApp -u "http://www.ASPCert.com/MyApp"
Original questions authored by G. R. Roosta
ASPX Page [Part One]
Question 1: What is the order of events fired when an ASPX page is loaded and displayed?
9 events are fired in this order:
- PreInit
- Init
- InitComplete
- PreLoad
- Load
- LoadComplete
- PreRender
- PreRenderComplete
- Unload
Original questions authored by G. R. Roosta
ASP.NET MVC Framework
Model–View–Controller (MVC) is an architectural pattern in software engineering. This pattern isolates business logic from user interface leading to applications that modifying the visual appearance and the biz rules can be performed independently.
In MVC, the model represents data of the application, the controller manages the communication between data and the biz rules (to manipulate data) and the view corresponds to items in the user interface (pages/forms and controls).
ASP.NET MVC provides a MVC framework on top of the existing ASP.NET 3.5 runtime. This new framework defines a pattern to the web application folder structure and provides a controller base-class to handle and process requests for “actions”. Developers can use the specific Visual Studio 2008 MVC templates to create MVC web applications (You can download it from: http://www.microsoft.com/downloads/details.aspx?FamilyID=f4e4ee26-4bc5-41ed-80c9-261336b2a5b6). MVC framework is extensible allowing developers to create sophisticated structures that meet their needs, including for example Dependency Injection techniques, new view rendering engines or specialized controllers. As ASP.NET MVC framework is built on ASP.NET 3.5, developers can also take advantage of the existing ASP.NET 3.5 features with this framework.
Tuesday, February 10, 2009
Creating Server Controls [Part One]
Question 1: How do you declare the class a server control that must support data binding and data paging?
The class should inherit from DataBoundControl and implement the IPageableItemContainer interface; for example:
public class MyClass : DataBoundControl, IPageableItemContainer
{
...
}
Original questions authored by G. R. Roosta
Sunday, February 8, 2009
WCF & ASP.NET 3.5 Web Services [Part One]
Question 1: How are ASP.NET web services set to work with ASP.NET AJAX scripts?
The attribute [System.Web.Script.Services.ScriptService] is set for the class of each web service. This attribute indicates that a web service may be invoked from script.
Example:
[WebService(Namespace = "http://www.aspcert.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld( )
{
return "Hello World";
}
}
Original questions authored by G. R. Roosta
My New Blog: Questions in ASP.NET 3.5
See my new blog, Questions in ASP.NET 3.5, at http://aspnet35questions.blogspot.com/
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - - - -