How do I add read more link in Whatsapp message ?


I received a message from a friend about my profile picture on whatsapp which has only two lines and a 'read more' link just after two lines and when i look behind that message there was  just lots of space..

that appears that adding too much space can do the trick..
i tested and its working...
i will add this post with sample text and data as soon as i get some time ...



How to convert CMYK to RGB and RGB to CMYK in Java

RGB (Red Green Blue) are the colors i guess we all know most of the web developers works with rgb and hex colors.

CMYK (Cyan, Magenta, Yellow, Black) CMYK are the colors used in printing.

Most of the Graphic softwares such as Photoshop, gimp etc are actually able to work with both models.

The point of this post is simply tell you the process of transforming RGB to CMYK or reverse.

Let's start with RGB to CMYK.

RGB to CMYK conversion formula

The R,G,B values are divided by 255 to change the range from 0..255 to 0..1

R1 = R/255
G1 = G/255
B1 = B/255

The black key (K) color is calculated from the red (R1,G1,B1)
K = 1-max(R1, G1, B1)

The cyan color (C) is calculated from the red (R1) and black (K) colors:
C = (1-R1-K) / (1-K)

The magenta color (M) is calculated from the green (G1) and black (K) colors:
M = (1-G1-K) / (1-K)

The yellow color (Y) is calculated from the blue (B1) and black (K) colors:
Y = (1-B1-K) / (1-K)

lets implement this into code
public CMYK toCMYK() {

     double c, m, y, k;
     double r = 2, g = 25, b = 255;
     double r1 =  r / 255, g1 = g / 255, b1 = b / 255;
     
     k = 1 - max(r1, g1, b1);
     c = (1 - r1 - k) / (1 - k);
     m = (1 - g1 - k) / (1 - k);
     y = (1 - b1 - k) / (1 - k);
     return new CMYK(c, m, y, k);

}


so now lets look into CMYK to RGB

CMYK to RGB conversion formula

The R,G,B values are given in the range of 0 - 255.

The red (R) color is calculated from the cyan (C) and black (K)
colors:
R = 255 × (1-C) × (1-K)

The green color (G) is calculated from the magenta (M) and black
(K) colors:
G = 255 × (1-M) × (1-K)

The blue color (B) is calculated from the yellow (Y) and black
(K) colors:
B = 255 × (1-Y) × (1-K)

And here is the code.

public RGB toRGB() {

      double r = 255 * (1 - c) * (1 - k);
      double g = 255 * (1 - m) * (1 - k);
      double b = 255 * (1 - y) * (1 - k);

      return new RGB(r, g, b);
}


All right, so now hopefully we understand the conversion, let's see everything in action

Full code

package chap09;

/**
 *
 * @author Aamir khan @hacktw
 * @version 1.2
 *
 */
public class RGBtoCMYK {

    public static void main(String argu[]) {
        new RGBtoCMYK().run();
    }//main end

    private void run() {
        RGB rgb = new RGB(255, 0, 255);
        CMYK cmyk = new CMYK(0, 1, 0, 0);

        System.out.println(rgb.toCMYK());
        System.out.println(cmyk.toRGB());
    }

    class CMYK {

        double c, m, y, k;

        public CMYK(double c, double m, double y, double k) {
            if (c > 1 || m > 1 || y > 1 || k > 1) {
                System.err.print("make sure CMYK values are in range 0-1");
                System.exit(0);
            }

            this.c = c;
            this.m = m;
            this.y = y;
            this.k = k;
        }

        public RGB toRGB() {

            /**
             * <b>CMYK to RGB conversion formula</b>
             *
             * <p>
             * The R,G,B values are given in the range of 0..255.
             *
             * The red (R) color is calculated from the cyan (C) and black (K)
             * colors:
             *
             * R = 255 × (1-C) × (1-K)
             *
             * The green color (G) is calculated from the magenta (M) and black
             * (K) colors:
             *
             * G = 255 × (1-M) × (1-K)
             *
             * The blue color (B) is calculated from the yellow (Y) and black
             * (K) colors:
             *
             * B = 255 × (1-Y) × (1-K)
             * </p>
             *
             */
            double r = 255 * (1 - c) * (1 - k);
            double g = 255 * (1 - m) * (1 - k);
            double b = 255 * (1 - y) * (1 - k);

            return new RGB(r, g, b);
        }

