Logika Standar

Wednesday, 9 March 2016

Face Recognition

Membuat aplikasi face Recognition,

import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;

 class ImageFileViewer extends Frame implements WindowListener, ActionListener, MouseListener {

    // control buttons

    Button ExitButton;
    ImageCanvas canvas;

    public ImageFileViewer() {

    // constructor--initialize frame

    super("PPM/JPG File Viewer (Click on canvas to load image)");
    setup();
    }

    // initialize frame contents (buttons, etc.)

    public void setup() {

    Panel CanvasPanel;   // panel for drawing canvas
    Panel ButtonPanel;   // main button panel

    setSize(500,400);

    setLayout(new BorderLayout());

    this.setBackground(Color.gray);
    this.setForeground(Color.black);

    // initialize buttons, make frame responsible for actions

    ExitButton = new Button("Exit");
    ExitButton.addActionListener(this);

    // initialize canvas

    canvas = new ImageCanvas();
    canvas.addMouseListener(this);
    canvas.setSize(400, 300);
    canvas.setBackground(Color.black);
    canvas.setForeground(Color.white);

    ButtonPanel = new Panel();

    // buttons will be centered

    ButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

    // add buttons to button panel

    ButtonPanel.add(ExitButton);

    // add canvas to canvas panel centered

    CanvasPanel = new Panel();
    CanvasPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    CanvasPanel.add(canvas);

    // put main panels into the frame

    add("North", new Label(""));
    add("South", ButtonPanel);
    add("Center", CanvasPanel);

    // frame is hidden until you show it

    setVisible(true);

    // care about window events

    addWindowListener(this);
    }

    // under the new event handling model, you have to "implement" all
    // of these window operations if you're interested in any of them.
    // We only care about window close events.

    public void windowDeiconified(WindowEvent event) {
    }
    public void windowIconified(WindowEvent event) {
    }
    public void windowActivated(WindowEvent event) {
    }
    public void windowDeactivated(WindowEvent event) {
    }
    public void windowOpened(WindowEvent event) {
    }
    public void windowClosed(WindowEvent event) {
    }

    public void windowClosing(WindowEvent event) {

    // handle user closing frame

    setVisible(false); // hide frame first...
    dispose();         // release resources and destroy frame
    System.exit(0);    // exit program

    }

    public void mouseDragged(MouseEvent event) {

    }


    public void mousePressed(MouseEvent event) {

    // show file dialog for loading PPM when the user clicks...

        FileDialog f = new FileDialog(this, "Open a JPG/PPM image file",
                      FileDialog.LOAD);
        f.setFile("*.*");
        f.show();
        if (f.getFile() == null) {
        System.out.println("Image open cancelled.");
        }
        else {
              try {
                xxxFile file = null;
                String temp = (f.getDirectory()+f.getFile()).toLowerCase();

                temp = temp.substring(temp.lastIndexOf('.')+1,temp.length());
                if (temp.equals("jpg") || temp.equals("jpeg"))
                    file = new JPGFile(f.getDirectory() + f.getFile());
                else if (temp.equals("ppm") || temp.equals("pnm"))
                    file = new PPMFile(f.getDirectory() + f.getFile());

        setImage(file.getBytes(), file.getWidth(), file.getHeight());
              } catch (Exception e) { e.printStackTrace(); }
        }


    }
    public void setImage(byte[] b, int w, int h) {
      canvas.readImage(b, w, h);
    }

    public void setImage(int[] b, int w, int h) {
      canvas.readImage(b, w, h);
    }
    public void setImage(double[] b, int w, int h) {
      canvas.readImage(b, w, h);
    }
    public void mouseReleased(MouseEvent event) {
    }
    public void mouseMoved(MouseEvent event) {
    }
    public void mouseEntered(MouseEvent event) {
    }
    public void mouseExited(MouseEvent event) {
    }
    public void mouseClicked(MouseEvent event) {
    }

    public void actionPerformed(ActionEvent event) {

    // handle pushbutton events--first get source of event

    Object source = event.getSource();

    if (source == ExitButton) {
        setVisible(false); // hide frame first...
        dispose();         // release resources and destroy frame
        System.exit(0);    // exit program
    }
    }


}
 

Tuesday, 3 November 2015

Java JTextField AutoComplete

