Margin and padding in Silverlight UIElements
<StackPanel Background="Gray"> <TextBox Background="LightGray" Margin="10" Padding="10" Text="Margin is outside, Padding is inside" /> </StackPanel>
Horizontal and vertical alignment in Silverlight
The example below shows the effects of all four HorizontalAlignment options and all four VerticalAlignment options. The HorizontalAlignment property accepts the Left, Center, Right, and Stretch values, whereas the VerticalAlignment property accepts the Top, Center, Bottom, and Stretch values.
<StackPanel Orientation="Horizontal"> <StackPanel Width="200" Background="LightGray"> <TextBox HorizontalAlignment="Left" /> <TextBox HorizontalAlignment="Center" /> <TextBox HorizontalAlignment="Right" /> <TextBox HorizontalAlignment="Stretch" /> </StackPanel> <Canvas Width="20"></Canvas> <StackPanel Width="200" Background="LightGray" Orientation="Horizontal"> <TextBox VerticalAlignment="Top" /> <TextBox VerticalAlignment="Center" /> <TextBox VerticalAlignment="Bottom" /> <TextBox VerticalAlignment="Stretch" /> </StackPanel> </StackPanel>
Two visible elements and one collapsed element in a StackPanel
<StackPanel x:Name="myStackPanel" Background="Orange" Width="90"> <TextBox x:Name="tb1" Width="60" Background="LightGray" /> <TextBox x:Name="tb2" Width="60" Background="DarkGray" Visibility="Collapsed" /> <TextBox x:Name="tb3" Width="60" Background="Gray" /> </StackPanel> Listing 6.2 highlights
Three visible elements in a StackPanel
<StackPanel x:Name="myStackPanel" Background="Orange" Width="90"> <TextBox x:Name="tb1" Width="60" Background="LightGray" /> <TextBox x:Name="tb2" Width="60" Background="DarkGray" /> <TextBox x:Name="tb3" Width="60" Background="Gray" /> </StackPanel>
Using the Stylus cursor with a TextBlock in Silverlight
<Canvas Cursor="Hand" Background="Green" Height="60" Width="180"> <TextBox Cursor="Stylus" Height="20" Width="60" /> </Canvas>
Using #elif in C
#if STATUS == 1 #define PERSON "Single" #elif STATUS == 2 #define PERSON "Married" #elif STATUS == 3 #define PERSON "Divorced" #elif #define PERSON "Widowed" #endif
Retrieve user specified lines from a text & store these lines to another destination file
#include <stdio.h> #include <process.h> #define MAX 500 void makendx(FILE *rfp, FILE *nfp) { long line=0, spot=0; int ch; /* leave space for storing total number of lines in file*/ fseek(nfp,(long)sizeof(long),0); /* Write the position of the first line*/ fwrite((char*)&spot, sizeof(long),1,nfp); /* loop to store the positions of the subsequent lines */ while((ch=fgetc(rfp))!= EOF){ ++spot; if(ch=='n'){ ++spot; line++; fwrite((char*)&spot,sizeof(long),1,nfp); } } /* Go to the top of the index file and store total lines*/ rewind(nfp); fwrite((char*)&line,sizeof(long),1,nfp); fclose(nfp); return; } void makeout(FILE *rfp, FILE *wfp, FILE *nfp) { long lines,lineno,start,end; char chunk[MAX]; /*reopen index for reading*/ if((nfp=fopen("tmp.ndx","rb+"))==NULL){ fprintf(stderr,"Cannot open tmp.ndxn"); exit(5); } /* read total numbers of lines in source*/ fread((char*)&lines,sizeof(long),1,nfp); printf("Enter line numbers to retrieve one by one:n"); /* loop to get desired line and store to destination*/ while(1){ scanf("%ld",&lineno); if(lineno==0) return; if(lineno>lines) continue; /* set file position indicator to get starting position*/ fseek(nfp,lineno*sizeof(long),0); /* read starting position*/ fread((char*)&start,sizeof(long),1,nfp); /* read starting position of next line to count number of characters in the current one*/ fread((char*)&end,sizeof(long),1,nfp); /* position the indicator to the start of source*/ fseek(rfp,start,0); /*read desired number of character*/ fread((char*)&chunk,1,end-start-1,rfp); /* write the line to destination file*/ fwrite((char*)&chunk,1,end-start-1,wfp); } return; } int main(int argc, char *argv[]) { FILE *rfp, *wfp, *nfp; if(argc!=3){ fprintf(stderr,"Usage : %s <source> <destination>n",argv[0]); exit(1); } if((rfp=fopen(*++argv,"r"))== NULL){ fprintf(stderr,"Cannot open %s n",*argv); exit(2); } if((wfp=fopen(*++argv,"w"))==NULL){ fprintf(stderr,"Cannot open %sn", *argv); exit(3); } if((nfp=fopen("tmp.ndx","wb+"))==NULL){ fprintf(stderr,"Cannot open tmp.ndxn"); exit(4); } makendx(rfp,nfp); makeout(rfp,wfp,nfp); fclose(rfp); fclose(wfp); fclose(nfp); return 0; }
Program listing for simulating the cat command in UNIX with error handling
#include <stdio.h> #include <process.h> void copyfile(FILE *,FILE *); int main(int argc, char *argv[]) { FILE *fileptr, *fopen(); if(argc>1) while(--argc>0) if((fileptr=fopen(*++argv, "r"))==NULL) { fprintf(stderr,"cat : can't open %sn",*argv); exit(1); } else{ copyfile(fileptr,stdout); fclose(fileptr); } else copyfile(stdin, stdout); if(ferror(stdout)) { fprintf(stderr, "cat : error in writing at stdoutn" ); exit(2); } return(0); } /* Function to copy file from rfp to wfp */ void copyfile(FILE *rfp, FILE *wfp) { int c; while((c=fgetc(rfp))!=EOF) fputc(c, wfp); return; }
Program listing for simulating the cat command in UNIX
#include <stdio.h> #include <process.h> void copyfile(FILE *, FILE *); int main(int argc,char *argv[]) { FILE *fileptr,*fopen(); if(argc>1) while(--argc>0) if((fileptr=fopen(*++argv, "r"))==NULL) { printf("cat : can't open %sn",*argv); exit(1); } else { copyfile(fileptr,stdout); fclose(fileptr); } else copyfile(stdin, stdout); return(0); } /* Function to copy file from rfp to wfp */ void copyfile (FILE *rfp,FILE *wfp) { int c; while((c=fgetc(rfp))!=EOF) fputc(c, wfp); return; }
Parse and format a date in Java
import java.text.DateFormat; import java.text.ParseException; import java.util.Date; public class DateFormatTest { public static void main(String[] args) { DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM); DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG); DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL); System.out.println(shortDf.format(new Date())); System.out.println(mediumDf.format(new Date())); System.out.println(longDf.format(new Date())); System.out.println(fullDf.format(new Date())); // parsing try { Date date = shortDf.parse("12/12/2010"); } catch (ParseException e) { } } }
After and before methods in Java date class
The after method returns true if this date is a later time than the when argument. Otherwise, it returns false. The before method returns true if this date is before the specified date and returns false otherwise.
The following code prints “date1 before date2″ because the first date represents a time that is one millisecond earlier than the second.
Date date1 = new Date(1000); Date date2 = new Date(1001); if (date1.before(date2)) { System.out.println("date1 before date2"); } else { System.out.println("date1 not before date2"); }
Parsing numbers in Java
The example below takes user input and parses it. If the user types in an invalid number, an error message will be displayed.
import java.util.Scanner; public class NumberTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String userInput = scanner.next(); try { int i = Integer.parseInt(userInput); System.out.println("The number entered: " + i); } catch (NumberFormatException e) { System.out.println("Invalid user input"); } } }
Methods in the Math class in Java
public static double abs(double a)
Returns the absolute value of the specified double..
public static double acos(double a)
Returns the arc cosine of an angle, in the range of 0.0 through pi.
public static double asin(double a)
Returns the arc sine of an angle, in the range of –pi/2 through pi/2.
public static double atan(double a)
Returns the arc tangent of an angle, in the range of –pi/2 through pi/2.
public static double cos(double a)
Returns the cosine of an angle.
public static double exp(double a)
Returns Euler’s number e raised to the power of the specified double.
public static double log(double a)
Returns the natural logarithm (base e) of the specified double.
public static double log10(double a)
Returns the base 10 logarithm of the specified double.
public static double max(double a, double b)
Returns the greater of the two specified double values.
public static double min(double a, double b)
Returns the smaller of the two specified double values.
Example of continue with a label in Java
start: for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { if (j == 2) { continue start; } System.out.println(i + ":" + j); } }
The result of running this code is as follows:
0:0
0:1
1:0
1:1
2:0
2:1
Produce three beeps with a 500 milliseconds interval between two beeps in Java
java.awt.Toolkit.getDefaultToolkit().beep(); try { Thread.currentThread().sleep(500); } catch (Exception e) { } java.awt.Toolkit.getDefaultToolkit().beep(); try { Thread.currentThread().sleep(500); } catch (Exception e) { } java.awt.Toolkit.getDefaultToolkit().beep();
Use if with a series of else statements in Java
if (a == 1) { System.out.println("one"); } else if (a == 2) { System.out.println("two"); } else if (a == 3) { System.out.println("three"); } else { System.out.println("invalid"); }
Dangling else problem in Java
The else statement in the code below is dangling because it is not clear which if statement the else statement is associated with. An else statement is always associated with the immediately preceding if. Using braces makes your code clearer.
if (a > 0 || b < 5) if (a > 2) System.out.println("a > 2"); else System.out.println("a < 2");
Character literals that are escape sequences in Java
‘b’ the backspace character
‘t’ the tab character
‘\’ the backslash
”’ single quote
‘”‘ double quote
‘n’ linefeed
‘r’ carriage return
Primitive data types in Java
| Primitive | Description | Range |
|---|---|---|
| byte | Byte-length integer (8 bits) | -128 (-27) to 127 (27-1) |
| short | Short integer (16 bits) | -32,768 (-215) to 32,767 (-215-1) |
| int | Integer (32 bits) | -2,147,483,648 (-231) to 2,147,483,647 (-231-1) |
| long | Long integer (64 bits) | -9,223,372,036,854,775,808 (-263) to 9,223,372,036,854,775,807 (263-1) |
| float | Single-precision floating point (32-bit IEEE 7541) | Smallest positive nonzero: 14e-45 Largest positive nonzero: 3.4028234e38 |
| double | Double-precision floating point (64-bit IEEE 754) | Smallest positive nonzero: 4.9e-324 Largest positive nonzero: 1.7976931348623157e308 |
| char | A Unicode character | [See Unicode 6 specification] |
| boolean | A boolean value | true or false |
Separators in Java
| Symbol | Name | Description |
|---|---|---|
| () | Parentheses | Used in:
|
| {} | Braces | Used in:
|
| [] | Brackets | Used in:
|
| < > | Angle brackets | Used to pass parameter to parameterized types. |
| ; | Semicolon | Used to terminate statements and in the for statement to separate the initialization code, the expression, and the update code. |
| : | Colon | Used in the for statement that iterates over an array or a collection. |
| , | Comma | Used to separate arguments in method declarations. |
| . | Period | Used to separate package names from subpackages and type names, and to separate a field or method from a reference variable. |
