Friday, January 13, 2012

Friday 1-13-12

Imports System
Imports System.Threading

Namespace Apress.VisualBasicRecipes.Chapter04

Class Recipe04_01
'a private class used to pass data to the Display Message
'method when it is executed using the thread pool
Private Class MessageInfo
Private m_Iterations As Integer
Private m_Message As String

'a constructor that takes configuration settings for the thread
Public Sub New(ByVal iterations As Integer, ByVal message As String)
m_Iterations = iterations
m_Message = message
End Sub

'properties to retrieve configuration settings
Public ReadOnly Property Iterations() As Integer
Get
Return m_Iterations
End Get
End Property

Public ReadOnly Property Message() As String
Get
Return m_Message
End Get
End Property

End Class


'a method that conforms to the System.Threading.WaitCallback delegate signature
'displays a message to the console
Public Shared Sub DisplayMessage(ByVal state As Object)
'Safely case the state argument to a messageinfo object
Dim config As MessageInfo = TryCast(state, MessageInfo)

'if the config argument is Nothing, no arguments were passed to the threadPool.QueueUserWorkItem method; use default values
If config Is Nothing Then
'display a fixed message to the console three times
For count As Integer = 1 To 3
Console.WriteLine("A thread pool example.")
'sleep for the purpose of demonstration avoid sleeping (of course) on thread-pool threads in real applications
Thread.Sleep(1000)
Next

Else
'display the specified message the specified number of times
For count As Integer = 1 To config.Iterations
Console.WriteLine(config.Message)
'seep for the purpose of demonstration, don't do this in real life lol
Thread.Sleep(1000)
Next
End If
End Sub


Public Shared Sub Main()
'execute DisplayMessage using the thread pool and no arguments
ThreadPool.QueueUserWorkItem(AddressOf DisplayMessage)

'create a MessageInfo object to pass to the DisplayMessage method
Dim info As New MessageInfo(5, "A thread pool example with arguments.")

'execute a DisplayMesage using the thread pool and providing an argument
ThreadPool.QueueUserWorkItem(AddressOf DisplayMessage, info)

Dim otherinfo As New MessageInfo(7, "Another example with arguments.")
ThreadPool.QueueUserWorkItem(AddressOf DisplayMessage, otherinfo)
'wait to continue
Console.WriteLine("Main method complete. Press Enter")
Console.ReadLine()
End Sub

End Class

End Namespace


using System.Numerics;

namespace CSharpPrac
{
class Program
{
static void Main(string[] args)
{
UseBigInteger();
BasicStringFunctionality();
StringConcatenation();
}

static void UseBigInteger()
{
Console.WriteLine("=> Use BigInteger:");
BigInteger biggy = BigInteger.Parse("999999999999999999999999999999999999999999999999999999999");
Console.WriteLine("Value of biggy is {0}", biggy);
Console.WriteLine("Is biggy an even value?: {0}", biggy.IsEven);
Console.WriteLine("Is biggy a power of two?: {0}", biggy.IsPowerOfTwo);
BigInteger reallyBig = BigInteger.Multiply(biggy, BigInteger.Parse("88888888888888888888888888888888888888888888888888888888888"));
Console.WriteLine("Value of reallyBig is {0}", reallyBig);
}

static void BasicStringFunctionality()
{
Console.WriteLine("=> Basic String functionality:");
string firstName = "Freddy";
Console.WriteLine("Value of firstName: {0}", firstName);
Console.WriteLine("firstName has {0} characters.", firstName.Length);
Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper());
Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower());
Console.WriteLine("firstName contains the letter y?: {0}", firstName.Contains("y"));
Console.WriteLine("firstName after replace: {0}", firstName.Replace("dy", ""));
Console.WriteLine();
}

static void StringConcatenation()
{
Console.WriteLine("=> String concatentation:");
string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";
string s3 = s1 + s2;
//string s3 = String.Concat(s1, s2);
Console.WriteLine(s3);
Console.WriteLine();
}
}
}



namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
EscapeChars();
StringEquality();
StringsAreImmutable();
FunWithStringBuilder();
}

static void EscapeChars()
{
Console.WriteLine("=> Escape characters:\a");
string strWithTabs = "Model\tColor\tSpeed\tPet Name\a ";
Console.WriteLine(strWithTabs);

Console.WriteLine("Everyone loves \"Hello World\"\a ");
Console.WriteLine("C:\\MyApp\\bin\\Debug\a ");

//adds a total of 4 blank lines (then beep again!)
Console.WriteLine("All finished.\n\n\n\a ");
Console.WriteLine();
}