Berikut Script Java untuk JTextField AutoComplete :
import java.util.List;
import javax.swing.JTextField;
import javax.swing.text.*;

public class Java2sAutoTextField extends JTextField {
  class AutoDocument extends PlainDocument {

    public void replace(int i, int j, String s, AttributeSet attributeset)
        throws BadLocationException {
      super.remove(i, j);
      insertString(i, s, attributeset);
    }

    public void insertString(int i, String s, AttributeSet attributeset)
        throws BadLocationException {
      if (s == null || "".equals(s))
        return;
      String s1 = getText(0, i);
      String s2 = getMatch(s1 + s);
      int j = (i + s.length()) - 1;
      if (isStrict && s2 == null) {
        s2 = getMatch(s1);
        j--;
      } else if (!isStrict && s2 == null) {
        super.insertString(i, s, attributeset);
        return;
      }
      if (autoComboBox != null && s2 != null)
        autoComboBox.setSelectedValue(s2);
      super.remove(0, getLength());
      super.insertString(0, s2, attributeset);
      setSelectionStart(j + 1);
      setSelectionEnd(getLength());
    }

    public void remove(int i, int j) throws BadLocationException {
      int k = getSelectionStart();
      if (k > 0)
        k--;
      String s = getMatch(getText(0, k));
      if (!isStrict && s == null) {
        super.remove(i, j);
      } else {
        super.remove(0, getLength());
        super.insertString(0, s, null);
      }
      if (autoComboBox != null && s != null)
        autoComboBox.setSelectedValue(s);
      try {
        setSelectionStart(k);
        setSelectionEnd(getLength());
      } catch (Exception exception) {
      }
    }

  }

  public Java2sAutoTextField(List list) {
    isCaseSensitive = false;
    isStrict = true;
    autoComboBox = null;
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      init();
      return;
    }
  }

  Java2sAutoTextField(List list, Java2sAutoComboBox b) {
    isCaseSensitive = false;
    isStrict = true;
    autoComboBox = null;
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      autoComboBox = b;
      init();
      return;
    }
  }

  private void init() {
    setDocument(new AutoDocument());
    if (isStrict && dataList.size() > 0)
      setText(dataList.get(0).toString());
  }

  private String getMatch(String s) {
    for (int i = 0; i < dataList.size(); i++) {
      String s1 = dataList.get(i).toString();
      if (s1 != null) {
        if (!isCaseSensitive
            && s1.toLowerCase().startsWith(s.toLowerCase()))
          return s1;
        if (isCaseSensitive && s1.startsWith(s))
          return s1;
      }
    }

    return null;
  }

  public void replaceSelection(String s) {
    AutoDocument _lb = (AutoDocument) getDocument();
    if (_lb != null)
      try {
        int i = Math.min(getCaret().getDot(), getCaret().getMark());
        int j = Math.max(getCaret().getDot(), getCaret().getMark());
        _lb.replace(i, j - i, s, null);
      } catch (Exception exception) {
      }
  }

  public boolean isCaseSensitive() {
    return isCaseSensitive;
  }

  public void setCaseSensitive(boolean flag) {
    isCaseSensitive = flag;
  }

  public boolean isStrict() {
    return isStrict;
  }

  public void setStrict(boolean flag) {
    isStrict = flag;
  }

  public List getDataList() {
    return dataList;
  }

  public void setDataList(List list) {
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      return;
    }
  }

  private List dataList;

  private boolean isCaseSensitive;

  private boolean isStrict;

  private Java2sAutoComboBox autoComboBox;
}

import java.awt.event.ItemEvent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.plaf.basic.BasicComboBoxEditor;

public class Java2sAutoComboBox extends JComboBox {
  private class AutoTextFieldEditor extends BasicComboBoxEditor {

    private Java2sAutoTextField getAutoTextFieldEditor() {
      return (Java2sAutoTextField) editor;
    }

    AutoTextFieldEditor(java.util.List list) {
      editor = new Java2sAutoTextField(list, Java2sAutoComboBox.this);
    }
  }

  public Java2sAutoComboBox(java.util.List list) {
    isFired = false;
    autoTextFieldEditor = new AutoTextFieldEditor(list);
    setEditable(true);
    setModel(new DefaultComboBoxModel(list.toArray()) {

      protected void fireContentsChanged(Object obj, int i, int j) {
        if (!isFired)
          super.fireContentsChanged(obj, i, j);
      }

    });
    setEditor(autoTextFieldEditor);
  }