        @Override
        public String toString() {
            //Format the Output
            java.text.DecimalFormat p = new java.text.DecimalFormat("#.###");
            return "Cyan " + p.format(c)
                    + "nMagenta " + p.format(m)
                    + "nYellow " + p.format(y)
                    + "nBlack " + p.format(k);
        }

    }

    class RGB {

        double r, g, b;

        public RGB(double r, double g, double b) {
            if (r > 255 || g > 255 || b > 255) {
                System.err.print("make sure RGB values are in range 0-255");
                System.exit(0);
            }
            this.r = r;
            this.g = g;
            this.b = b;
        }

        /** <b>RGB to CMYK conversion formula</b>
        *
        * <p>
        * The R,G,B values are divided by 255 to change the range from 0..255 to 0..1:
        *
        * R1 = R/255
        *
        * G1 = G/255
        *
        * B1 = B/255
        *
        * The black key (K) color is calculated from the red (R1,G1,B1)
        *
        * K = 1-max(R1, G1, B1)
        *
        * The cyan color (C) is calculated from the red (R1) and black (K) colors:
        *
        * C = (1-R1-K) / (1-K)
        *
        * The magenta color (M) is calculated from the green (G1) and black (K) colors:
        *
        * M = (1-G1-K) / (1-K)
        *
        * The yellow color (Y) is calculated from the blue (B1) and black (K) colors:
        *
        * Y = (1-B1-K) / (1-K)
        * </p>
        **/
        public CMYK toCMYK() {

            double c, m, y, k;

            double r1 = r / 255, g1 = g / 255, b1 = b / 255;

            /*the black key Color (k) is Calculated from r1,g1,b1
                so k = 1- max(r1,g1,b1)
             */
            k = 1 - max(r1, g1, b1);
            //The Cyan
            c = (1 - r1 - k) / (1 - k);
            //The Magento
            m = (1 - g1 - k) / (1 - k);
            //The Yellow
            y = (1 - b1 - k) / (1 - k);

            return new CMYK(c, m, y, k);

        }

        public double max(double a, double b, double c) {

            double max = a;
            if (b > max) {
                max = b;
            }
            if (c > max) {
                max = c;
            }
            return max;

        }//max end

        @Override
        public String toString() {
            return String.format("rgb(%1.0f, %1.0f, %1.0f)", r, g, b);
        }

    }

}


output:
Cyan 0
Magenta 1
Yellow 0
Black 0
rgb(255, 0, 255)

How to use Java to Print Numbers in Hindi

An internationalized program can display information differently throughout the world.

For example, the program will display different messages in India , China, and New York. If the localization process has been fine-tuned,

in Java A Locale object is an identifier for a particular combination of language and region.When creating a Locale object, you usually specify a language code and a country code. A third parameter, the variant, is optional.


So, if you got my point than this is Simple to Print Different messages in Different Languages in java.

An Example Will be Enough to take you Down there...


import java.text.NumberFormat;
import java.util.Locale;

/**
 *
 * @author Aamir Khan
 */
public class Hindi_123 {

    public static void main(String[] args) {
        //set the Locale to Hindi,India
        Locale myloc = new Locale("hi", "in");
        //pass the instace to NumberFormat to Handle the Rest
        NumberFormat nf = NumberFormat.getInstance(myloc);
        for (int i = 0; i <= 100; i++) {

            //print the Numbers
            System.out.println(nf.format(i));
        }

    }

}

How to join a list with prefix in python

Sometimes you may need to turn your list into a string and the most pythonic way of doing is by using join.
But when it comes to adding a prefix with the list its does not work properly lets give a try.

>>> animals = ['Cat', 'Dog', 'Elephant']
>>> "The".join(animals)
    'CatTheDogTheElephant'


