Thursday, December 6, 2012

How do I escape single quotes in SQL queries?

INVALID:

SELECT * FROM TableName WHERE FieldName = 'QueryString's Value'

VALID:

SELECT * FROM TableName WHERE FieldName = 'QueryString''s Value'

Java rounding off a float to two decimal places

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12
 

int n = 100; 
float f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd2dec = new Double(df2.format(f)).doubleValue();

// The value of dd2dec will be 100.00 



int n = 100.203;
float f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd2dec = new Double(df2.format(f)).doubleValue();

// The value of dd2dec will be 100.20

Wednesday, December 5, 2012

Php make zip file

$zip = new ZipArchive();
$zipFileDir = "c:/src/";
$zipFileName = "test.zip";
$zip->open($zipFileDir.$zipFileName, ZIPARCHIVE::CREATE);

/* FROM FOLDER c:/files/ */
$zipIncludedFilesDir = "c:/files/";
chdir($zipIncludedFilesDir);
$zip->addFile("a.jpg");
$zip->addFile("b.jpg");
$zip->close();
if(file_exists($zipFileDir.$zipFileName)) {
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipFileName);
    header('Content-Length: ' . filesize($zipFileDir.$zipFileName));
    readfile($zipFileDir.$zipFileName);
    unlink($zipFileDir.$zipFileName);
}
exit;

Java check if file exists on remote server using its url

import java.net.*;
import java.io.*;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(URLUtils.exists("http://www.test.com/exists.html"));
    System.out.println(URLUtils.exists("http://www.test.com/no_exists.html"));
    /*
      output :
        true
        false
    */    
  }

  public static boolean exists(String URLName){
    try {
      HttpURLConnection.setFollowRedirects(false);
      // note : you may also need
      //        HttpURLConnection.setInstanceFollowRedirects(false)
      HttpURLConnection con =
         (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
       e.printStackTrace();
       return false;
    }
  }
}
 
 
The following is doing the same thing but this time we identify ourself to a proxy.
See also this HowTo.
 
import java.net.*;
import java.io.*;
import java.util.Properties;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(exists("http://www.your_server.com"));
    System.out.println(exists("http://www.yahoo.com"));
  }


  public static boolean exists(String URLName){
    try {
      Properties systemSettings = System.getProperties();
      systemSettings.put("proxySet", "true");
      systemSettings.put("http.proxyHost","proxy.mycompany.local") ;
      systemSettings.put("http.proxyPort", "80") ;

      URL u = new URL(URLName);
      HttpURLConnection con = (HttpURLConnection) u.openConnection();
      //
      // it's not the greatest idea to use a sun.misc.* class
      // Sun strongly advises not to use them since they can 
      // change or go away in a future release so beware.
      //
      sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
      String encodedUserPwd =
         encoder.encode("domain\\username:password".getBytes());
      con.setRequestProperty
         ("Proxy-Authorization", "Basic " + encodedUserPwd);
      con.setRequestMethod("HEAD");
      System.out.println
         (con.getResponseCode() + " : " + con.getResponseMessage());
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
}  

http://www.rgagnon.com/javadetails/java-0059.html

Run Multiple Java Thread

bool isFinished = false;
final ProgressDialogue dialogue = new ProgressDialogue("Loading...");
final Thread progressThread = new Thread() {
    public void run() {
        dialogue.setVisible(true);
    }
};
final Thread progressEvent = new Thread() {
    public synchronized void run() {
        /* DO SOME WORK */
        isFinished = true;
    }
};
 final Runnable doFinished = new Runnable() {
     public void run() { saveBackupFile(); }
};
final Thread progressMonitor = new Thread() {
    public void run() {
        while (true) {
            try {
                /* SLEEP SOME TIME 1000 ms */
                Thread.sleep(1000);
            } catch (Exception ex) {

            }
            /* WAIT FOR WORK FINISHED */
            if (isFinished) {
                /* FINISH ALL */
                Thread.currentThread().interrupt();
                break;
            }
        }
         /* CALL DO FINISH METHOD WHEN THIS PROCESS REACH TO END */
         SwingUtilities.invokeLater(doFinished);
    }
};
progressThread.start();
progressEvent.start();
progressMonitor.start();

Tuesday, December 4, 2012

Execute shell commands in PHP

/**
Method to execute a command in the terminal
Uses :

1. system
2. passthru
3. exec
4. shell_exec

 */
function terminal($command)
{
    //system
    if (function_exists('system')) {
        ob_start();
        system($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } //passthru
    else if (function_exists('passthru')) {
        ob_start();
        passthru($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } //exec
    else if (function_exists('exec')) {
        exec($command, $output, $return_var);
        $output = implode("\n", $output);
    } //shell_exec
    else if (function_exists('shell_exec')) {
        $output = shell_exec($command);
    } else {
        $output = 'Command execution not possible on this system';
        $return_var = 1;
    }

    return array('output' => $output, 'status' => $return_var);
}

Use as this way:
$o = terminal('ls');
print_r($o);

http://www.binarytides.com/execute-shell-commands-php/

How to know that a string starts/ends with a specific string in jQuery

One option is to use regular expressions:
if (str.match("^Hello")) {
   // ...
}

if (str.match("World$")) {
   // ...
}