static void StringEquality()
{
Console.WriteLine("=> String equality:");
string s1 = "Hello!";
string s2 = "Yo!";
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine("s2 = {0}", s2);
Console.WriteLine();

//test these strings for equality
Console.WriteLine("s1 == s2: {0}", s1 == s2);
Console.WriteLine("s1 == Hello!: {0}", s1 == "Hello!");
Console.WriteLine("s1 = HELLO!: {0}", s1 == "HELLO!");
Console.WriteLine("s1 == hello!: {0}", s1 == "hello!");
Console.WriteLine("s1.Equals(s2): {0}", s1.Equals(s2));
Console.WriteLine("Yo.Equals(s2): {0}", "Yo!".Equals(s2));
}

static void StringsAreImmutable()
{
//set initial string value
string s1 = "This is my string.";
Console.WriteLine("s1 = {0}", s1);

//uppercase s1?
string upperString = s1.ToUpper();
Console.WriteLine("upperString = {0}", upperString);

//nope! s1 is in the same format
Console.WriteLine("s1 = {0}", s1);
}

static void FunWithStringBuilder()
{
Console.WriteLine("=> Using the StringBuilder:");
StringBuilder sb = new StringBuilder("*** Fantastic games ****");
sb.Append("\n");
sb.AppendLine("Half Life");
sb.AppendLine("Beyond Good and Evil");
sb.AppendLine("Deus Ex 2");
sb.AppendLine("System Shock");
Console.WriteLine(sb.ToString());

sb.Replace("2", "Invisible War");
Console.WriteLine(sb.ToString());
Console.WriteLine("sb has {0} chars.", sb.Length);
Console.WriteLine();
}
}
}



class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Type Conversions *****");
//add two shorts and print the result
short numb1 = 9, numb2 = 10;
Console.WriteLine("{0} + {1} = {2}", numb1, numb2, Add(numb1, numb2));
Console.WriteLine();

numb1 = 30000;
numb2 = 30000;

//explicitly cast the int into a short (and allow loss of data)
short answer = (short)Add(numb1, numb2);

Console.WriteLine("{0} + {1} = {2}", numb1, numb2, answer);
NarrowingAttempt();
Console.ReadLine();
}

//widing is the term used to define an implicit upward cast that does not result in a loss of data
static int Add(int x, int y)
{
return x + y;
}

static void NarrowingAttempt()
{
byte myByte = 0;
int myInt = 200;

//explicitly cast the int into a byte (no loss of data)
myByte = (byte)myInt;
Console.WriteLine("Value of myByte: {0}", myByte);
}

static void ProcessBytes()
{
byte b1 = 100;
byte b2 = 250;

//this time tell the compiler to add CIL code to throw an exception if overflow /underflow
//takes place
try
{
byte sum = checked((byte)Add(b1, b2));
Console.WriteLine("sum = {0}", sum);

}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}
}
}



@autoreleasepool {
double value1, value2;
char operator;

Calculator *deskCalc = [[Calculator alloc] init];
NSLog(@"Type in your expression.");
scanf("%lf %c %lf", &value1, &operator, &value2);

[deskCalc setAccumulator: value1];

if (operator == '+')
[deskCalc add: value2];
else if (operator == '-')
[deskCalc subtract: value2];
else if (operator == '*')
[deskCalc multiply: value2];
else if (operator == '/')
if (value2 == 0)
NSLog(@"Division by zero.");
else
[deskCalc divide: value2];
else
NSLog(@"Unknown operator");

NSLog(@"%.2f", [deskCalc accumulator]);
}



@autoreleasepool {
double value1, value2;
char operator;

Calculator *deskCalc = [[Calculator alloc] init];

NSLog(@"Type in your expression.");
scanf("%lf %c %lf", &value1, &operator, &value2);

[deskCalc setAccumulator: value1];

switch (operator) {
case '+':
[deskCalc add: value2];
break;
case '-':
[deskCalc subtract: value2];
break;
case '*':
[deskCalc multiply: value2];
break;
case '/':
[deskCalc divide: value2];
break;
default:
NSLog(@"Unkown operator.");
break;
}
NSLog(@"%.2f", [deskCalc accumulator]);
}

@autoreleasepool {
int p, d, isPrime;

for (p = 2; p <= 200; ++p){
isPrime = 1;

for (d = 2; d < p; ++d){
if (p % d == 0)
isPrime = 0;

}
if (isPrime != 0)
NSLog(@"%i ", p);
}
}

No comments:

Post a Comment