What that's not prefix at all but that can be fixed by adding just "\n" with prefix.
Lets try.

>>> print("\nThe ".join(animals))
Cat
The Dog
The Elephant

Ok, that seems to work but if we look at the output we are missing the prefix with first output.
so how to fix that?

Well a simple way is to map all the input with prefix and convert that into string.
Lets Try.

>>> print("\n".join(map(lambda x: "The " + x, animals)))
The Cat
The Dog
The Elephant


and perfect it works.

some people prefer to use list comprehension over map and filter, so we can

>>> print("\n".join(["The " + x for x in animals]))
The Cat
The Dog
The Elephant


Note : you will have to convert list into string if the list is having data other then string

For Example:
>>> print("\n".join(map(lambda x: "prefix" + str(x), some_list)))

IMEI Validation app in JavaFX

IMEI (International Mobile Station Equipment Identity) is a unique number to identify GSM, UMTS, LTE and iDEN mobile phones.

The IMEI is basically used to identify a device. It is usually found printed inside the battery or you can dial *#06# to see your device IMEI.

The Digits are calculated with an algorithm called "Luhn algorithm" also known as "mod 10"  created by scientist Hans Peter Luhn.

It is also used to validate a variety of identification numbers, such as credit card numbers, National Provider Identifier numbers in the US etc. Which means you can use the same app to validate variety of things those using "mod 10" .