  public boolean isCaseSensitive() {
    return autoTextFieldEditor.getAutoTextFieldEditor().isCaseSensitive();
  }

  public void setCaseSensitive(boolean flag) {
    autoTextFieldEditor.getAutoTextFieldEditor().setCaseSensitive(flag);
  }

  public boolean isStrict() {
    return autoTextFieldEditor.getAutoTextFieldEditor().isStrict();
  }

  public void setStrict(boolean flag) {
    autoTextFieldEditor.getAutoTextFieldEditor().setStrict(flag);
  }

  public java.util.List getDataList() {
    return autoTextFieldEditor.getAutoTextFieldEditor().getDataList();
  }

  public void setDataList(java.util.List list) {
    autoTextFieldEditor.getAutoTextFieldEditor().setDataList(list);
    setModel(new DefaultComboBoxModel(list.toArray()));
  }

  void setSelectedValue(Object obj) {
    if (isFired) {
      return;
    } else {
      isFired = true;
      setSelectedItem(obj);
      fireItemStateChanged(new ItemEvent(this, 701, selectedItemReminder,
          1));
      isFired = false;
      return;
    }
  }

  protected void fireActionEvent() {
    if (!isFired)
      super.fireActionEvent();
  }

  private AutoTextFieldEditor autoTextFieldEditor;

  private boolean isFired;

}

Konversi File ke Byte array dan Byte Array ke File

