Wednesday, January 16, 2013

CKEDITOR instances and operations by jQuery

 var id = "CKEDITOR_100";

/* Get CKEDITOR */
var editor = CKEDITOR.instances[id];

/* Set data to CKEDITOR */
editor.setData("The Content");

/* Update CKEDITOR content */
try {
    for (var i in CKEDITOR.instances) {
        if (CKEDITOR.instances[i]) {
            CKEDITOR.instances[i].updateElement();
        }
    }
} catch (ex) {

}

/* Destroy CKEDITOR */
editor.destroy();

jsFiddle example of CKEDITOR instance update content

Thursday, January 3, 2013

Jquery call function, name taken from a string

Get function name from a string.
var formcheck = "function_name";
if (typeof window[formcheck] === 'function'){
    formok = window[formcheck]();
    e.preventDefault();
}

function function_name(){
    alert("Checked");
    return false;
}

Tuesday, January 1, 2013

PHP filter with preg_replace allow only letters and some other characters

Only receive - letters, numbers, spaces
$str = preg_replace("/[^A-Za-z0-9 ]/","",$str);
$str = preg_replace("/[^A-Za-z0-9\s]/","",$str);
$str = preg_replace("/[^A-Za-z0-9[:space:]]/","",$str);
$str = preg_replace("/([^a-z0-9A-Z[:space:]\'\"\?\!\,\.\-\:\~]+)/", "", $str]);
$str = preg_replace("/([--]+)/", "-", $str); 
 
$str = preg_replace("/<\/address>\r\n/e", "'</address>'", $str); 
When using the /e modifier in preg_replace, you have to pass a string of code to 
be evaluated as the replacement parameter, not an already-evaluated expression.
 
$str = preg_replace("/<\/address>[[:space:]]*?<address/e", "'</address><address'", $str); 
 
 
 

Round to a certain number of places using jQuery

For rounding decimals you can use the built-in JavaScript methods toFixed or toPrecision.
var num = 10;
var result = num.toFixed(2); // result will equal 10.00

num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2

Sunday, December 16, 2012

Print JEditorPane content using Java with header and footer

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javatest.pritom;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

/**
 *
 * @author User
 */
public class JavaSimpleBrowser extends JPanel {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Print Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(new JavaSimpleBrowser(), BorderLayout.CENTER);
                frame.setSize(800, 600);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
   
    private JComponent simpleBrowser;
    private final JEditorPane editorPane;
    private final JScrollPane scrollPane;
    public JavaSimpleBrowser() {
        this.setSize(new Dimension(800, 600));
        this.setPreferredSize(new Dimension(800, 600));
        JPanel pnlM = new JPanel(new BorderLayout());
        this.add(pnlM, BorderLayout.CENTER);
       
        HTMLEditorKit kit = new HTMLEditorKit();
       
        StyleSheet styleSheet = kit.getStyleSheet();
        styleSheet.addRule("body {color:#000; font-family:times; margin: 0px; }");
        styleSheet.addRule("p.line {"
                + "border-width: 3px; border-style: solid; border-color: red;"
                + "font : 10px monaco; padding: 4px; background-color: gray;"
                + "} ");
       
        editorPane = new JEditorPane();
        editorPane.setEditorKit(kit);
        Document doc = kit.createDefaultDocument();
        editorPane.setDocument(doc);
        editorPane.setContentType("text/html");
        editorPane.setText(getHtml());
        editorPane.setEditable(false);
       
        scrollPane = new JScrollPane(editorPane);
        scrollPane.setPreferredSize(new Dimension(780, 500));
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       
        pnlM.add(scrollPane, BorderLayout.CENTER);
       
        JButton button = new JButton("Print");
        pnlM.add(button, BorderLayout.NORTH);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MessageFormat header = new MessageFormat("Order Details History");               
                MessageFormat footer = new MessageFormat(" Page #{0,number,integer}");
                try {
                    editorPane.print(header, footer);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
   
    private String getHtml() {
        StringBuffer sb = new StringBuffer();
       
        sb.append("<html>");
        sb.append("<body>");
        for(int index = 0; index < 500; index++) {
            sb.append("<p class='line'>I AM IN LINE: "+index+"</p>");
        }
        sb.append("</body>");
        sb.append("</html>");
       
        return sb.toString();
    }
}

Friday, December 14, 2012

Java: Reading and writing text files

package pritom;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 14/12/12
 * Time: 9:28 AM
 * To change this template use File | Settings | File Templates.
 */
public class ReadWriteTextFileJDK7 {

    public static void main(String... aArgs) throws IOException {
        ReadWriteTextFileJDK7 text = new ReadWriteTextFileJDK7();

        //treat as a small file
        List<String> lines = text.readSmallTextFile(FILE_NAME);
        log(lines);
        lines.add("This is a line added in code.");
        text.writeSmallTextFile(lines, FILE_NAME);

        //treat as a large file - use some buffering
        text.readLargerTextFile(FILE_NAME);
        lines = Arrays.asList("Line added #1", "Line added #2");
        text.writeLargerTextFile(OUTPUT_FILE_NAME, lines);
    }

    final static String FILE_NAME = "C:/tmp/input.txt";
    final static String OUTPUT_FILE_NAME = "C:/tmp/output.txt";
    final static Charset ENCODING = StandardCharsets.UTF_8;

    //For smaller files

    List<String> readSmallTextFile(String aFileName) throws IOException {
        System.out.print("***** readSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        return Files.readAllLines(path, ENCODING);
    }

    void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        System.out.print("***** writeSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, ENCODING);
    }

    //For larger files

    void readLargerTextFile(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        Scanner scanner =  new Scanner(path, ENCODING.name());
        while (scanner.hasNextLine()){
            //process each line in some way
            log(scanner.nextLine());
        }
    }

    void readLargerTextFileAlternate(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFileAlternate *****\n");
        Path path = Paths.get(aFileName);
        BufferedReader reader = Files.newBufferedReader(path, ENCODING);
        String line = null;
        while ((line = reader.readLine()) != null) {
            //process each line in some way
            log(line);
        }
    }

    void writeLargerTextFile(String aFileName, List<String> aLines) throws IOException {
        System.out.print("***** writeLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        BufferedWriter writer = Files.newBufferedWriter(path, ENCODING);
        for(String line : aLines){
            writer.write(line);
            writer.newLine();
        }
        writer.flush();
    }

    private static void log(Object aMsg){
        System.out.println(String.valueOf(aMsg));
    }

}
http://www.javapractices.com/topic/TopicAction.do?Id=42 

Thursday, December 13, 2012

Finding real body height using jQuery

function getDocumentHeight() {
    if ($.browser.msie) {
        var $temp = $("<div>")
            .css("position", "absolute")
            .css("left", "-10000px")
            .append($("body").html());

        $("body").append($temp);
        var h = $temp.height();
        $temp.remove();
        return h;
    }
    return $("body").height();
}