How it works ?

  1. Take the digit from the rightmost and double the value of every other digit.
  2. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the product (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or alternatively subtract 9 from the product (e.g., 16: 16 - 9 = 7, 18: 18 - 9 = 9) or in simple wordsif the result in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.
  3. Take the sum of all the digits.
  4. if the sum is divided by 10 then its valid else its not.

so enough theory lets jump into coding.
below is the code implemented with mod 10.




package chap09;

/**
 *
 * @author Aamir khan
 */
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.geometry.Pos;
import javafx.scene.layout.VBox;
import java.util.stream.IntStream;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.application.Application;
import javafx.scene.control.TextField;

/**
 *
 *
 * @author Aamir khan
 */
public class IMEIValidaotrApp extends Application {

    //components
    IMEIField field;
    Label status;
    VBox root;
    Button checkBtn;

    //this is a bad idea use a separate css file indeed
    private final String INVALID_LABEL_CSS = "-fx-text-fill:white; "
            + "-fx-background-color: #E26868;"
            + "-fx-padding:5px;"
            + "-fx-border-width:1; -fx-border-color:#B63E5A;"
            + "-fx-font-size: 9pt;";

    private final String VALID_LABEL_CSS = "-fx-text-fill:white; "
            + "-fx-background-color: #20A286;"
            + "-fx-padding:5px;"
            + "-fx-border-width:1; -fx-border-color:#19B99A;"
            + "-fx-font-size: 9pt;";

    private final String CHECK_BUTTON_CSS = "-fx-background-color:#c3c4c4,"
            + "linear-gradient(#d6d6d6 50%, white 100%),"
            + "radial-gradient(center 50% -40%, radius 200%, #e6e6e6 45%, rgba(230,230,230,0) 50%);"
            + "-fx-background-radius: 30; -fx-background-insets: 0,1,1;"
            + "-fx-text-fill: black;"
            + "-fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 3, 0.0 , 0 , 1 );";

    @Override
    public void init() {

        field = new IMEIField();
        field.setText("490154203237518");//for the Demo

        status = new Label();

        checkBtn = new Button("Check");
        checkBtn.setDefaultButton(true);
        //disable the button if the length is less than 15
        checkBtn.disableProperty().bind(field.textProperty().length().lessThan(15));
        checkBtn.setStyle(CHECK_BUTTON_CSS);
    }

    @Override
    public void start(Stage window) throws Exception {

        root = new VBox(status, field, checkBtn);
        root.setAlignment(Pos.CENTER);
        root.setSpacing(5.0);
        root.setStyle("-fx-padding: 10; -fx-font-size: 18;");

        window.setScene(new Scene(root, 300, 200));
        window.setTitle("IMEI Checker");
        window.setResizable(false);
        window.show();

        checkBtn.setOnAction(e -> validateIMEI());

    }

    /**
     * implementation of
     * <a href = "https://en.wikipedia.org/wiki/Luhn_algorithm Luhn algorithm">Luhn
     * algorithm</a>
     * is also known as “Modulus 10” algorithm.<br>
     * It is a simple checksum formula used to validate a variety of
     * identification numbers,<br>
     * such as credit card numbers, IMEI numbers, National Provider Identifier
     * numbers in US and Canadian Social Insurance Numbers.<br>
     * It was created by IBM scientist Hans Peter Luhn.<br>
     * Verification is done by validating check digit.<br><br>
     *
     * <p>
     * simply Double the value of every second digit from the right end (first
     * right will be check digit number). Add the individual digits comprising
     * both the products from step (1) and unaffected digits in the original
     * number. If the total modulo 10 is equal to 0, then the number is valid,
     * else it is not valid. an example of IMEI no. 490154203237518</p>
     */
    private void validateIMEI() {

        final int[] numbers = field.getText().chars().map(this::ConvertASCIIToNumer).toArray();
        boolean isValid = IntStream.range(0, numbers.length)
                .map(i -> (((i % 2) ^ (numbers.length % 2)) == 0)
                        ? ((2 * numbers[i]) / 10 + (2 * numbers[i]) % 10)
                        : numbers[i])
                .sum() % 10 == 0;

        if (isValid) {
            status.setStyle(VALID_LABEL_CSS);
            status.setText("VALID");
        } else {
            status.setText("INVALID");
            status.setStyle(INVALID_LABEL_CSS);
        }
    }

    /**
     * Returns the numeric value of the ASCII
     */
    private int ConvertASCIIToNumer(int value) {
        return Character.digit(value, 10);
    }

    /**
     * a specific class for Holding
     * <a href =
     * "https://en.wikipedia.org/wiki/International_Mobile_Station_Equipment_Identity">
     * IMEI Numbers
     * </a>
     */
    class IMEIField extends TextField {

        private final int LIMIT = 15;//A Valid IMEI Number has 15 digits

        @Override
        public void replaceText(int start, int end, String text) {
            if (validate(text)) {
                super.replaceText(start, end, text);
                onLengthListener();
            }
        }

        @Override
        public void replaceSelection(String text) {
            if (validate(text)) {
                super.replaceSelection(text);
                onLengthListener();
            }
        }

        private void onLengthListener() {
            //Stop if user type more than LIMIT
            textProperty().
                    addListener((observable, oldValue, newValue) -> {
                        if (newValue.length() > LIMIT) {
                            setText(oldValue);
                        }
                    });

        }

        /**
         * Validate input against the {@link String} and make sure input is
         * Number only
         *
         * @return true if the value is a Numeric Value <b>0-9</b>
         */
        private boolean validate(String text) {

            //furtuhre check can be done for "Empty input" or for "White Space"
            //return (" ".equals(text) || "".equals(text) ||text.matches("[0-9]"));
            return ("".equals(text) || text.matches("[0-9]"));
        }

    }

    //Mr. Main
    public static void main(String[] args) {
        launch(args);//Entry point for the FX Thread

    }

}

Lambda, Stream, Method Reference, and Multithreading All in one simple program

This code sums up Lambda, Stream, Method Reference and Multithreading all in one.


import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.IntPredicate;

/**
 *
 * @author Aamir khan
 */
public class Count {

    private String userinpt = "";
    private final List<runnable> tasks;

    public static void main(String[] args) {
        Count c = new Count();
        c.takeInput();
        c.start();
    }

    /**
    * init the list of tasks
    **/
    Count() {
    //Lambda in action
        tasks = Arrays.asList(
                () -> countVowels(),
                () -> countCons(),
                () -> countDigits(),
                () -> countWhiteSpace()
        );

    }

    /**
     * take user input used by
     * {@link #count(java.util.function.IntPredicate)};
     *
     */
    private void takeInput() {

        System.out.println("Enter your Text");
        userinpt = new Scanner(System.in).useDelimiter("\\z").next();

    }

    /***
    * submit the task to Thread pool and execute them.
    */
    private void start() {
    //Multithreading in action
        ExecutorService thread = Executors.newFixedThreadPool(tasks.size());
        tasks.forEach(thread::submit);
        thread.shutdown();
    }

    private void countVowels() {
    //Method Reference in action
        long numberOfVowels = count(this::isVowel);
        print("Total number of Vowels: " + numberOfVowels);

    }

    private void countWhiteSpace() {
        long numberOfWhiteSpaces = count(Character::isWhitespace);
        print("Total number of Spaces: " + numberOfWhiteSpaces);
    }

    private void countDigits() {
        long numberOfDigits = count(Character::isDigit);
        print("Total number of Digits: " + numberOfDigits);

    }

    private void countCons() {
        long numberOfCons = count(e -> Character.isLetter(e) && !isVowel(e));
        print("Total number of Consonants: " + numberOfCons);

    }

    /**
    * filter with given Predicate and count the filtered result
    **/
    private long count(IntPredicate filter) {
        // Stream in action    
        return userinpt.toLowerCase().chars().filter(filter).count();
    }
    
    
    
    //util methods
    public boolean isVowel(int codePoint) {
        //checking for lower case because the input will only be in lower case
        return (codePoint == 'a')
                || (codePoint == 'e')
                || (codePoint == 'i')
                || (codePoint == 'o')
                || (codePoint == 'u');

    }

    public void print(String s) {
        System.out.println(s);
    }
}

A simple string xoring program in Python

In cryptography, the simple XOR cipher is a type of additive cipher.
As the XOR operation is common in programming languages. It's pretty simple to implement it and it's also less expensive on computers.

The cipher is sometimes used for hiding information or used in cases where no particular security is required.

But, before we dive into code keep in mind that this cypher can easily be crack using a frequency analysis . But wait !, this is easy because most of the time they use the same key for xoring and if we simply generates random keys its actually pretty hard than to crack it.

So, below is the implementation of xoring in python 3.


#!/usr/bin/env python3

from os import urandom as keygen


def xor_str(data, key):
    return "".join(chr(ord(a) ^ b) for a, b in zip(data, key))


def run():
    # Note: string in Python 2.x is a bytestring
    msg = input("Enter your message: ")
    key = keygen(len(msg))

    xored = xor_str(msg, key)
    # this is how you can decrypt the data
    un_xored = xor_str(xored, key)

    # Verify that data
    if un_xored == msg:
        print("success")
        print("Encrypted:")
        print(xored)
    else:
        print("Error")


if __name__ == "__main__":
    run()

A Simple Encryption app in JavaFX

OK, So Here is another toy app i wrote to understand Multi-threading in JavaFX.
The main focus of this app is to understand multi-threading in JavaFX. So, Do not use it for any real world encryption,

By the way the algorithm that i used in this app was found in a python module called "this" also known as "Zen of Python".


Here is the main logic of the app. You can find full repo on Github or Download Standalone jar

/**
imports omitted for brevity  
**/

/**
 *
 * @author Aamir khan
 */

public class FXMLDocumentController implements Initializable {

    @FXML
    private TextArea input;
    @FXML
    private TextArea output;
    @FXML
    private Label counter;
    @FXML
    private Label progress;
    @FXML
    private Label progressMsg;
    @FXML
    private Button btn;
    @FXML
    private Label stopTask;

    final ImageView DONE_ICON = new ImageView(
            new Image(getClass().getResourceAsStream("sign-check.png")));

    StringBuilder demoText;

    private Map<character character> encodingMap;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        init();
        prepareMap(encodingMap);
        bindNodes();
    }

    @FXML
    private void encrypt(ActionEvent event) {
        startTask();
    }

    Service<void> task = new Service() {

        @Override
        protected Task createTask() {
            return new Task<void>() {

                long start = 0L;
                long stop = 0L;

                @Override
                protected Void call() throws Exception {
                    String inputText = input.getText();
                    final float INPUT_LEN = inputText.length();
                    StringBuilder result = new StringBuilder((int)INPUT_LEN);

                    start = System.nanoTime();

                    for (char c : inputText.toCharArray()) {
                        Character ch = encodingMap.getOrDefault(c, c);
                        result.append(ch);

                        String percent = String.format("%.2f", (result.length() / INPUT_LEN) * 100);
                        updateMessage("Processing... " + percent + "%");

                        if (isCancelled()) {
                            updateMessage("Task Was Cancelled " + percent + "% was done");
                            break;
                        }

                    }
                    stop = System.nanoTime();

                    Platform.runLater(() -&gt; {
                        output.setText(result.toString());
                    });

                    return null;
                }

                @Override
                protected void succeeded() {
                    progressMsg.setText("Done. in " + (stop - start) / 1000000000.0 + " sec");
                    progressMsg.setGraphic(DONE_ICON);
                    updateMessage("");
                }

            };
        }

    };

    boolean wasStartedBefore = false;

    /**
     * start or restart the task
     */
    private void startTask() {

        if (wasStartedBefore) {
            task.restart();
        } else {
            task.start();
            wasStartedBefore = true;
        }

    }

    @FXML
    private void cancleTask() {
        progress.setTextFill(Color.RED);
        task.cancel();
    }

    /**
     * fills the @link{Map} with chars according to the algo <strong> ((i + 13) % 26 +c)</strong>
     * 
where i represents [a-z]
     * 
where c represents the range of [a-z] and [A-Z]
     * 
* <b>Note:the algorithm was copied form the python Module called "this"</b>
     *
     * @param map
     */
    private void prepareMap(Map map) {

        System.out.println("preparing map");
        for (int c : new int[]{65, 97}) {

            for (int i = 0; i &lt; 26; i++) {

                Character key = (char) (i + c);
                Character value = (char) ((i + 13) % 26 + c);

                map.put(key, value);
            }
        }

    }//prepareMap ENDS

    //avoid re generating the text
    boolean wasTextNotGeneratedBefore = true;

    /**
     * Fill input field with some demo text
     */
    @FXML
    private void fillWithDemoText() {
        //if Text was not generated before genetate it
        if (wasTextNotGeneratedBefore) {
            generateDemoTextAndFill();
            wasTextNotGeneratedBefore = false;
        } //if text was generated before fill the input with some random text &gt; 200000 characteres
        else {
            //just fill with some random data
            input.setText(demoText.substring(0, (int) (200000 + Math.random() * 500)));
        }

    }//fillWithDemoText ends

    /**
     * * Bind the properties to keep track the state of app  
     * - keep track of input field changes and update the counter 
     * - keep track of input field if its empty disable the encrypt/decrypt
     * button 
     * - keep track of task property if a task is running disable the
     * encrypt/decrypt button till task is running
     * - keep update the progress Msg while task is running
     * - show the stop task label as the user start the task - Mor to come
     * 
     */
    private void bindNodes() {

        //keep track of input field changes and update the counter
        counter.textProperty().bind(input.textProperty().length().asString());

        //keep track of input field if its empty disable the encrypt/decrypt button
        btn.disableProperty().bind(input.textProperty().isEmpty()
                .or(task.stateProperty().isEqualTo(RUNNING))
        );
        //keep update the progress Msg while task is running
        progress.textProperty().bind(task.messageProperty());
        //show the stop task label as the user start the task
        stopTask.visibleProperty().bind(task.stateProperty().isEqualTo(RUNNING));

    }

    /**
     * initialize things
     */
    private void init() {
        encodingMap = new HashMap&lt;&gt;(52);
        stopTask.setTooltip(new Tooltip("Cancle Task"));
        //Some House keeping 
        task.setOnReady(e -&gt; {
            progressMsg.setText("");
            progressMsg.setGraphic(null);
            progress.setTextFill(Color.web("#078ffa"));
            output.clear();
        });
    }

    /**
     * Generate some Demo Text and fill the input filed with the Text
     */
    private void generateDemoTextAndFill() {

        new Thread() {//in future i am gonna use Executors

            String data = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\n"
                    + "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\n"
                    + "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\n"
                    + "consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\n"
                    + "cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\n"
                    + "proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\n";

            @Override
            public void run() {
                final int BUILDER_SIZE = (data.length() * data.length());
                demoText = new StringBuilder(BUILDER_SIZE);

                for (int i = 0; i &lt; data.length(); i++) {
                    demoText.append(data);
                }

                Platform.runLater(() -&gt; {
                    input.setText(demoText.toString());
                });

            }

        }.start();
    }

}



