/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ /* This module contains the recursive descent parser that recognizes variables. */ using System; // Exception class for parser errors. class ParserException : ApplicationException { public ParserException(string str) : base(str) { } public override string ToString() { return Message; } } class Parser { // Enumerate token types. enum Types { NONE, DELIMITER, VARIABLE, NUMBER }; // Enumerate error types. enum Errors { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO }; string exp; // refers to expression string int expIdx; // current index into the expression string token; // holds current token Types tokType; // holds token's type // Array for variables. double[] vars = new double[26]; public Parser() { // Initialize the variables to zero. for(int i=0; i < vars.Length; i++) vars[i] = 0.0; } // Parser entry point. public double Evaluate(string expstr) { double result; exp = expstr; expIdx = 0; try { GetToken(); if(token == "") { SyntaxErr(Errors.NOEXP); // no expression present return 0.0; } EvalExp1(out result); // now, call EvalExp1() to start if(token != "") // last token must be null SyntaxErr(Errors.SYNTAX); return result; } catch (ParserException exc) { // Add other error handling here, as desired. Console.WriteLine(exc); return 0.0; } } // Process an assignment. void EvalExp1(out double result) { int varIdx; Types ttokType; string temptoken; if(tokType == Types.VARIABLE) { // save old token temptoken = String.Copy(token); ttokType = tokType; // Compute the index of the variable. varIdx = Char.ToUpper(token[0]) - 'A'; GetToken(); if(token != "=") { PutBack(); // return current token // restore old token -- not an assignment token = String.Copy(temptoken); tokType = ttokType; } else { GetToken(); // get next part of exp EvalExp2(out result); vars[varIdx] = result; return; } } EvalExp2(out result); } // Add or subtract two terms. void EvalExp2(out double result) { string op; double partialResult; EvalExp3(out result); while((op = token) == "+" || op == "-") { GetToken(); EvalExp3(out partialResult); switch(op) { case "-": result = result - partialResult; break; case "+": result = result + partialResult; break; } } } // Multiply or divide two factors. void EvalExp3(out double result) { string op; double partialResult = 0.0; EvalExp4(out result); while((op = token) == "*" || op == "/" || op == "%") { GetToken(); EvalExp4(out partialResult); switch(op) { case "*": result = result * partialResult; break; case "/": if(partialResult == 0.0) SyntaxErr(Errors.DIVBYZERO); result = result / partialResult; break; case "%": if(partialResult == 0.0) SyntaxErr(Errors.DIVBYZERO); result = (int) result % (int) partialResult; break; } } } // Process an exponent. void EvalExp4(out double result) { double partialResult, ex; int t; EvalExp5(out result); if(token == "^") { GetToken(); EvalExp4(out partialResult); ex = result; if(partialResult == 0.0) { result = 1.0; return; } for(t=(int)partialResult-1; t > 0; t--) result = result * (double)ex; } } // Evaluate a unary + or -. void EvalExp5(out double result) { string op; op = ""; if((tokType == Types.DELIMITER) && token == "+" || token == "-") { op = token; GetToken(); } EvalExp6(out result); if(op == "-") result = -result; } // Process a parenthesized expression. void EvalExp6(out double result) { if((token == "(")) { GetToken(); EvalExp2(out result); if(token != ")") SyntaxErr(Errors.UNBALPARENS); GetToken(); } else Atom(out result); } // Get the value of a number or variable. void Atom(out double result) { switch(tokType) { case Types.NUMBER: try { result = Double.Parse(token); } catch (FormatException) { result = 0.0; SyntaxErr(Errors.SYNTAX); } GetToken(); return; case Types.VARIABLE: result = FindVar(token); GetToken(); return; default: result = 0.0; SyntaxErr(Errors.SYNTAX); break; } } // Return the value of a variable. double FindVar(string vname) { if(!Char.IsLetter(vname[0])){ SyntaxErr(Errors.SYNTAX); return 0.0; } return vars[Char.ToUpper(vname[0])-'A']; } // Return a token to the input stream. void PutBack() { for(int i=0; i < token.Length; i++) expIdx--; } // Handle a syntax error. void SyntaxErr(Errors error) { string[] err = { "Syntax Error", "Unbalanced Parentheses", "No Expression Present", "Division by Zero" }; throw new ParserException(err[(int)error]); } // Obtain the next token. void GetToken() { tokType = Types.NONE; token = ""; if(expIdx == exp.Length) return; // at end of expression // skip over white space while(expIdx < exp.Length && Char.IsWhiteSpace(exp[expIdx])) ++expIdx; // trailing whitespace ends expression if(expIdx == exp.Length) return; if(IsDelim(exp[expIdx])) { // is operator token += exp[expIdx]; expIdx++; tokType = Types.DELIMITER; } else if(Char.IsLetter(exp[expIdx])) { // is variable while(!IsDelim(exp[expIdx])) { token += exp[expIdx]; expIdx++; if(expIdx >= exp.Length) break; } tokType = Types.VARIABLE; } else if(Char.IsDigit(exp[expIdx])) { // is number while(!IsDelim(exp[expIdx])) { token += exp[expIdx]; expIdx++; if(expIdx >= exp.Length) break; } tokType = Types.NUMBER; } } // Return true if c is a delimiter. bool IsDelim(char c) { if((" +-/*%^=()".IndexOf(c) != -1)) return true; return false; } } // Demonstrate the parser. public class ParserDemo1 { public static void Main() { string expr; Parser p = new Parser(); Console.WriteLine("Enter an empty expression to stop."); for(;;) { Console.Write("Enter expression: "); expr = Console.ReadLine(); if(expr == "") break; Console.WriteLine("Result: " + p.Evaluate(expr)); } } }
Regular Expressions: More Complex Parsing
/* A Programmer's Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3 */ // 17 - StringsRegular ExpressionsMore Complex Parsing // copyright 2000 Eric Gunnerson // file=logparse.cs // compile with: csc logparse.cs using System; using System.Net; using System.IO; using System.Text.RegularExpressions; using System.Collections; public class MoreComplexParsing { public static void Main(string[] args) { if (args.Length == 0) //we need a file to parse { Console.WriteLine("No log file specified."); } else ParseLogFile(args[0]); } public static void ParseLogFile(string filename) { if (!System.IO.File.Exists(filename)) { Console.WriteLine ("The file specified does not exist."); } else { FileStream f = new FileStream(filename, FileMode.Open); StreamReader stream = new StreamReader(f); string line; line = stream.ReadLine(); // header line line = stream.ReadLine(); // version line line = stream.ReadLine(); // Date line Regex regexDate= new Regex(@":s(?<date>[^s]+)s"); Match match = regexDate.Match(line); string date = ""; if (match.Length != 0) date = match.Groups["date"].ToString(); line = stream.ReadLine(); // Fields line Regex regexLine = new Regex( // match digit or : @"(?<time>(d|:)+)s" + // match digit or . @"(?<ip>(d|.)+)s" + // match any non-white @"(?<method>S+)s" + // match any non-white @"(?<uri>S+)s" + // match any non-white @"(?<status>d+)"); // read through the lines, add an // IISLogRow for each line while ((line = stream.ReadLine()) != null) { //Console.WriteLine(line); match = regexLine.Match(line); if (match.Length != 0) { Console.WriteLine("date: {0} {1}", date, match.Groups["time"]); Console.WriteLine("IP Address: {0}", match.Groups["ip"]); Console.WriteLine("Method: {0}", match.Groups["method"]); Console.WriteLine("Status: {0}", match.Groups["status"]); Console.WriteLine("URI: {0} ", match.Groups["uri"]); } } f.Close(); } } }
Set NumberGroupSeparator
using System.Globalization; using System; public class MainClass { public static void Main() { NumberFormatInfo f = new NumberFormatInfo(); f.NumberGroupSeparator = " "; Console.WriteLine(12345.6789.ToString("N3", f)); // 12 345.679 } }
Use NumberFormatInfo to format a number
using System; using System.Globalization; public class MainClass { public static void Main() { NumberFormatInfo f = new NumberFormatInfo(); f.CurrencySymbol = "$$"; Console.WriteLine(3.ToString("C", f)); // $$ 3.00 } }
SMK MediaPlayer
/* Professional Windows GUI Programming Using C# by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury, Zach Greenvoss, Shripad Kulkarni, Neil Whitlow Publisher: Peer Information ISBN: 1861007663 */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using MediaPlayer ; namespace SMK_MediaPlayer { /// <summary> /// Summary description for SMKMediaPlayer. /// </summary> public class SMKMediaPlayer : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private AxMediaPlayer.AxMediaPlayer mPlayer = null ; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.NotifyIcon notifyIcon1; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.MenuItem menuItem4; private System.Windows.Forms.ContextMenu contextMenu1; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem menuItem6; private System.ComponentModel.IContainer components; public SMKMediaPlayer() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { notifyIcon1.Dispose() ; mPlayer.Stop() ; mPlayer.Dispose(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } private void streamEnded(object sender , AxMediaPlayer._MediaPlayerEvents_EndOfStreamEvent e) { this.Show(); notifyIcon1.Visible = false ; mPlayer.Stop(); mPlayer.CurrentPosition= 0.0; } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SMKMediaPlayer)); this.panel2 = new System.Windows.Forms.Panel(); this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.menuItem4 = new System.Windows.Forms.MenuItem(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.contextMenu1 = new System.Windows.Forms.ContextMenu(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.menuItem6 = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); // // panel2 // this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(344, 109); this.panel2.TabIndex = 1; // // notifyIcon1 // this.notifyIcon1.Text = "notifyIcon1"; this.notifyIcon1.Visible = true; // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.menuItem4}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem2, this.menuItem3}); this.menuItem1.Text = "File"; // // menuItem2 // this.menuItem2.Index = 0; this.menuItem2.Text = "Open"; this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); // // menuItem3 // this.menuItem3.Index = 1; this.menuItem3.Text = "Exit"; this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click); // // menuItem4 // this.menuItem4.Index = 1; this.menuItem4.Text = "Hide"; this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click); // // imageList1 // this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.imageList1.ImageSize = new System.Drawing.Size(16, 16); this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // contextMenu1 // this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem5, this.menuItem6}); // // menuItem5 // this.menuItem5.Index = 0; this.menuItem5.Text = "Show"; this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click); // // menuItem6 // this.menuItem6.Index = 1; this.menuItem6.Text = "Exit"; this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click); // // SMKMediaPlayer // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(344, 109); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.panel2}); this.MaximizeBox = false; this.Menu = this.mainMenu1; this.Name = "SMKMediaPlayer"; this.Text = "ActiveX Media Player"; this.Load += new System.EventHandler(this.SMKMediaPlayer_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new SMKMediaPlayer()); } private void SMKMediaPlayer_Load(object sender, System.EventArgs e) { notifyIcon1.Icon = new Icon("EYE.ico"); notifyIcon1.Text = "SMK Media Player 1.0"; notifyIcon1.Visible = false ; notifyIcon1.DoubleClick += new EventHandler(NotifyIconDoubleClick); notifyIcon1.ContextMenu = contextMenu1 ; mPlayer = new AxMediaPlayer.AxMediaPlayer(); mPlayer.BeginInit(); mPlayer.Size = new System.Drawing.Size(292, 273); mPlayer.Location = new System.Drawing.Point(0 , 16); mPlayer.TabIndex = 0; mPlayer.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Controls.AddRange(new System.Windows.Forms.Control[] {this.mPlayer}); mPlayer.EndOfStream += new AxMediaPlayer._MediaPlayerEvents_EndOfStreamEventHandler(this.streamEnded); mPlayer.EndInit(); } private void menuItem2_Click(object sender, System.EventArgs e) { try { Image im = imageList1.Images[0]; OpenFileDialog fd = new OpenFileDialog(); fd.ShowDialog(); mPlayer.Open(fd.FileName); mPlayer.Play(); } catch(Exception eee) { Console.WriteLine(eee.Message); } } private void menuItem4_Click(object sender, System.EventArgs e) { notifyIcon1.Visible = true ; this.Hide(); } private void menuItem3_Click(object sender, System.EventArgs e) { Application.Exit() ; } private void menuItem5_Click(object sender, System.EventArgs e) { notifyIcon1.Visible = false; this.Show(); } private void menuItem6_Click(object sender, System.EventArgs e) { notifyIcon1.Visible = false ; Application.Exit() ; } private void NotifyIconDoubleClick(object sender, System.EventArgs e) { this.Visible = true ; this.Activate() ; this.Show() ; this.BringToFront() ; } } } SMK_MediaPlayer.zip( 181 k)
Same as System.Math.Acos but if angle is out of range, the result is clamped.
public static class MathUtility { //------------------------------------------------------------------------------------- /// <summary> /// Same as System.Math.Acos but if angle is out of range, the result is clamped. /// </summary> /// <param name="angle">Input angle.</param> /// <returns>Acos the angle.</returns> //------------------------------------------------------------------------------------- public static float SafeAcos(float angle) { if(angle <= -1.0f) { return (float) (System.Math.PI); } if(angle >= 1.0f) { return 0.0f; } return (float) System.Math.Acos(angle); } }
Get Prime, Is prime
//GNU Library General Public License (LGPL)
//http://dac.codeplex.com/license
using System;
using System.Runtime.ConstrainedExecution;
namespace RaisingStudio.Collections.Generic
{
internal static class HashHelpers
{
internal static readonly int[] primes = new int[] {
3, 7, 11, 0x11, 0x17, 0x1d, 0x25, 0x2f, 0x3b, 0x47, 0x59, 0x6b, 0x83, 0xa3, 0xc5, 0xef,
0x125, 0x161, 0x1af, 0x209, 0x277, 0x2f9, 0x397, 0x44f, 0x52f, 0x63d, 0x78b, 0x91d, 0xaf1, 0xd2b, 0xfd1, 0x12fd,
0x16cf, 0x1b65, 0x20e3, 0x2777, 0x2f6f, 0x38ff, 0x446f, 0x521f, 0x628d, 0x7655, 0x8e01, 0xaa6b, 0xcc89, 0xf583, 0x126a7, 0x1619b,
0x1a857, 0x1fd3b, 0x26315, 0x2dd67, 0x3701b, 0x42023, 0x4f361, 0x5f0ed, 0x72125, 0x88e31, 0xa443b, 0xc51eb, 0xec8c1, 0x11bdbf, 0x154a3f, 0x198c4f,
0x1ea867, 0x24ca19, 0x2c25c1, 0x34fa1b, 0x3f928f, 0x4c4987, 0x5b8b6f, 0x6dda89
};
internal static int GetMinPrime()
{
return primes[0];
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static int GetPrime(int min)
{
for (int i = 0; i < primes.Length; i++)
{
int num2 = primes[i];
if (num2 >= min)
{
return num2;
}
}
for (int j = min | 1; j < 0x7fffffff; j += 2)
{
if (IsPrime(j))
{
return j;
}
}
return min;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
{
return (candidate == 2);
}
int num = (int)Math.Sqrt((double)candidate);
for (int i = 3; i <= num; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return true;
}
}
}
[/csharp]