Berikut Script java uintuk konversi File ke byte dan sebaliknya... :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileToArrayOfBytes
{
    public static void main( String[] args )
    {
        FileInputStream fileInputStream=null;
       
        File file = new File("C:\\testing.txt");
       
        byte[] bFile = new byte[(int) file.length()];
       
        try {
            //convert file into array of bytes
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bFile);
        fileInputStream.close();
          
        for (int i = 0; i < bFile.length; i++) {
               System.out.print((char)bFile[i]);
            }
           
        System.out.println("Done");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ArrayOfBytesToFile
{
    public static void main( String[] args )
    {
        FileInputStream fileInputStream=null;
       
        File file = new File("C:\\testing.txt");
       
        byte[] bFile = new byte[(int) file.length()];
       
        try {
            //convert file into array of bytes
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bFile);
        fileInputStream.close();
          
        //convert array of bytes into file
        FileOutputStream fileOuputStream =
                  new FileOutputStream("C:\\testing2.txt");
        fileOuputStream.write(bFile);
        fileOuputStream.close();
          
        System.out.println("Done");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

Sunday, 1 November 2015

Backup And Restore Mysql

Back up From the Command Line (using mysqldump)
If you have shell or telnet access to your web server, you can backup your MySQL data by using the mysqldump command. This command connects to the MySQL server and creates an SQL dump file. The dump file contains the SQL statements necessary to re-create the database. Here is the proper syntax:

$ mysqldump --opt -u [uname] -p[pass] [dbname] > [backupfile.sql]
 
For example, to backup a database named 'Tutorials' with the username 'root' and with no password to a file tut_backup.sql, you should accomplish this command:

$ mysqldump -u root -p Tutorials > tut_backup.sql
 
This command will backup the 'Tutorials' database into a file called tut_backup.sql which will contain all the SQL statements needed to re-create the database.
With mysqldump command you can specify certain tables of your database you want to backup. For example, to back up only php_tutorials and asp_tutorials tables from the 'Tutorials' database accomplish the command below. Each table name has to be separated by space.

$ mysqldump -u root -p Tutorials php_tutorials asp_tutorials > tut_backup.sql
 
Sometimes it is necessary to back up more that one database at once. In this case you can use the --database option followed by the list of databases you would like to backup. Each database name has to be separated by space.

$ mysqldump -u root -p --databases Tutorials Articles Comments > content_backup.sql 
 
If you want to back up all the databases in the server at one time you should use the --all-databases option. It tells MySQL to dump all the databases it has in storage.

$ mysqldump -u root -p --all-databases > alldb_backup.sql 
 
The mysqldump command has also some other useful options:

--add-drop-table: Tells MySQL to add a DROP TABLE statement before each CREATE TABLE in the dump.
--no-data: Dumps only the database structure, not the contents.
--add-locks: Adds the LOCK TABLES and UNLOCK TABLES statements you can see in the dump file.

The mysqldump command has advantages and disadvantages. The advantages of using mysqldump are that it is simple to use and it takes care of table locking issues for you. The disadvantage is that the command locks tables. If the size of your tables is very big mysqldump can lock out users for a long period of time.
Back up your MySQL Database with Compress

If your mysql database is very big, you might want to compress the output of mysqldump. Just use the mysql backup command below and pipe the output to gzip, then you will get the output as gzip file.

$ mysqldump -u [uname] -p[pass] [dbname] | gzip -9 > [backupfile.sql.gz]
 
If you want to extract the .gz file, use the command below:

$ gunzip [backupfile.sql.gz]
 
Restoring your MySQL Database
Above we backup the Tutorials database into tut_backup.sql file. To re-create the Tutorials database you should follow two steps:
  • Create an appropriately named database on the target machine
  • Load the file using the mysql command:
$ mysql -u [uname] -p[pass] [db_to_restore] < [backupfile.sql]
 
Have a look how you can restore your tut_backup.sql file to the Tutorials database.

$ mysql -u root -p Tutorials < tut_backup.sql
 
To restore compressed backup files you can do the following:

gunzip < [backupfile.sql.gz] | mysql -u [uname] -p[pass] [dbname]
 
If you need to restore a database that already exists, you'll need to use mysqlimport command. The syntax for mysqlimport is as follows:

mysqlimport -u [uname] -p[pass] [dbname] [backupfile.sql]

Wednesday, 21 January 2015

Cara Mengirim MMS Java Android

Lansung saja listingnya dishare bagi agan-agan yang lagi sibuk membuat aplikasi Send MMS Android.


 private void sendMMSUsingNokiaAPI()
    {
        // Magic happens here.
       
        MMMessage mm = new MMMessage();
        SetMessage(mm);
        AddContents(mm);

        MMEncoder encoder=new MMEncoder();
        encoder.setMessage(mm);

        try {
          encoder.encodeMessage();
          byte[] out = encoder.getMessage();
         
          MMSender sender = new MMSender();
          APNHelper apnHelper = new APNHelper(this);
          List<APN> results = apnHelper.getMMSApns();

          if(results.size() > 0){

              final String MMSCenterUrl = results.get(0).MMSCenterUrl;
              final String MMSProxy = results.get(0).MMSProxy;
              final int MMSPort = Integer.valueOf(results.get(0).MMSPort);
              final Boolean  isProxySet =   (MMSProxy != null) && (MMSProxy.trim().length() != 0);           
             
              sender.setMMSCURL(MMSCenterUrl);
              sender.addHeader("X-NOKIA-MMSC-Charging", "100");

              MMResponse mmResponse = sender.send(out, isProxySet, MMSProxy, MMSPort);
              Log.d(TAG, "Message sent to " + sender.getMMSCURL());
              Log.d(TAG, "Response code: " + mmResponse.getResponseCode() + " " + mmResponse.getResponseMessage());

              Enumeration keys = mmResponse.getHeadersList();
              while (keys.hasMoreElements()){
                String key = (String) keys.nextElement();
                String value = (String) mmResponse.getHeaderValue(key);
                Log.d(TAG, (key + ": " + value));
              }
             
              if(mmResponse.getResponseCode() == 200)
              {
                  // 200 Successful, disconnect and reset.
                  endMmsConnectivity();
                  mSending = false;
                  mListening = false;
              }
              else
              {
                  // kill dew :D hhaha
              }
          }   
        } catch (Exception e) {
          System.out.println(e.getMessage());
        }
    }


Jika sempat, berkunjunglah di www.kasmacell.tk 

Monday, 2 June 2014

kirim email dengan lampiran file ( attach file ) menggunakan java

Berikut merupakan contoh cara mengirim email menggunakan bahasa pemrograman java dengan melampirkan file pada saat mengirim email.

public static void kirimAttachmentEmail(Session session, String toEmail, String subject, String body){
    try{
         MimeMessage msg = new MimeMessage(session);
         msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
         msg.addHeader("format", "flowed");
         msg.addHeader("Content-Transfer-Encoding", "8bit");
          
         msg.setFrom(new InternetAddress("no_reply@journaldev.com", "NoReply-JD"));

         msg.setReplyTo(InternetAddress.parse("no_reply@journaldev.com", false));

         msg.setSubject(subject, "UTF-8");

         msg.setSentDate(new Date());

         msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
          
         // Create the message body part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText(body);
         
         // Create a multipart message for attachment
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         // Second part is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "abc.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts
         msg.setContent(multipart);

         // Send message
         Transport.send(msg);
         System.out.println("EMail Sent Successfully with attachment!!");
      }catch (MessagingException e) {
         e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
    }
}

Thursday, 25 April 2013

Melacak Android yang hilang

Mantep, ternyata ada sebuah web Android yang bisa melacak Lokasi dimana device Android berada.
Kerennya lagi, bisa menginstall aplikasi dari WEB ke Device android itu sendiri, keren kan?...
Anda tinggal mengunjungi www.androidlost.com,,, Desain Webnya cukup Userfrienly, jadi anda pasti mengerti cara menggukannya. . . cool

Monday, 1 April 2013

Membuat Jaringan Ad-hoc di windows 8

Ni juga dapet di google nih, dah lupa nama sumbernya apaan,,, langsung aja bagi yang belum tau,,,,
langkahnya :
  1. klik tombol window-ketik "CMD"-klik kanan dan pilih Run Administrator yang dibawah
  2. setelah CMD terbuka, ketik " netsh wlan set hostednetwork mode=allow ssid=NAMA JARINGAN key=PASSWORD "  tampa tanda kutip kemudian ENTER.
  3. setelah itu, kalo gak ada pesan error, ketik lagi di CMD " netsh wlan start hostednetwork ", tanpa tanda kutip.
  4. untuk stop tinggal ganti start jadi stop.
  5. jadi deh.
catatan: untuk melihat hasilnya, refreslah pada view jaringan dilaptop lain,,, okkeee... tankz . . .

Saturday, 28 April 2012

Sunday, 22 April 2012

Data Mining 7

Smoothing Data by Median Binning Technique

Data pendapatan siswa (dalam ribuan Rupiah) saat melakukan pekerjaan paruh waktu bersama pada liburan terakhir.
xx =39
 
a = 39 * 10 = 390               b = 39 * 15 = 585               c = 39 * 13 = 507
d = 39 * 12 = 468                e = 39 * 19 = 741              f = 39 * 16 = 624
g = 39 * 17 = 663               h = 39 * 18 = 702               i = 39 * 14 = 546
j = 39 * 23 = 897               k = 39 * 29 = 1131             l = 39 * 26 = 1014
m = 39 * 35 = 1365           n = 39 * 24 = 936               o = 39 * 25 = 975
p = 39 * 31 = 1209             q = 39 * 32 = 1248             r = 39 * 28 = 1092
s = 39 * 13 = 507                t = 39 * 20 = 780                u = 39 * 34 = 1326
v = 39 * 27 = 1053             w = 39 * 33 = 1287            x = 39 * 50 = 1950
y = 39 * 43 = 1677             z = 39 * 11 = 429                aa = 39 * 37 = 1443
  

 Mengurutkan data dari yang nilainya terkecil ke terbesar:

390
a
429
z
468
d
507
c
507
s
545
b
546
i
624
f
663
g
702
h
741
e
780
t
897
j
936
n
975
o
1014
l
1053
v
1092
r
1131
k
1209
p
1248
q
1287
w
1326
u
1365
m
1443
aa
1677
y
1950
x

Masukkan bilangan pada bin :

Bin 1 : 390, 429, 468, 507, 507, 545, 546, 624, 663.
Bin 2 : 702, 741, 780, 897, 936, 975, 1014, 1053, 1092.
Bin 3 : 1131, 1209, 1248, 1287, 1326, 1365, 1443, 1677, 1950.

Smoothing data dengan teknik Bin Median (nilai tengah) :
Bin 1 : 507, 507, 507, 507, 507, 507, 507, 507, 507.
Bin 2 : 936, 936, 936, 936, 936, 936, 936, 936, 936.
Bin 3 : 1326, 1326, 1326, 1326, 1326, 1326, 1326, 1326, 1326.