5 Classic Free C Books You must read



C is the language that i think we all learn at some point and we, as being a programmer know what it is and what it can.
C is most longer living Programming language on earth,  It's the language that powers most of the modern programming language such as Java, Python, C++ etc...

I don't think i must describe C as a Programming language so lets be on topic,
Here are 5 Classic Free C Books that you must read even you are not gonna type any C code in future..

1. Foundations of Computer Science - C Ed:

Al Aho and Jeff 

This book has been taken out of print by W. H. Freeman.
Actually its a C version of ground breaking book of Foundation of Computer Science by its original Authors.


2.  Functional C

Pieter Hartel, Henk Muller

C of course is not a Functional Language at all it known as its structural style of programming which is some what being criticized in the community. This book will teach you how you can apply Functional style of  programming in C.

3. Object-Oriented Programming with ANSI-C

Axel-Tobias Schreiner

No programming technique solves all problems.
No programming language produces only correct results.
No programmer should start each project from scratch.
And no Programming paradigm is perfect OOP approach is something that tries to make your life easier and some how it success. Languages like C++ or Java are the Examples of this paradigm in Action. but unlike those language C is not a Object Oriented language but it does not mean it can not be program in that universe and this is what this book teach you.


4. C Programming in Linux

David Haskins

C was actually design to work on Unix. and all *nix like operating system are driven from this. and Linux is most popular one of them. C is the natural choice on Linux and this book will teach how you can make use of that..

