Tips&Tricks | I trucchi del mestiere |
![]() |
Come utilizzare l'aritmetica |
public class SimpleArithmetic { public static void main(String[] args) { int withdraw = 300; int deposit = 400; // dichiarare e inizializzare le variabili int balance = deposit - withdraw; // incrementare un valore balance = balance + 100; balance += 100; // utilizzare valori booleani boolean isGood = false; isGood = !isGood; // isGood ora Φ vero // tutti gli opeartori hanno la semantica |
![]() |
Come realizzare metodi ricorsivi |
public class LetterCombinations { private static String sum = ""; public static void main(String[] argv) { long l = System.currentTimeMillis(); printAlphabetCombinations(4,""); System.out.println("Time:"+ (System.currentTimeMillis() - l)/1000 + " sec"); } public static void printAlphabetCombinations(int recurseCounter,String current) { String temp = current; if (recurseCounter==0) { System.out.println(temp); return; } else { recurseCounter--; for (int i=0; i<26;i++) { temp = current+(char)(65+i); printAlphabetCombinations(recurseCounter,temp); } } } } |
![]() |
RomanNumeral |
public class RomanNumeral extends Number implements Comparable { private static final char[] charList = { 'M', 'D', 'C', 'L', 'X', 'V', 'I' }; private static final int[] valList = { 1000, 500, 100, 50, 10, 5, 1 }; private String strVal; private int intVal; /** * Class constructor specifying initial |
![]() |
Come generare le eccezioni |
public class PieEater { private int piesEaten; // la clausola throw indica che il metodo pu≥ lanciare una eccezione PieException public int howManyPies() throws PieException { // do some processing if( piesEaten > 100 ) { // crea una eccezione PieException e la lancia throw new PieException( "non ha mangiato tutte le torte!" ); } return piesEaten; } } |
![]() |
Come generare numeri casuali secondo la distribuzione di Poisson |
import java.util.Random; public class RandomPoissonDistribution { private Random rand; private long mean; public RandomPoissonDistribution(long mean) { this.mean = mean; rand = new Random(); } /** * Return a random number with Poisson distribution. */ public long nextLong() { // See Knuth, TAOCP, vol. 2, second print // section 3.4.1, algorithm Q on page 117 // Q1. [Calculate exponential] double p = Math.exp(-(double)mean); long N = 0; double q = 1.0; while (true) { // Q2. [Get uniform variable] double U = rand.nextDouble(); // Q3. [Multiply] q = q * U; // Q4. [Test] if (q >= p) N = N + 1; else return N; } } public static void main(String[] args) { RandomPoissonDistribution poisson = new RandomPoissonDistribution(10); for (int i = 0; i <= 10; i++) System.out.println(poisson.nextLong()); } } |
![]() |
Come realizzare conversioni di base |
#include |
![]() |
Come salvare e recuperare le impostazioni degli utenti |
#include |
![]() |
Come calcolare il determinante di una matrice |
template< class ElType > ElType EHMatrix<ElType>::Determinant() const { if( nRows() != nCols() ) throw MatException( IDR_ERMATRIXOP ); // Or some other appropriate // way to remind yourself that only a nitwit would try to // take the determinant of a nonsquare matrix. if( nRows() == 0 ) return 0; CArray<EHVector<ElType>*, EHVector<ElType>>*> Rowps; // Array of POINTERS to // vectors that are copies of the original matrix's rows. Swapping // rows that are pointers is much more efficient that swapping entire // arrays. Rowps.SetSize( nRows() ); for( int r=1; r<=Rowps.GetSize(); r++ ) // { Rowps[r-1] = new EHVector<ElType>; // NOTE: Matrix class this is from (*(Rowps[r-1])) = m_Rows[r]; // is 1 based, the array the rows are } // being copied into is 0 based ElType det=1; // Start with determinant as 1 // Now row reduce, aka Reduce Row Echelon Form #define EL(n,m) (*(Rowps[n]))[m+1] // To take care of both dereferencing and 0,1 base // discrepancy for( r=0; r<Rowps.GetSize(); r++ ) { if( EL(r,r) == 0 ) // Swap with a row that has non zero in that col { int searchr=r+1; while( searchr < Rowps.GetSize() && EL( searchr, r )==0 ) searchr++; if (searchr==Rowps.GetSize()) { det=0; // This system doesn't have a unique solution goto XDeterminant_done; } EHVector<ElType>* TempRp = Rowps[r]; Rowps[r] = Rowps[searchr]; Rowps[searchr] = TempRp; det *= -1; // Swapping rows negated determinant } det *= EL(r,r); (*(Rowps[r])) /= EL(r,r); for( int RedRow = r+1; RedRow<Rowps.GetSize(); RedRow++ ) { (*(Rowps[RedRow])) += (*(Rowps[r])) * (-1*EL(RedRow,r)); } } // matrix is now upper triangular with diagonal of all ones, so its determinant is 1 // The Row swaps and divisions it took to get to this point have determined what the // determinant of the original matrix was #undef EL XDeterminant_done: for( r=0; r<Rowps.GetSize(); r++ ) { delete Rowps[r]; // } return det; } // matrix is now upper triangular with diagonal of all ones, so its determinant is 1 // The Row swaps and divisions it took to get to this point have determined what the // determinant of the original matrix was #undef EL XDeterminant_done: for( r=0; r<Rowps.GetSize(); r++ ) { delete Rowps[r]; // } return det; } |
![]() |
Come allineari i controlli sulle form |
Sub ButtonRight(X As Control, _ Frm As Form, Offset as Integer) X.Left = Frm.ScaleWidth - _ X.Width - Offset End Sub |
Con la costante Offset Φ possibile specificare la distanza fra ogni pulsante e riutulizzare cos∞ il medesimo codice per pi∙ pulsanti. Una volta sistemati i pulsanti sulla form, Φ necessario aggiungere all'evento Form_Resize il seguente codice: |
Private Sub Form_Resize() ButtonRight Command1, Me, 0 ButtonRight Command2, Me, _ Command1.Width End Sub |
![]() |
Come spostare controlli e form |
frmCustomer.Left = frmCustomer.Left + 100 frmCustomer.Top = frmCustomer.Top + 50 |
Un metodo alternative Φ utilizzare il metodo Move, che risulta pi∙ veloce di circa il 40% rispetto al codice appena visto: |
frmCustomer.Move frmCustomer.Left + 100, frmCustomer.Top + 50 |
![]() |
Come generare l'evento clic |
cmdAdd.Value = True |
Cos∞ facendo Φ possibile attivare facilmente un comando su una form diversa rispetto a quella in cui Φ scritto il codice, tuttavia risulta pi∙ veloce chiamare direttamente la procedura relativa all'evento che ci interessa: |
Call cmdAdd_Click |
![]() |
Come installare un font speciale |
'API: Dichiarazioni Private Declare Function AddFontResource Lib "gdi32" Alias "AddFontResourceA" (ByVal lpFileName As String) As Long Private Declare Function RemoveFontResource Lib "gdi32" Alias "RemoveFontResourceA" (ByVal lpFileName As String) As Long 'CODICE Public Function LoadFont(FntFileName As String) As Boolean Dim FntRC As Long FntRC = AddFontResource(FntFileName) If FntRC = 0 Then 'no success LoadFont = False Else 'success LoadFont = True End If End Function 'FntFileName include anche il path Public Function RemoveFont(FntFileName As String) As Boolean Dim RC As Long Do RC = RemoveFontResource(FntFileName) Loop Until RC=0 End Function |
![]() |
Come allineare il testo in un pulsante |
Option Explicit Private Declare Function GetWindowLong Lib _ "user32" Alias "GetWindowLongA" (ByVal hWnd _ As Long, ByVal nIndex As Long) As Long Private Declare Function SetWindowLong Lib _ "user32" Alias "SetWindowLongA" (ByVal hWnd _ As Long, ByVal nIndex As Long, ByVal _ dwNewLong As Long) As Long Private Const BS_LEFT As Long = &H100 Private Const BS_RIGHT As Long = &H200 Private Const BS_CENTER As Long = &H300 Private Const BS_TOP As Long = &H400 Private Const BS_BOTTOM As Long = &H800 Private Const BS_VCENTER As Long = &HC00 Private Const BS_ALLSTYLES = BS_LEFT Or BS_RIGHT _ Or BS_CENTER Or BS_TOP Or BS_BOTTOM Or _ BS_VCENTER Private Const GWL_STYLE& = (-16) Public Enum bsHorizontalAlignments bsLeft = BS_LEFT bsRight = BS_RIGHT bsCenter = BS_CENTER End Enum Public Enum bsVerticalAlignments bsTop = BS_TOP bsBottom = BS_BOTTOM bsVCenter = BS_VCENTER End Enum Public Sub AlignButtonText(cmd As CommandButton, _ Optional ByVal HStyle As _ bsHorizontalAlignments = bsCenter, _ Optional ByVal VStyle As _ bsVerticalAlignments = bsVCenter) Dim oldStyle As Long ' get current style oldStyle = GetWindowLong(cmd.hWnd, GWL_STYLE) ' clear existing alignment setting(s) oldStyle = oldStyle And (Not BS_ALLSTYLES) ' set new style and refresh button Call SetWindowLong(cmd.hWnd, GWL_STYLE, _ oldStyle Or HStyle Or VStyle) cmd.Refresh End Sub |
![]() |
Come valutare le espressioni |
eval(codestring) |
L'argomento Φ un oggetto String che contiene codice JavaScript. La Stringa Φ passata al parser JavaScript, e viene dunque eseguita come normale codice. Se ci sono istruzioni JavaScript, sono dunque eseguite regolarmente mentre, se Φ presente una espressione, la stessa viene valutata ed il valore risultante Φ ritornato come valore della funzione. Ecco un esempio: |
eval("primo=1973; secondo=29; document.write(primo + secondo);"); |
Codice che darα come risultato: |
2002 |
E' da notare che l'argomento codestring Φ opzionale ma, se non si indica alcun argomento, eval restituirα "undefined". |
![]() |
Come leggere un numero in una stringa |
La funzione parseInt si occupa di cercare il primo intero presente in una stringa. Il numero di argomenti accettati da parseInt Φ pari a due: il primo Φ la stringa in cui cercare il numero, mentre il secondo parametro indica la base dell'intero Φ pu≥ andare da 2 a 36 (ad esempio 16 per un esadecimale). Il secondo parametro Φ opzionale e, nel caso in cui non viene fornito, il parser cercherα di individuare da solo la base del numero presente nella stringa: se la stringa comincia con una cifra compresa fra 1 e 9, verrα considerata la base 10; se la stringa inizia con 0x oppure 0X, il numero verrα considerato esadecimale; se la stringa comincia con uno zero, il numero sarα analizzato in base otto. Una volta scelta la base, il parser analizza la stringa da sinistra verso destra fino ad incontrare il primo carattere non corrispondente ad alcuna cifra coerente con la base. A partire da questa posizione la restante parte della stringa viene ignorata e parseInt restituisce il valore trovato come intero (attenzione: non come stringa!). Questa funzione intercetta solo il primo intero presente in una stringa e non considera eventuali numeri decimali: tutti i caratteri posizionati dopo un punto o una virgola sono dunque ignorati. Se il primo carattere non Φ uno spazio bianco nΦ un carattere numerico, la funzione restituisce "NaN": Not a Number. |
document.write(" |
Questo l'output: |
50 50 32 71 37 NaN |
La funzione pu≥ essere utilmente utilizzata per effettuare delle conversioni di base: |
document.write(parseInt("110", 2)) |
Output: |
6 |
La corrispettiva funzione per i numeri in virgola mobile Φ parseFloat. La funzione determina se il primo carattere della stringa ricevuta come argomento Φ un numero, in caso affermativo processa la stringa fino a che intercetta la fine del numero. Anche in questo caso il valore Φ ritornato come numero e non come stringa. |
document.write(" |
Ecco il risultato: |
50 50.12345 32.00000000 71.348 37 NaN |
![]() |
Come verificare che un drive sia pronto |
La funzione riportata accetta come parametro la lettera identificativa del drive di cui vogliamo verificare lo stato. La funzione ritorna poi un valore booleano: true se il drive Φ pronto, false se il disco non Φ presente nel drive. |
function DiskInDrive(Drive: Char): Boolean; var ErrorMode: word; begin { make it upper case } if Drive in ['a'..'z'] then Dec(Drive, $20); { make sure it's a letter } if not (Drive in ['A'..'Z']) then raise EConvertError.Create('Not a valid drive ID'); { turn off critical errors } ErrorMode := SetErrorMode(SEM_FailCriticalErrors); try { drive 1 = a, 2 = b, 3 = c, etc. } if DiskSize(Ord(Drive) - $40) = -1 then Result := False else Result := True; finally { restore old error mode } SetErrorMode(ErrorMode); end; end; |
![]() |
Come mostrare la dialog con le proprietα di un file |
La procedura che presentiamo consente di richiamare la finestra di proprietα dei file. Per poterla utilizzare correttamente Φ necessario aggiungere ShellApi alla clausola USES |
procedure PropertiesDialog(FileName:String); var sei: TShellExecuteInfo; begin FillChar(sei, SizeOf(sei), 0); sei.cbSize := SizeOf(sei); sei.lpFile := PChar(filename); sei.lpVerb := 'properties'; sei.fMask := SEE_MASK_INVOKEIDLIST; ShellExecuteEx(@sei); end; |
Ed ecco come richiamare la procedura |
procedure TForm1.Button1Click(Sender: TObject); begin if Opendialog1.Execute then PropertiesDialog(Opendialog1.FileName); end; |
![]() |
Come creare un file temporaneo |
Se si ha bisogno di un file temporaneo, il primo problema Φ trovare un nome univoco per salvarlo e riferirlo univocamente. La funzione che presentiamo si limita proprio a questo, ritornando un nome di file univoco da utilizzare successivamente per la creazione di un file temporaneo. |
function GetTempFile(const Extension: string): string; var Buffer: array[0..MAX_PATH] OF Char; aFile : string; begin GetTempPath(Sizeof(Buffer)-1,Buffer); GetTempFileName(Buffer,'~',0,Buffer); result := StrPas(Buffer); end; procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage(GetTempFile('.tmp')); // Il file temporaneo sarα del tipo C:\WINDOWS\TEMP\~61D5.TMP end; |
![]() |
Come rendere una form trasparente |
Se si vuole dare uno stile inconsueto ed accattivante alle proprie applicazioni, una possibilitα Φ offerta da questo tip. Con il form completamente trasparente, le nostre applicazioni non correranno il rischio di passare inosservate! |
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure dovisible; procedure doinvisible; end; var Form1: TForm1; FullRgn,ClientRgn,CtlRgn:HWND; implementation {$R *.DFM} procedure TForm1.DoInvisible; var AControl : TControl; A, Margin, X, Y, CtlX, CtlY : Integer; begin Margin := ( Width - ClientWidth ) div 2; FullRgn := CreateRectRgn(0, 0, Width, Height); X := Margin; Y := Height - ClientHeight - Margin; ClientRgn := CreateRectRgn( X, Y, X + ClientWidth, Y + ClientHeight ); CombineRgn( FullRgn, FullRgn, ClientRgn, RGN_DIFF ); for A := 0 to ControlCount - 1 do begin AControl := Controls[A]; if ( AControl is TWinControl ) or ( AControl is TGraphicControl ) then with AControl do begin if Visible then begin CtlX := X + Left; CtlY := Y + Top; CtlRgn := CreateRectRgn( CtlX, CtlY, CtlX + Width, CtlY + Height ); CombineRgn( FullRgn, FullRgn, CtlRgn, RGN_OR ); end; end; end; SetWindowRgn(Handle, FullRgn, TRUE); end; procedure TForm1.DoVisible; begin FullRgn := CreateRectRgn(0, 0, Width, Height); CombineRgn(FullRgn, FullRgn, FullRgn, RGN_COPY); SetWindowRgn(Handle, FullRgn, TRUE); end; procedure TForm1.Button1Click(Sender: TObject); begin DoVisible; end; procedure TForm1.Button2Click(Sender: TObject); begin DoInvisible; end; end. |
![]() |
Come impedire lo spostamento di una finestra |
Con il codice qui presentato Φ possibile fissare la posizione di una finestra sullo schermo. Qualsiasi tentativo dell'utente di spostarla fallirα miseramenteà Nella sezione Private dichiaramo la procedura: |
procedure WMWindowPosChanging(var Message: TWMWindowPosChanging); message WM_WINDOWPOSCHANGING; Mentre questo sarα il codice della procedura sarα: procedure TForm1.WMWindowPosChanging(var Message: TWMWindowPosChanging); begin with Message.WindowPos^ do Flags:= Flags OR SWP_NOMOVE; end; |