5. The C Library Reference Guide

Eric Huss

This book is like a Reference as the title says which take you dive into language.

A Simple Hex Color Analyzer in JavaFX


I was explaining Regular Expressions to one of my friend and suddenly he ask,
Can we extract hex colors from a CSS file using Regex?
And here I just throw this code using the same idea.

Basically the idea is pretty simple, we fetch some css file or html containing hex colors, Grab those colors and turn them into colorful Rectangles using JavaFX.

You can provide any page url that contains hex colors, For example https://www.google.com will work fine,
But its recommended to use css urls such as this , this, or this or any you want.

Clicking on the Rectangle will show the #hex value at bottom of the app, And just a side note, The below code is written in Java 8 so it "may" look alien to some of you, if yes, feel free to comment and ask what you do not understand or you can mention me on twitter @hacktw

By the way the Regex that i use is this → "#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})", of course this can be simplified but i like it that way , Simplify it on your own and feel free to share the simplified version in comments.


import java.net.URL;
import java.util.Set;
import java.util.HashSet;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.BufferedReader;
import java.net.URLConnection;
import javafx.geometry.Insets;
import javafx.concurrent.Task;
import javafx.scene.text.Font;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.event.ActionEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import java.io.InputStreamReader;
import javafx.concurrent.Service;
import javafx.scene.control.Alert;
import javafx.application.Platform;
import javafx.scene.control.Button;
import javafx.scene.layout.Priority;
import javafx.scene.layout.TilePane;
import javafx.scene.shape.Rectangle;
import javafx.application.Application;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Alert.AlertType;

/**
 *
 * @author Aamir khan
 */
public class HexAnalyzer extends Application {

    final String HEX_PATTERN_STRING = "#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})";
    final String CSS_URL = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";
    Pattern pattern;
    TilePane colorsPane;
    TextField urlField;
    TextField colorVal;
    Button fetchBtn;

    @Override
    public void init() {
        pattern = Pattern.compile(HEX_PATTERN_STRING);
        urlField = new TextField(CSS_URL);
        fetchBtn = new Button("Fetch");
        fetchBtn.setPrefWidth(80.0);
        fetchBtn.setDefaultButton(true);
        colorVal = new TextField();
        colorVal.setVisible(false);
        colorsPane = new TilePane();

    }

    @Override
    public void start(Stage window) {

        colorVal.setFont(Font.font(14.0));

        HBox bar = new HBox(urlField, fetchBtn);
        bar.setSpacing(1.5);
        bar.setPadding(new Insets(5));
        HBox.setHgrow(urlField, Priority.ALWAYS);

        ScrollPane colorPane = new ScrollPane(colorsPane);
        colorPane.setFitToWidth(true);

        VBox root = new VBox(bar, colorPane, colorVal);

        window.setTitle("#HEX Color Analyzer");
        window.setScene(new Scene(root, 610, 400));
        window.show();

        fetchBtn.setOnAction(this::runTask);
    }

    boolean wasTaskStarted = false;

    private void runTask(ActionEvent e) {
        colorsPane.getChildren().clear();
        Service task = prepareTask();
        bindProperties(task);

        if (wasTaskStarted) {
            task.restart();
        } else {
            task.start();
            wasTaskStarted = true;
        }

    }

    private Service prepareTask() {
        return new Service() {
            @Override
            protected Task createTask() {
                return new Task() {
                    @Override
                    protected Void call() throws Exception {

                        try {

                            final String css = fetchDataFrom(urlField.getText());
                            final Set hexColors = extractHexColors(css);

                            hexColors.forEach(color -> {
                                Rectangle colorBox = new Rectangle(40, 40, Color.web(color));
                                colorBox.setEffect(new DropShadow(3, Color.rgb(0, 0, 0, 0.5)));
                                colorBox.setUserData(color);

                                colorBox.setOnMouseClicked(ae -> {
                                    final String val = colorBox.getUserData().toString().toUpperCase();
                                    colorVal.setText(val);
                                });
                                Platform.runLater(() -> {
                                    colorsPane.getChildren().add(colorBox);
                                });
                            });
                        } catch (IOException ex) {
                            Alert alert = new Alert(AlertType.ERROR);
                            alert.setTitle("Error");
                            alert.setHeaderText("Oops, Something went wrong");
                            alert.setContentText(ex.toString());
                            alert.showAndWait();
                        }
                        return null;
                    }

                    //Util method to fetch data from the given url
                    private String fetchDataFrom(String url) throws IOException {
                        updateMessage("Fetching");
                        StringBuilder result = new StringBuilder();
                        URL cssurl = new URL(url);
                        URLConnection data = cssurl.openConnection();
                        try (BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                        data.getInputStream())
                        )) {
                            in.lines().forEach(result::append);
                        }
                        updateMessage("Done");

                        return result.toString();

                    }

                    //Util method to extract hex colors from the given String
                    private Set extractHexColors(final String css) {
                        updateMessage("extracting hex");
                        Set colorSet = new HashSet();
                        Matcher matcher = pattern.matcher(css);
                        while (matcher.find()) {
                            colorSet.add(matcher.group(0));
                        }
                        return colorSet;
                    }

                    @Override
                    public void succeeded() {
                        super.succeeded();
                        updateMessage("Fetch");//restrore the button
                        colorVal.setText("");//remove any previous val
                    }
                };
            }

        };
    }

    private void bindProperties(Service task) {
        fetchBtn.textProperty().bind(task.messageProperty());
        fetchBtn.disableProperty().bind(task.runningProperty());
        colorVal.visibleProperty().bind(task.runningProperty().not());
    }

    public static void main(String[] args) {
        launch(args);
    }
}


Download Project

Please note that this code may have some flaws, I have not given much time to this code its just for fun. Feel free to point out any flaw if you find out...