text:
package org.hcjf.log;

import org.hcjf.properties.SystemProperties;
import org.hcjf.service.Service;
import org.hcjf.service.ServiceSession;
import org.hcjf.service.ServiceThread;
import org.hcjf.utils.Strings;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

/**
 * Static class that contains the functionality in order to
 * maintain and organize a log file with the same records format
 * The log behavior is affected by the following system properties
 *
hcfj_log_path: work directory of the log, by default app work directory
 *
hcfj_log_initial_queue_size: initial size of the internal queue, by default 10000;
 *
hcfj_log_file_prefix: all the log files start with this prefix, by default hcjf
 *
hcfj_log_error_file: if the property is true then log create a particular file for error group only, by default false
 *
hcfj_log_warning_file: if the property is true then log create a particular file for warning group only, by default false
 *
hcfj_log_info_file: if the property is true then log create a particular file for info group only, by default false
 *
hcfj_log_debug_file: if the property is true then log create a particular file for debug group only, by default false
 *
hcfj_log_level: min level to write file, by default "I"
 *
hcfj_log_date_format: date format to show in the log file, by default "yyyy-mm-dd hh:mm:ss"
 * @author javaito
 *
 */
public final class Log extends Service<LogPrinter> {

    private static final Log instance;

    static {
        instance = new Log();
    }

    private final List<LogPrinter> printers;
    private final Queue<LogRecord> queue;
    private final Object logMonitor;
    private Boolean shuttingDown;

    /**
     * Private constructor
     */
    private Log() {
        super(SystemProperties.get(SystemProperties.Log.SERVICE_NAME),
                SystemProperties.getInteger(SystemProperties.Log.SERVICE_PRIORITY));
        this.printers = new ArrayList<>();
        this.queue = new PriorityBlockingQueue<>(
                SystemProperties.getInteger(SystemProperties.Log.QUEUE_INITIAL_SIZE),
                (o1, o2) -> (int)(o1.getDate().getTime() - o2.getDate().getTime()));
        this.logMonitor = new Object();
        this.shuttingDown = false;
    }

    /**
     * Start the log thread.
     */
    @Override
    protected void init() {
        for (int i = 0; i < SystemProperties.getInteger(SystemProperties.Log.LOG_CONSUMERS_SIZE); i++) {
            fork(new LogRunnable());
        }
        List<String> logConsumers = SystemProperties.getList(SystemProperties.Log.CONSUMERS);
        logConsumers.forEach(S -> {
            try {
                LogPrinter printer = (LogPrinter) Class.forName(S).newInstance();
                registerConsumer(printer);
            } catch (Exception ex){
                ex.printStackTrace();
            }
        });
    }

    /**
     * Only valid with the stage is START
     * @param stage Shutdown stage.
     */
    @Override
    protected void shutdown(ShutdownStage stage) {
        switch (stage) {
            case START: {
                shuttingDown = true;
                synchronized (this.logMonitor) {
                    this.logMonitor.notifyAll();
                }
                break;
            }
        }
    }

    /**
     * This method register a printer.
     * @param consumer Printer.
     * @throws NullPointerException If the printer is null.
     */
    @Override
    public void registerConsumer(LogPrinter consumer) {
        if(consumer == null) {
            throw new NullPointerException("Log printer null");
        }

        printers.add(consumer);
    }

    @Override
    public void unregisterConsumer(LogPrinter consumer) {
        printers.remove(consumer);
    }

    /**
     * Add the record to the queue and notify the consumer thread.
     * @param record Record to add.
     */
    private UUID addRecord(LogRecord record) {
        if (instance.queue.add(record)) {
            synchronized (this.logMonitor) {
                this.logMonitor.notifyAll();
            }
        }
        return record.getId();
    }

    /**
     * Returns an array that contains al the call stack information to store into the
     * log record. The array contains the element in the next order [className, methodName, lineNumber]
     * @return Call stack information.
     */
    private static String[] getCallStackInformation() {
        StackTraceElement element = Thread.currentThread().getStackTrace()[3];
        return new String[] {element.getClassName(), element.getMethodName(), Integer.toString(element.getLineNumber())};
    }

    /**
     * This method register a printer.
     * @param printer Printer.
     * @throws NullPointerException If the printer is null.
     */
    public static void addPrinter(LogPrinter printer) {
        instance.registerConsumer(printer);
    }

    /**
     * Create a record with debug group ("[D]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID d(String tag, String message, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.DEBUG, tag, message,
                    getCallStackInformation(), params));
        }
        return result;
    }

    /**
     * Create a record with debug group ("[D]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param throwable Throwable whose message will be printed as part of record
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID d(String tag, String message, Throwable throwable, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.DEBUG, tag, message,
                    getCallStackInformation(), throwable, params));
        }
        return result;
    }

    /**
     * Create a record with info group ("[I]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID i(String tag, String message, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.INFO, tag, message,
                    getCallStackInformation(), params));
        }
        return result;
    }

    /**
     * Create a record with info group ("[IN]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID in(String tag, String message, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.INPUT, tag, message,
                    getCallStackInformation(), params));
        }
        return result;
    }

    /**
     * Create a record with info group ("[OUT]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID out(String tag, String message, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.OUTPUT, tag, message,
                    getCallStackInformation(), params));
        }
        return result;
    }

    /**
     * Create a record with warning group ("[W]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID w(String tag, String message, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.WARNING, tag, message,
                    getCallStackInformation(), params));
        }
        return result;
    }

    /**
     * Create a record with warning group ("[W]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param throwable Throwable whose message will be printed as part of record
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID w(String tag, String message, Throwable throwable, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.WARNING, tag, message,
                    getCallStackInformation(), throwable, params));
        }
        return result;
    }

    /**
     * Create a record with error group ("[E]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID e(String tag, String message, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.ERROR, tag, message,
                    getCallStackInformation(), params));
        }
        return result;
    }

    /**
     * Create a record with error group ("[E]"). All the places in the messages
     * are replaced for each param in the natural order.
     * @param tag Tag of the record
     * @param message Message to the record. This message use the syntax for class
     *                {@link java.util.Formatter}.
     * @param throwable Throwable whose message will be printed as part of record
     * @param params Parameters for the places in the message.
     * @return Returns the id assigned to the log record created, this id could be null
     * if the service does not generates any log records
     */
    public static UUID e(String tag, String message, Throwable throwable, Object... params) {
        UUID result = null;
        if(SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED) ||
                instance.printers.size() > 0) {
            result = instance.addRecord(new LogRecord(LogGroup.ERROR, tag, message,
                    getCallStackInformation(), throwable, params));
        }
        return result;
    }

    /**
     * Return the size of the log queue.
     * @return Size of the log queue.
     */
    public static Integer getLogQueueSize() {
        return instance.queue.size();
    }

    private class LogRunnable implements Runnable {

        /**
         * Wait to found a recor to print.
         */
        @Override
        public void run() {
            try {
                while(!shuttingDown) {
                    if(instance.queue.isEmpty()) {
                        synchronized (Log.this.logMonitor) {
                            Log.this.logMonitor.wait();
                        }
                    }

                    try {
                        writeRecord(instance.queue.remove());
                    } catch (Exception ex) {}
                }
            } catch (InterruptedException e) {}
        }

        /**
         * Print the record in all the printers registered and the
         * syste out printer.
         * @param record Record to print.
         */
        private void writeRecord(LogRecord record) {
            ServiceSession serviceSession = ServiceSession.getCurrentIdentity();
            serviceSession.addIdentity(record.getCurrentSession());
            try {
                if (record.getGroup().getOrder() >= SystemProperties.getInteger(SystemProperties.Log.LEVEL)) {
                    printers.forEach(printer -> printer.print(record));
                }

                if (SystemProperties.getBoolean(SystemProperties.Log.SYSTEM_OUT_ENABLED)) {
                    if (SystemProperties.getBoolean(SystemProperties.Log.JAVA_STANDARD_LOGGER_ENABLED)) {
                        if (record.getThrowable() != null) {
                            Logger.getGlobal().logp(record.getGroup().getStandardLevel(),
                                    record.getClassName(), record.getMethodName(), record.getThrowable(),
                                    () -> String.format(record.getOriginalMessage(), record.getParams()));
                        } else {
                            Logger.getGlobal().logp(record.getGroup().getStandardLevel(),
                                    record.getClassName(), record.getMethodName(),
                                    () -> String.format(record.getOriginalMessage(), record.getParams()));
                        }
                    } else {
                        System.out.println(record.toString());
                        System.out.flush();
                    }
                }
            } finally {
                serviceSession.removeIdentity();
            }
        }
    }

    /**
     * This class contains all the information to write a record in the log.
     * The instances of this class will be queued sorted chronologically waiting for
     * be write
     */
    public static final class LogRecord {

        private final UUID id;
        private final Date date;
        private final LogGroup group;
        private final String tag;
        private final String originalMessage;
        private String message;
        private final String className;
        private final String methodName;
        private final String lineNumber;
        private final SimpleDateFormat dateFormat;
        private final Object[] params;
        private final Throwable throwable;
        private final ServiceSession currentSession;

        /**
         * Constructor
         * @param group Group of the record.
         * @param tag Tag for the record.
         * @param message Message with wildcard for the parameters.
         * @param throwable The error object, could be null
         * @param params Values that will be put in the each places of the message.
         */
        private LogRecord(LogGroup group, String tag, String message, String[] callStackInformation,
                          Throwable throwable, Object... params) {
            this.id = UUID.randomUUID();
            this.date = new Date();
            this.group = group;
            this.tag = tag;
            this.dateFormat = new SimpleDateFormat(SystemProperties.get(SystemProperties.Log.DATE_FORMAT));
            this.originalMessage = message;
            this.className = callStackInformation[0];
            this.methodName = callStackInformation[1];
            this.lineNumber = callStackInformation[2];
            this.params = params;
            this.throwable = throwable;

            if(Thread.currentThread() instanceof ServiceThread) {
                this.currentSession = ServiceSession.getCurrentIdentity();
            } else {
                this.currentSession = ServiceSession.getGuestSession();
            }
        }

        /**
         * Constructor
         * @param group Group of the record.
         * @param tag Tag for the record.
         * @param message Message with wildcard for the parameters.
         * @param params Values that will be put in the each places of the message.
         */
        private LogRecord(LogGroup group, String tag, String message,
                          String[] callStackInformation, Object... params) {
            this(group, tag, message, callStackInformation, null, params);
        }

        /**
         * Returns the id of log record.
         * @return Log record id.
         */
        public UUID getId() {
            return id;
        }

        /**
         * Creates a final version of string to print the record.
         * @return Return the last version of the message.
         */
        private String createMessage() {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);

            String group = getGroup().getGroup();
            String tag = getTag();
            if(SystemProperties.getBoolean(SystemProperties.Log.TRUNCATE_TAG)) {
                int truncateSize = SystemProperties.getInteger(SystemProperties.Log.TRUNCATE_TAG_SIZE);
                if(truncateSize > tag.length()) {
                    tag = Strings.rightPad(tag, truncateSize);
                } else if(truncateSize < tag.length()) {
                    tag = tag.substring(0, truncateSize);
                }
            }

            printWriter.print(dateFormat.format(getDate()));
            printWriter.print(" [");
            printWriter.print(group);
            printWriter.print("][");
            printWriter.print(tag);
            printWriter.print("][");
            printWriter.print(getClassName());
            printWriter.print("][");
            printWriter.print(getMethodName());
            printWriter.print("][");
            printWriter.print(getLineNumber());
            printWriter.print("] ");
            printWriter.printf(originalMessage, params);

            if(throwable != null) {
                printWriter.print("\r\n");
                throwable.printStackTrace(printWriter);
            }

            printWriter.flush();
            printWriter.close();

            return stringWriter.toString();
        }

        /**
         * Returns the session instance owner of this record.
         * @return Session instance.
         */
        public ServiceSession getCurrentSession() {
            return currentSession;
        }

        /**
         * Returns the record date
         * @return Record date.
         */
        public Date getDate() {
            return date;
        }

        /**
         * Returns the record group.
         * @return Record group.
         */
        public LogGroup getGroup() {
            return group;
        }

        /**
         * Returns the log record tag.
         * @return Log record tag.
         */
        public String getTag() {
            return tag;
        }

        /**
         * Returns the last version of the message.
         * @return Record message.
         */
        public synchronized String getMessage() {
            if(message == null) {
                message = createMessage();
            }
            return message;
        }

        /**
         * Returns the original message.
         * @return Original message.
         */
        public String getOriginalMessage() {
            return originalMessage;
        }

        /**
         * Returns de format message.
         * @return Format message.
         */
        @Override
        public String toString() {
            return getMessage();
        }

        /**
         * Returns the log record params.
         * @return Log record params.
         */
        public Object[] getParams() {
            return params;
        }

        /**
         * Returns the throwable instance of the record.
         * @return Throwable instance.
         */
        public Throwable getThrowable() {
            return throwable;
        }

        /**
         * Returns the name of the class where the log is written.
         * @return Class name.
         */
        public String getClassName() {
            return className;
        }

        /**
         * Returns the name of the method where the log is written.
         * @return Method name.
         */
        public String getMethodName() {
            return methodName;
        }

        /**
         * Returns the line number where the log is written.
         * @return Line number.
         */
        public String getLineNumber() {
            return lineNumber;
        }
    }

    /**
     * This enum contains all the possible groups for the records
     */
    public static enum LogGroup {

        DEBUG("D", 0),

        INPUT("A", 1),

        OUTPUT("O", 1),

        INFO("I", 1),

        WARNING("W", 2),

        ERROR("E", 3);

        private Integer order;
        private String group;

        LogGroup(String tag, Integer order) {
            this.order = order;
            this.group = tag;
        }

        /**
         * Return the group order.
         * @return Tag order.
         */
        public Integer getOrder() {
            return order;
        }

        /**
         * Return the group label.
         * @return Tag label.
         */
        public String getGroup() {
            return group;
        }

        /**
         * Return the group instance that correspond with the parameter.
         * @param tagString String group
         * @return Tag instance founded or null if the instance is not exist.
         */
        public LogGroup valueOfByTag(String tagString) {
            LogGroup result = null;

            try {
                result = Stream.of(values()).
                        filter(r -> r.getGroup().equals(tagString)).
                        findFirst().get();
            } catch (NoSuchElementException ex) {}

            return result;
        }

        public Level getStandardLevel() {
            Level result;
            switch(this) {
                case ERROR:{
                    result = Level.SEVERE;
                    break;
                }
                case WARNING: {
                    result = Level.WARNING;
                    break;
                }
                default: {
                    result = Level.INFO;
                }
            }
            return result;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.wso2.ei</groupId>
        <artifactId>org.wso2.carbon.ei.tests.platform</artifactId>
        <version>6.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.ei.tests.platform.wso2mb</artifactId>
    <name>EI test Module - Platform - with WSO2MB</name>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
                <executions>
                    <execution>
                        <id>default-testCompile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                <inherited>false</inherited>
                <configuration>
                    <!--<argLine>-Xms512m -Xmx1024m -XX:MaxPermSize=128m -Xmx1024m -XX:PermSize=256m
                        -XX:MaxPermSize=512m -Xdebug -Xnoagent -Djava.compiler=NONE
                        -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006
                    </argLine>-->
                    <argLine>-Xms512m -Xmx1024m -XX:MaxPermSize=128m</argLine>
                    <testFailureIgnore>true</testFailureIgnore>
                    <disableXmlReport>false</disableXmlReport>
                    <skipTests>${skipPlatformTests}</skipTests>
                    <parallel>false</parallel>
                    <suiteXmlFiles>
                        <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                    <systemProperties>
                        <property>
                            <name>framework.resource.location</name>
                            <value>
                                ${basedir}/src/test/resources/
                            </value>
                        </property>
                        <property>
                            <name>server.list</name>
                            <value>
                                ESB
                            </value>
                        </property>
                        <property>
                            <name>usedefaultlisteners</name>
                            <value>false</value>
                        </property>
                        <sec.verifier.dir>${basedir}/target/security-verifier/</sec.verifier.dir>
                        <maven.test.haltafterfailure>false</maven.test.haltafterfailure>
                        <carbon.zip>
                            ${basedir}/../../../../distribution/target/wso2ei-${product.ei.version}.zip
                        </carbon.zip>
                        <instr.file>${basedir}/src/test/resources/instrumentation.txt</instr.file>
                        <filters.file>${basedir}/src/test/resources/filters.txt</filters.file>
                    </systemProperties>
                    <workingDirectory>${basedir}/target</workingDirectory>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-jacoco-dependencies</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/jacoco</outputDirectory>
                            <includeTypes>jar</includeTypes>
                            <includeArtifactIds>org.jacoco.agent</includeArtifactIds>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-jar-dependencies</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/src/test/resources/artifacts/ESB/jar
                            </outputDirectory>
                            <includeTypes>jar</includeTypes>
                            <includeArtifactIds>
                                groovy-all,jruby-complete,mysql-connector-java,activemq-core,geronimo-j2ee-management_1.1_spec,geronimo-jms_1.1_spec
                            </includeArtifactIds>
                            <excludeTransitive>true</excludeTransitive>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-secVerifier</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/security-verifier</outputDirectory>
                            <includeTypes>aar</includeTypes>
                            <includeArtifactIds>SecVerifier</includeArtifactIds>
                            <stripVersion>true</stripVersion>
                        </configuration>
                    </execution>
                    <execution>
                        <id>unpack-mar-jks</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.wso2.ei</groupId>
                                    <artifactId>wso2ei</artifactId>
                                    <version>${product.ei.version}</version>
                                    <type>zip</type>
                                    <overWrite>true</overWrite>
                                    <outputDirectory>${basedir}/target/tobeCopied/</outputDirectory>
                                    <includes>**/*.jks,**/*.mar,**/synapse_sample*.xml</includes>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>

                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-resources-jks</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/src/test/resources/keystores/products
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>
                                        ${basedir}/target/tobeCopied/wso2ei-${product.ei.version}/repository/resources/security/
                                    </directory>
                                    <includes>
                                        <include>**/*.jks</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-stratos-jks</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/src/test/resources/keystores/stratos
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>
                                        ${basedir}/target/tobeCopied/wso2ei-${product.ei.version}/repository/resources/security/
                                    </directory>
                                    <includes>
                                        <include>**/*.jks</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-sample-jks</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/src/test/resources/keystores/products
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>
                                        ${basedir}/target/tobeCopied/wso2ei-${product.ei.version}/samples/service-bus/resources/security/
                                    </directory>
                                    <includes>
                                        <include>**/*.jks</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-resources-mar</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/src/test/resources/client/modules
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>
                                        ${basedir}/target/tobeCopied/wso2ei-${product.ei.version}/repository/deployment/client/modules
                                    </directory>
                                    <includes>
                                        <include>**/*.mar</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-samples</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/src/test/resources/artifacts/ESB/samples/
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>
                                        ${basedir}/target/tobeCopied/wso2ei-${product.ei.version}/samples/service-bus/
                                    </directory>
                                    <includes>
                                        <include>**/*.xml</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.wso2.andes.wso2</groupId>
            <artifactId>andes-client</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.ei</groupId>
            <artifactId>admin-clients</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.ei</groupId>
            <artifactId>integration-test-utils</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.ei</groupId>
            <artifactId>automation-extensions</artifactId>
        </dependency>
        <!-- Jacoco Dependency-->
        <dependency>
            <groupId>org.jacoco</groupId>
            <artifactId>org.jacoco.agent</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <skipPlatformTests>true</skipPlatformTests>
    </properties>

</project>

redpajama_set_name: RedPajamaGithub


text:
package de.codesourcery.asm.controlflow;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.objectweb.asm.tree.MethodNode;

/**
 * Execution control-flow graph.
 *
 * @author tobias.gierke@code-sourcery.de
 */
public class ControlFlowGraph
{
    private final MethodNode method;

    private Set<IBlock> allNodes = null; // populated lazily
    private MethodEntry start;
    private MethodExit end;

    /**
     * Creates the graph and automatically assigns unique IDs to all nodes witout an ID.
     *
     * @param method
     * @param blocks
     *
     * @see IBlock#getId()
     */
    public ControlFlowGraph(MethodNode method, List<IBlock> blocks)
    {
        if ( method == null ) {
            throw new IllegalArgumentException("method must not be NULL.");
        }
        if ( blocks == null ) {
            throw new IllegalArgumentException("blocks must not be NULL.");
        }
        if ( blocks.isEmpty() ) {
            throw new IllegalArgumentException("Method "+method.name+" has no blocks?");
        }

        this.method = method;
        final Set<String> ids = new HashSet<>();

        for ( IBlock b : blocks )
        {
            if ( b instanceof MethodEntry )
            {
                if ( start != null ) {
                    throw new IllegalArgumentException("Input contains more than one method-entry block?");
                }
                if ( b.hasRegularPredecessor() ) {
                    throw new IllegalArgumentException("Input contains method-entry block with predecessor ?");
                }
                start = (MethodEntry) b;
            }
            else if ( b instanceof MethodExit )
            {
                if ( end != null ) {
                    throw new IllegalArgumentException("Input contains more than one method-exit block");
                }
                if ( b.hasRegularSuccessor() ) {
                    throw new IllegalArgumentException("Input contains method-exit block with successor ?");
                }
                end = (MethodExit) b;
            }

            // assign unique ID if not already done so
            if ( StringUtils.isEmpty( b.getId() ) )
            {
                String newId;
                if ( b == start ) {
                    newId = "START";
                }
                else if ( b == end )
                {
                    newId = "END";
                }
                else
                {
                    List<Integer> sorted = new ArrayList<>( b.getInstructionNums() );
                    Collections.sort( sorted );
                    newId = "\""+StringUtils.join( sorted , "_" )+"\"";
                    if ( ids.contains( newId ) )
                    {
                        int i = 1;
                        while ( ids.contains( Integer.toString( i ) ) ) {
                            i++;
                        }
                        newId = Integer.toString( i );
                    }
                }
                ids.add( newId );
                b.setId( newId );
            }
            else
            {
                if ( ids.contains( b.getId() ) ) {
                    throw new IllegalArgumentException("Input contains multiple blocks with ID '"+b.getId()+"'");
                }
                ids.add( b.getId() );
            }
        }

        if ( start == null ) {
            throw new IllegalArgumentException("Input contains no start block");
        }

        if ( end == null ) {
            throw new IllegalArgumentException("Input contains no end block");
        }
    }

    /**
     * Returns the block that contains a given instruction node.
     *
     * @param instructionNum ASM instruction node index
     * @return block or null
     */
    public IBlock getBlockForInstruction(int instructionNum)
    {
        for ( IBlock block : getAllNodes() ) {
            if ( block.containsInstructionNum( instructionNum ) ) {
                return block;
            }
        }
        return null;
    }

    /**
     * Returns all nodes of this graph.
     *
     * @return
     */
    public Set<IBlock> getAllNodes()
    {
        if ( allNodes == null ) {
            final Set<IBlock> result = new HashSet<>();
            getAllNodes( start , result );
            allNodes = result;
        }
        return allNodes;
    }

    private void getAllNodes(IBlock current , Set<IBlock> result)
    {
        if ( result.contains( current ) ) {
            return;
        }
        result.add( current );

        for ( Edge e : current.getEdges() ) {
            getAllNodes(e.src , result );
            getAllNodes(e.dst , result );
        }
    }

    /**
     * Returns the method node this graph was generated from.
     * @return
     */
    public MethodNode getMethod()
    {
        return method;
    }

    /**
     * Returns the starting (method-entry) node of this graph.
     *
     * @return
     */
    public MethodEntry getStart()
    {
        return start;
    }

    /**
     * Returns the ending (method-exit) node of this graph.
     * @return
     */
    public MethodExit getEnd()
    {
        return end;
    }
}


text:
var FileSystem = require("fs");
var Utility = require("ytility");
var DOM = require("xmldom");

var XML = {
	declaration: "<?xml version=\"1.1\" encoding=\"UTF-8\"?>",

	/**
	 * @param {String} text XML text to parse.
	 * @return {Document}
	 */
	parse: function parse(text) {
		var parser = new DOM.DOMParser();
		return parser.parseFromString(text);
	},

	/**
	 * @param {String}  file      XML file to load.
	 * @param {Boolean} [convert] Tells whether the document should be converted into JXON.
	 * @return {Document}
	 */
	load: function load(file, convert) {
		var document = String(FileSystem.readFileSync(file));
		document = XML.parse(document);

		return convert ? JXON.convert(document, true) : document;
	},

	/**
	 * @param {Node} node XML node to serialize.
	 * @return {String}
	 */
	serialize: function serialize(node) {
		var serializer = new DOM.XMLSerializer();
		return serializer.serializeToString(node);
	},

	/**
	 * @param {Node}   node       Node to evaluate the expression on.
	 * @param {String} expression X-Path expression to evaluate.
	 * @param {Object} [resolver] Simple URI resolver like {"prefix": "http://...", ...}.
	 *   Default namespace may be specified with the empty key: "".
	 * @return {Array} X-Path evaluation results.
	 */
	query: function query(node, expression, resolver) {
		var XPath = require("xpath");

		var evaluate = !!resolver && (typeof resolver == "object") ? XPath.useNamespaces(resolver) : XPath.select;

		return evaluate(expression, node);
	}
};

var JXON = {
	/**
	 * @param {Node} node Node to convert into a JXON object.
	 * @return {Object}
	 */
	convert: function convert(node, compact) {
		var transformer = this.transformers[node.nodeType];

		if(!transformer) {
			throw new Error("Unsupported node type: " + node.nodeType);
		}

		var object = transformer(node);

		return compact || !Utility.isDefined(compact) ? this.compact(object) : object;
	},

	/**
	 * @param {Object} object JXON object to compact, which should not be compacted already.
	 * @return {Object}
	 */
	compact: function compact(object) {
		for(var type in object) break;
		(type[0] !== "#") && (type = "#ELEMENT");

		return this.compactors[type](object);
	}
};

Object.defineProperty(JXON, "transformers", {
	enumerable: false,
	value: (function() {
		var transformers = {
			"#DOCUMENT": function(node) {
				return transformers["#ELEMENT"](node.documentElement);
			},

			"#ELEMENT": function(node) {
				var result = {};

				var properties = result[node.nodeName] = {};

				Utility.forEach(node.attributes, function(attribute) {
					var transformer = transformers["#ATTRIBUTE"];
					Utility.forOwn(transformer(attribute), function(value, name) {
						if(name.indexOf("@xmlns") === 0) {
							var alias = name.split(":")[1];
							if(!("#NAMESPACE" in properties)) {
								properties["#NAMESPACE"] = {};
							}
							properties["#NAMESPACE"][alias || ""] = value;
						}
						else {
							properties[name] = value;
						}
					});
				});

				var children = properties["children"] = [];

				if(node.hasChildNodes()) {
					Utility.forEach(node.childNodes, function(child) {
						var transformer = transformers[child.nodeType];
						if(transformer) {
							var childResult = transformer(child);
							if(!Utility.isEmpty(childResult)) {
								children.push(childResult);
							}
						}
					});
				}

				return result;
			},

			"#ATTRIBUTE": function(node) {
				var result = {};

				result["@" + node.name] = node.value;

				return result;
			},

			"#TEXT": function(node) {
				var result = {};

				result["#TEXT"] = node.nodeValue;

				return result;
			},

			"#CDATA": function(node) {
				var result = {};

				result["#CDATA"] = node.nodeValue;

				return result;
			},

			"#COMMENT": function(node) {
				var result = {};

				result["#COMMENT"] = node.nodeValue;

				return result;
			}
		};

		transformers[1] = transformers["#ELEMENT"];
		transformers[2] = transformers["#ATTRIBUTE"];
		transformers[3] = transformers["#TEXT"];
		transformers[4] = transformers["#CDATA"];
		transformers[8] = transformers["#COMMENT"];
		transformers[9] = transformers["#DOCUMENT"];

		return transformers;
	})()
});

Object.defineProperty(JXON, "compactors", {
	enumerable: false,
	value: (function() {
		var compactors = {
			"#ELEMENT": function(object) {
				for(var tag in object) break;
				var properties = object[tag];

				// Free the "children" key before attributes are re-written:
				var children = properties["children"];
				delete properties["children"];
				if(!Utility.isEmpty(children)) {
					properties["*"] = children;

					var index = 0;
					while(index < children.length) {
						var child = children[index];

						for(var type in child) break;
						(type[0] !== "#") && (type = "#ELEMENT");

						var result = compactors[type](child);
						if(!result) {
							children.splice(index, 1);
						}
						else {
							var previous = (index > 0) ? children[index - 1] : {};
							if(type === "#TEXT") {
								// Combine #TEXT objects:
								if(typeof(previous) === "string") {
									children[index - 1] += "\n" + child;
									children.splice(index, 1);
								}
								else {
									// Only #TEXT objects are to be replaced by `result`:
									children.splice(index, 1, result);
									index++
								}
							}
							else if((type === "#COMMENT") && (Utility.isObject(previous) && "#C" in previous)) {
								// Combine #COMMENT objects:
								previous["#C"] += "\n" + child["#C"];
								children.splice(index, 1);
							}
							else {
								index++;
							}
						}
					}

					// Take out the first child when it is alone:
					if(children.length === 1) {
						child = properties["*"] = children[0];

						// When it is a #TEXT child, extract its value:
						if(typeof(child) === "string") {
							properties["*"] = child;
						}
					}
				}

				// Rewrite attributes:
				var attributes = [];
				Utility.forOwn(properties, function(value, attribute) {
					if(attribute.charAt(0) === "@") {
						attributes.push(attribute);
						compactors["#ATTRIBUTE"](attribute, object);
					}
					else if(attribute === "#NAMESPACE") {
						delete properties["#NAMESPACE"];
						var keys = Object.keys(value);
						if(keys.length) {
							properties["#N"] = value;
							if(keys.length === 1) {
								properties["#N"] = value[keys[0]];
							}
						}
					}
				});

				// Compact even more when the object has no attribute and its unique child is a #TEXT object:
				if(Utility.isEmpty(attributes) && Utility.isString(properties["*"])) {
					object[tag] = properties["*"];
				}

				return object;
			},

			"#ATTRIBUTE": function compact(attribute, object) {
				var tag;
				for(tag in object) break;
				var properties = object[tag];

				properties[attribute.split("@")[1]] = properties[attribute];
				delete properties[attribute];

				return object;
			},

			"#TEXT": function(object) {
				return object["#TEXT"].trim() || null;
			},

			"#CDATA": function(object) {
				var text = object["#CDATA"].trim();

				if(text) {
					object["#D"] = text;
					delete object["#CDATA"];
				}

				return text ? object : null;
			},

			"#COMMENT": function(object) {
				var text = object["#COMMENT"].trim();

				if(text) {
					object["#C"] = text;
					delete object["#COMMENT"];
				}

				return text ? object : null;
			}
		};

		compactors[1] = compactors["#ELEMENT"];
		compactors[2] = compactors["#ATTRIBUTE"];
		compactors[3] = compactors["#TEXT"];
		compactors[4] = compactors["#CDATA"];
		compactors[8] = compactors["#COMMENT"];

		return compactors;
	})()
});

XML.JXON = JXON;

module.exports = XML;


text:
describe TfpMetaprogramming::Callable::Procs::Procster do
  let(:myProcster) { TfpMetaprogramming::Callable::Procs::Procster.new }
  describe 'attributes' do
    it 'has a @num' do
      expect(myProcster.instance_variables).to include(:@num)
    end
    it 'has an @info' do
      expect(myProcster.instance_variables).to include(:@info)
    end
  end
  describe 'Arity module' do
    it 'includes Callable::Procs::Arity in its ancestor chain' do
      expect(myProcster.class.ancestors).to include(TfpMetaprogramming::Callable::Procs::Arity)
    end
    describe '#arity_proc' do
      it 'returns a proc ' do
        expect(myProcster.arity_proc).to be_a_kind_of(Proc)
      end
      it 'takes two args' do
        expect(myProcster.arity_proc.arity).to be(2)
      end
    end
    describe '#arity_lambda' do
      it 'returns a lambda' do
        expect(myProcster.arity_lambda.lambda?).to be(true)
      end
      it 'takes two args' do
        expect(myProcster.arity_proc.arity).to be(2)
      end
    end
    describe 'call_for_arity' do
      context 'when called with arity_proc' do
        it 'returns an array of length 2' do
          expect(myProcster.call_for_arity(&myProcster.arity_proc)).to include(1)
        end
      end
      context 'when called with arity_lamda' do
        it 'raises an error' do
          expect { myProcster.call_for_arity(&myProcster.arity_lambda) }.to raise_error(ArgumentError)
        end
      end
    end
  end
  describe 'Returns module' do
    it 'includes Callable::Procs::Returns in its ancestor chain' do
      expect(myProcster.class.ancestors).to include(TfpMetaprogramming::Callable::Procs::Returns)
    end
    describe 'return_proc' do
      it 'returns a proc' do
        expect(myProcster.return_proc).to be_a_kind_of(Proc)
      end
      context 'when called' do
        it 'raises a LocalJumpError' do
          expect { myProcster.return_proc.call }.to raise_error(LocalJumpError)
        end
      end

    end
    describe 'return_lambda' do
      it 'returns a proc' do
        expect(myProcster.return_lambda).to be_a_kind_of(Proc)
      end
      context 'when called' do
        it 'returns 20' do
          expect(myProcster.return_lambda.call).to eq(20)

        end
      end
    end
    describe '#double_callable' do
      context 'when called bith lambda' do
        it 'returns 40' do
          expect(myProcster.double_callable(&myProcster.return_lambda)).to eq(40)
        end
      end
      context 'when called with return_proc' do
        it 'raises a LocalJumpError' do
          expect { myProcster.double_callable(&myProcster.return_proc) }.to raise_error(LocalJumpError)
        end
      end
    end
  end
  describe 'ProcMod module' do
    it 'includes Callable::Procs::ProcMod in its ancestor chain' do
      expect(myProcster.class.ancestors).to include(TfpMetaprogramming::Callable::Procs::ProcMod)
    end
    describe '#deferred_increment' do
      it 'returns a proc object that increments an argument by num' do
        expect(myProcster.deferred_increment).to be_a_kind_of(Proc)
      end
    end
    describe '#call_increment' do
      it 'increments the arg vic a call to defferred_increment' do
        expect(myProcster.call_increment(6)).to eq(11)
      end
    end
    describe 'xy_lambda' do
      it 'returns a lambda that adds two values' do
        xy = myProcster.xy_lambda
        expect(xy.lambda?).to eq(true)
      end
    end
    describe 'ampersand_catch' do
      context 'when given a raw block {|a, b| a+b }' do
        it 'yields the provided args to the block' do
          block_return = myProcster.ampersand_catch(2,3) {|a, b| a+b }
          expect(block_return).to be(5)
        end
      end
      context 'when passed proc as argument @newProc = proc {|a, b| a * b }' do
        before(:each)do
          @newProc = proc {|a, b| a * b }
        end
        context 'when proc is not preceeded by & operator' do
          it 'raises an ArgumentError' do
            expect { myProcster.ampersand_catch(2,3, @newProc) }.to raise_error(ArgumentError)
          end
        end
        context 'when passed with & operator' do
          it 'converts proc to a block returns yield value ' do
            expect(myProcster.ampersand_catch(2,3, &@newProc)).to eq(6)
          end
        end
      end
      describe 'ampersand_pass' do
        context 'when given apLambda = lambda { |w,z| w * z} ' do
          context 'when given args w,z, apLambda' do
            it 'converts the lambda to a block and passes it to ampersand_catch' do
              apLambda = lambda { |w,z| w * z}
              expect(myProcster.ampersand_pass(4,5, &apLambda)).to be(20)
            end
          end
        end
      end
      describe 'xy_to_ampersand_pass' do
        it 'doubles num, passes xy_lambda to ampersand_pass ' do
          expect(myProcster.xy_to_ampersand_pass).to eq(10)
        end
      end
      describe 'info_lambda' do
        it 'returns a lambda' do
          expect(myProcster.info_lambda).to be_a_kind_of(Proc)
        end
        it 'has a sting endind with "lambda" ' do
          expect(myProcster.info_lambda.call).to end_with("lambda")
        end
      end
      describe '#proc_proxy' do
        it 'takes a proc object and doesnt convert it to a block' do
          lProx = ->(c) { c* 2}
          expect(myProcster.proc_proxy(&lProx)).to be_a_kind_of(Proc)
        end
        # context 'when called with info_lambda' do
        # 	it 'must be called with Proc#call' do

        # 	end

        # end

      end
    end

  end
end


text:
export class ListSelectedSetItemsSelectedAction {
  constructor(
    public items: string[],
    public selected: boolean = false,
    public refresh: boolean = true) {}
}


text:
<!DOCTYPE html>
<html lang="en" class="no-js">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{ site.name }}</title>
        <meta name="description" content="{{ site.name }}" />
        <meta name="keywords" content="UICollectionViewLayout, iOS, UIKit" />
        <meta name="author" content="Sidhant Gandhi" />

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        <link rel="stylesheet" type="text/css" href="./css/demo.css" />
        <link rel="stylesheet" type="text/css" href="./css/component.css" />
        <script src="./js/modernizr.custom.js"></script>
        <script src="./js/jquery-1.11.3.min.js"></script>
        <script src="./js/underscore-min.js"></script>
        <script src="./js/gh3.js"></script>
    </head>
    <body>

        {{ content }}

        <script src="./js/imagesloaded.pkgd.min.js"></script>
        <script src="./js/masonry.pkgd.min.js"></script>
        <script src="./js/classie.js"></script>
        <script src="./js/cbpGridGallery.js"></script>
        <script src="./js/jquery.fittext.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

        <script>
            jQuery("h3").fitText(1.6);
        </script>

        <script>
            new CBPGridGallery( document.getElementById( 'grid-gallery' ) );
        </script>
    </body>
</html>


text:
var five = require('johnny-five');
var board = new five.Board();

board.on('ready', function() {
    var led = new five.Led(11);

    led.blink(process.env.BLINK_RATE);
});


text:
package sample.testnomockito;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SampleTestNoMockitoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SampleTestNoMockitoApplication.class);
	}

}


text:
__author__ = 'pfCao'

import subprocess
import os

def run_adb_cmd(cmd):
    try:
        args = ["adb"]
        args.extend(cmd)
        process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        ret = process.communicate()
    except Exception, ex:
        print ex
        return None
    return ret

def main():
    module_name = "interceptSysCall"
    remote_path = "/data/local/tmp/" + module_name

    os.chdir("..")
    project_path = os.getcwd()

    bin_path = os.path.join(project_path, "libs", "armeabi", module_name)
    run_adb_cmd(["push", bin_path, remote_path])
    run_adb_cmd(["shell", "chmod", "777", remote_path])

if __name__ == '__main__':
    main()


text:
describe("tester Google Analytics Tracker _gat object", () => {

    it("can set ga script element", () => {
        ga = <HTMLScriptElement>document.createElement("script");
    });

    it("can set aync to true", () => {
        ga.async = true;
    });

    it("can set src to string url", () => {
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';;
    });

    it("can set type", () => {
        ga.type = 'text/javascript';
    });

});

describe("tester Google Analytics Tracker _gat object", () => {
    it("can create _createTracker", () => {
        _gat._createTracker('UA-65432-1');
        _gat._createTracker('UA-65432-2', 't2');
    });

    it("can create _getTrackerByName", () => {
        _gat._getTrackerByName();
        _gat._getTrackerByName('t2');
    });

    it("can create _anonymizeIp", () => {
        _gat._anonymizeIp();
    });

});

describe("tester Google Analytics Code  _gaq object", () => {
    it("can create _push", () => {
        _gaq.push(['_setAccount', 'UA-XXXXXXX-YY']);
        _gaq.push(['_gat._anonymizeIp']);
        _gaq.push(['_trackPageview']);

        _gaq.push(() => {
                var tracker = _gat._getTrackerByName('UA-65432-1');
                tracker._trackPageview();
            }
        );
    });
});

describe("tester Google Analytics Code  Tracker object", () => {
    it("can create Tracker object and call methods", () => {
        var tracker = _gat._getTrackerByName('UA-65432-1');
        tracker._trackPageview();
        tracker._getName();
        tracker._getAccount();
        tracker._getVersion();
        tracker._getVisitorCustomVar(0);
        tracker._setAccount();
        tracker._setCustomVar(0, "name", "value", 1);
        tracker._setSampleRate("80");
        tracker._setSessionCookieTimeout(1800000);
        tracker._setSiteSpeedSampleRate(5);
        tracker._setVisitorCookieTimeout(63072000000);
        tracker._trackPageLoadTime();
    });
});


text:
#include <sys/types.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net_connection.h>

#include "caipinterface.h"
#include "caipnwmonitor.h"
#include "caadapterutils.h"
#include "experimental/logger.h"
#include "oic_malloc.h"
#include "oic_string.h"
#include <coap/utlist.h>

#define TAG "OIC_CA_IP_MONITOR"

#define MAX_INTERFACE_INFO_LENGTH (1024)

#define NETLINK_MESSAGE_LENGTH  (4096)
#define IFC_LABEL_LOOP          "lo"
#define IFC_ADDR_LOOP_IPV4      "127.0.0.1"
#define IFC_ADDR_LOOP_IPV6      "::1"

/**
 * Used to storing a connection handle for managing data connections.
 */
static connection_h connection = NULL;

/**
 * Used to storing adapter changes callback interface.
 */
static struct CAIPCBData_t *g_adapterCallbackList = NULL;

/**
 * Create new interface item.
 */
static CAInterface_t *CANewInterfaceItem(int index, char *name, int family,
                                         const char *addr, int flags);

/**
 * Add new network interface in list.
 */
static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
                                     char *name, int family, const char *addr, int flags);

/**
 * Pass the changed network status through the stored callback.
 */
static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status);

/**
 * Used to passing the network status changes to adapter.
 */
static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status);

/**
 * Callback function to received connection state changes.
 */
static void CAIPConnectionStateChangedCb(connection_type_e type, void* userData);

int CAGetPollingInterval(int interval)
{
    return interval;
}

static void CAIPPassNetworkChangesToAdapter(CANetworkStatus_t status)
{
    CAIPCBData_t *cbitem = NULL;
    LL_FOREACH(g_adapterCallbackList, cbitem)
    {
        if (cbitem && cbitem->adapter)
        {
            cbitem->callback(cbitem->adapter, status);
        }
    }
}

CAResult_t CAIPSetNetworkMonitorCallback(CAIPAdapterStateChangeCallback callback,
                                         CATransportAdapter_t adapter)
{
    if (!callback)
    {
        OIC_LOG(ERROR, TAG, "callback is null");
        return CA_STATUS_INVALID_PARAM;
    }

    CAIPCBData_t *cbitem = NULL;
    LL_FOREACH(g_adapterCallbackList, cbitem)
    {
        if (cbitem && adapter == cbitem->adapter && callback == cbitem->callback)
        {
            OIC_LOG(DEBUG, TAG, "this callback is already added");
            return CA_STATUS_OK;
        }
    }

    cbitem = (CAIPCBData_t *)OICCalloc(1, sizeof(*cbitem));
    if (!cbitem)
    {
        OIC_LOG(ERROR, TAG, "Malloc failed");
        return CA_STATUS_FAILED;
    }

    cbitem->adapter = adapter;
    cbitem->callback = callback;
    LL_APPEND(g_adapterCallbackList, cbitem);

    return CA_STATUS_OK;
}

CAResult_t CAIPUnSetNetworkMonitorCallback(CATransportAdapter_t adapter)
{
    CAIPCBData_t *cbitem = NULL;
    CAIPCBData_t *tmpCbitem = NULL;
    LL_FOREACH_SAFE(g_adapterCallbackList, cbitem, tmpCbitem)
    {
        if (cbitem && adapter == cbitem->adapter)
        {
            OIC_LOG(DEBUG, TAG, "remove specific callback");
            LL_DELETE(g_adapterCallbackList, cbitem);
            OICFree(cbitem);
            return CA_STATUS_OK;
        }
    }
    return CA_STATUS_OK;
}

u_arraylist_t *CAFindInterfaceChange(void)
{
    u_arraylist_t *iflist = NULL;
    char buf[NETLINK_MESSAGE_LENGTH] = { 0 };
    struct sockaddr_nl sa = { 0 };
    struct iovec iov = { .iov_base = buf,
                         .iov_len = sizeof (buf) };
    struct msghdr msg = { .msg_name = (void *)&sa,
                          .msg_namelen = sizeof (sa),
                          .msg_iov = &iov,
                          .msg_iovlen = 1 };

    ssize_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0);

    for (struct nlmsghdr *nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
    {
        if (nh != NULL && (nh->nlmsg_type != RTM_DELADDR && nh->nlmsg_type != RTM_NEWADDR))
        {
            continue;
        }
        struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
        if (!ifi)
        {
            continue;
        }

        int ifiIndex = ifi->ifi_index;

        iflist = CAIPGetInterfaceInformation(ifiIndex);
        if (!iflist)
        {
            OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
            return NULL;
        }
    }
    return iflist;
}

CAResult_t CAIPStartNetworkMonitor(CAIPAdapterStateChangeCallback callback,
                                   CATransportAdapter_t adapter)
{
    if (!g_adapterCallbackList)
    {
        // Initialize Connections.
        connection_error_e ret = connection_create(&connection);
        if (CONNECTION_ERROR_NONE != ret)
        {
            OIC_LOG(ERROR, TAG, "connection_create failed");
            return CA_STATUS_FAILED;
        }

        // Set callback for receiving state changes.
        ret = connection_set_type_changed_cb(connection, CAIPConnectionStateChangedCb, NULL);
        if (CONNECTION_ERROR_NONE != ret)
        {
            OIC_LOG(ERROR, TAG, "connection_set_type_changed_cb failed");
            return CA_STATUS_FAILED;
        }
    }

    OIC_LOG(DEBUG, TAG, "Initialize network monitoring successfully");
    return CAIPSetNetworkMonitorCallback(callback, adapter);
}

CAResult_t CAIPStopNetworkMonitor(CATransportAdapter_t adapter)
{
    OIC_LOG(DEBUG, TAG, "IN");

    CAIPUnSetNetworkMonitorCallback(adapter);
    if (!g_adapterCallbackList)
    {
        // Reset callback for receiving state changes.
        if (connection)
        {
            connection_error_e ret = connection_unset_type_changed_cb(connection);
            if (CONNECTION_ERROR_NONE != ret)
            {
                OIC_LOG(ERROR, TAG, "connection_unset_type_changed_cb failed");
            }

            // Deinitialize Wifi service.
            ret = connection_destroy(connection);
            if (CONNECTION_ERROR_NONE != ret)
            {
                OIC_LOG(ERROR, TAG, "connection_destroy failed");
            }
            connection = NULL;
        }
    }

    OIC_LOG(DEBUG, TAG, "Network monitoring terminated successfully");
    return CA_STATUS_OK;
}

/**
 * Used to send netlink query to kernel and recv response from kernel.
 *
 * @param[in]   idx       desired network interface index, 0 means all interfaces.
 * @param[out]  iflist    linked list.
 *
 */
static bool CAIPGetAddrInfo(int idx, u_arraylist_t *iflist)
{
    if ((idx < 0) || (iflist == NULL))
    {
        return false;
    }

    struct ifaddrs *ifp = NULL;
    if (-1 == getifaddrs(&ifp))
    {
        OIC_LOG_V(ERROR, TAG, "Failed to get ifaddrs: %s", strerror(errno));
        return false;
    }

    struct ifaddrs *ifa = NULL;
    for (ifa = ifp; ifa; ifa = ifa->ifa_next)
    {
        if (!ifa->ifa_addr)
        {
            continue;
        }

        int family = ifa->ifa_addr->sa_family;
        if ((ifa->ifa_flags & IFF_LOOPBACK) || (AF_INET != family && AF_INET6 != family))
        {
            continue;
        }

        int ifindex = if_nametoindex(ifa->ifa_name);
        if (idx && (ifindex != idx))
        {
            continue;
        }

        char ipaddr[MAX_ADDR_STR_SIZE_CA] = {0};
        if (family == AF_INET6)
        {
            struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa->ifa_addr;
            inet_ntop(family, (void *)&(in6->sin6_addr), ipaddr, sizeof(ipaddr));
        }
        else if (family == AF_INET)
        {
            struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr;
            inet_ntop(family, (void *)&(in->sin_addr), ipaddr, sizeof(ipaddr));
        }

        if ((strcmp(ipaddr, IFC_ADDR_LOOP_IPV4) == 0) ||
            (strcmp(ipaddr, IFC_ADDR_LOOP_IPV6) == 0) ||
            (strcmp(ifa->ifa_name, IFC_LABEL_LOOP) == 0))
        {
            OIC_LOG(DEBUG, TAG, "LOOPBACK continue!!!");
            continue;
        }

        CAResult_t result = CAAddInterfaceItem(iflist, ifindex,
                                               ifa->ifa_name, family,
                                               ipaddr, ifa->ifa_flags);
        if (CA_STATUS_OK != result)
        {
            OIC_LOG(ERROR, TAG, "CAAddInterfaceItem fail");
            goto exit;
        }
    }
    freeifaddrs(ifp);
    return true;

exit:
    freeifaddrs(ifp);
    return false;
}

u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
{
    u_arraylist_t *iflist = u_arraylist_create();
    if (!iflist)
    {
        OIC_LOG_V(ERROR, TAG, "Failed to create iflist: %s", strerror(errno));
        return NULL;
    }

    if (!CAIPGetAddrInfo(desiredIndex, iflist))
    {
        goto exit;
    }

    return iflist;

exit:
    u_arraylist_destroy(iflist);
    return NULL;
}

static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
                                     char *name, int family, const char *addr, int flags)
{
    CAInterface_t *ifitem = CANewInterfaceItem(index, name, family, addr, flags);
    if (!ifitem)
    {
        return CA_STATUS_FAILED;
    }
    bool result = u_arraylist_add(iflist, ifitem);
    if (!result)
    {
        OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
        OICFree(ifitem);
        return CA_STATUS_FAILED;
    }

    return CA_STATUS_OK;
}

static CAInterface_t *CANewInterfaceItem(int index, char *name, int family,
                                         const char *addr, int flags)
{
    CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t));
    if (!ifitem)
    {
        OIC_LOG(ERROR, TAG, "Malloc failed");
        return NULL;
    }

    OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, name);
    ifitem->index = index;
    ifitem->family = family;
    OICStrcpy(ifitem->addr, sizeof(ifitem->addr), addr);
    ifitem->flags = flags;

    return ifitem;
}

void CAIPConnectionStateChangedCb(connection_type_e type, void* userData)
{
    OC_UNUSED(userData);

    switch (type)
    {
        case CONNECTION_TYPE_DISCONNECTED:
            OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_DISCONNECTED");
            CAIPPassNetworkChangesToAdapter(CA_INTERFACE_DOWN);
            break;
        case CONNECTION_TYPE_ETHERNET:
            OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_ETHERNET");
            CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
            break;
        case CONNECTION_TYPE_WIFI:
            OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_WIFI");
            CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
            break;
        case CONNECTION_TYPE_CELLULAR:
            OIC_LOG(DEBUG, TAG, "Connection is in CONNECTION_TYPE_CELLULAR");
            CAIPPassNetworkChangesToAdapter(CA_INTERFACE_UP);
            break;
        default:
            break;
    }
}

CAResult_t CAGetLinkLocalZoneIdInternal(uint32_t ifindex, char **zoneId)
{
    if (!zoneId || (*zoneId != NULL))
    {
        return CA_STATUS_INVALID_PARAM;
    }

    *zoneId = (char *)OICCalloc(IF_NAMESIZE, sizeof(char));
    if (!(*zoneId))
    {
        OIC_LOG(ERROR, TAG, "OICCalloc failed in CAGetLinkLocalZoneIdInternal");
        return CA_MEMORY_ALLOC_FAILED;
    }

    if (!if_indextoname(ifindex, *zoneId))
    {
        OIC_LOG(ERROR, TAG, "if_indextoname failed in CAGetLinkLocalZoneIdInternal");
        OICFree(*zoneId);
        *zoneId = NULL;
        return CA_STATUS_FAILED;
    }

    OIC_LOG_V(DEBUG, TAG, "Given ifindex is %d parsed zoneId is %s", ifindex, *zoneId);
    return CA_STATUS_OK;
}


text:
/** @jsx jsx **/
import { jsx, css } from "@emotion/core";
import * as React from "react";
import { Link } from "@material-ui/core";
import { DialogControlGroup } from "./BloomDialog/commonDialogComponents";

interface IBookInfoCardProps {
    title: string;
    bookUrl?: string;
    languages: string[];
    thumbnailUrl?: string;
    originalUpload?: string;
    lastUpdated?: string;
}

export const BookInfoCard: React.FunctionComponent<IBookInfoCardProps> = props => {
    const languageList = props.languages.map((languageName, index) => {
        return
{languageName}
;
    });

    const titleWithOptionalLink = (): JSX.Element => (

            {props.bookUrl ? (
                <Link color="primary" underline="always" href={props.bookUrl}>
                    {props.title}
                </Link>
            ) : (
                props.title
            )}

    );

    return (

            <DialogControlGroup>

                    {props.thumbnailUrl && (

                    )}

                        {titleWithOptionalLink()}
                        {languageList}
                        {props.originalUpload && (

Uploaded {props.originalUpload}

                        )}
                        {props.lastUpdated && (

Last updated on {props.lastUpdated}

                        )}

            </DialogControlGroup>

    );
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>例子 · Twitter Bootstrap中文版/中文翻译</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="assets/css/bootstrap.css" rel="stylesheet">
    <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
    <link href="assets/css/docs.css" rel="stylesheet">
    <link href="assets/js/google-code-prettify/prettify.css" rel="stylesheet">

    <link rel="shortcut icon" href="assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">

          Bootstrap

                概述

                框架

                基础CSS

                组件

                Javascript插件

                使用LESS

                定制

                例子

                译者言

Bootstrap 入门案例

    Bootstrap提供了一些基础例子,以便于快速上手。我们鼓励用户对这些例子进行扩展,而不是简单地照搬。

基本的市场类市场

      由一个主角单元(hero unit)强调首要内容,搭配三个辅助区动。

流式布局

      使用流动栅格系统,符合响应式设计的无缝流式布局。

初始模板

      包含所有Bootstrap样式和js的空白HTML文档。

回到顶端

我们倾注世间之爱于设计与创作 @twitter by @mdo and @fat,由Tvlike.me/TV来客开发者翻译

开源依照 Apache License v2.0 发布。 文档依照 CC BY 3.0 发布。

Icons取自 Glyphicons Free,授权依照 CC BY 3.0。


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Quick Sort — k14i.github.io 1.0.0 documentation</title>
    <link rel="stylesheet" href="../../_static/pyramid.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Prime Number" href="prime_number.html" />
    <link rel="prev" title="Merge Sort" href="merge_sort.html" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Neuton&subset=latin" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nobile:regular,italic,bold,bolditalic&subset=latin" type="text/css" media="screen" charset="utf-8" />

Navigation

          index

          next |

          previous |

k14i.github.io 1.0.0 documentation »

Computer Science »

Algorithm »

Quick Sort¶

Examples¶

Java¶

void quickSort(int arr[], int left, int right) {
  int index = partition(arr, left, right);
  if (left < index - 1) {
    quickSort(arr, left, index - 1);
  }
  if (index < right) {
    quickSort(arr, index, right);
  }
}

int partition(int arr[], int left, int right) {
  int pivot = arr[(left + right) / 2];
  while (left <= right) {
    while (arr[left] < pivot) left++;

    while (arr[right] > pivot) right--;

    if (left <= right) {
      swap(arr, left, right);
      left++;
      right--;
    }
  }
  return left;
}

My repository

Table Of Contents

Computer Science

Elixir

C

Programming Languages

Operation and Monitoring

GlusterFS

Docker

Bayes' theorem

Personal Data Protection

Sphinx

Presentation

Erlang Factory SF Bay Area 2014

Strata + Hadoop World 2015

Timeline

Favorite Tweets

Previous topic

Merge Sort

Next topic

Prime Number

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

k14i.github.io 1.0.0 documentation »

Computer Science »

Algorithm »

        © Copyright 2015-2021, Keisuke Takahashi.
      Created using Sphinx 1.7.9.


text:
package uk.ac.ebi.atlas.commons.readers;

import org.apache.commons.lang3.tuple.Triple;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.util.stream.Stream;

public class MatrixMarketReader implements AutoCloseable {
    private final int numRows;
    private final int numCols;
    private final Stream<Triple<Integer, Integer, Double>> lines;
    private final BufferedReader inReader;

    public MatrixMarketReader(Reader reader) throws IOException {
        inReader = new BufferedReader(reader);

        String line;
        do {
            line = inReader.readLine();
        } while (line.startsWith("%"));

        String[] splitLine = line.split(" ");
        numRows = Integer.parseInt(splitLine[0]);
        numCols = Integer.parseInt(splitLine[1]);

        lines = inReader.lines().map(MatrixMarketReader::parseLine);
    }

    public int getRows() {
        return numRows;
    }

    public int getColumns() {
        return numCols;
    }

    public Stream<Triple<Integer, Integer, Double>> stream() {
        return lines;
    }

    @Override
    public void close() {
        try {
            inReader.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static Triple<Integer, Integer, Double> parseLine(String line) {
        String[] splitLine = line.split(" ");
        return Triple.of(
                Integer.parseInt(splitLine[0]),
                Integer.parseInt(splitLine[1]),
                Double.parseDouble(splitLine[2]));
    }
}


text:
@interface UIImage (Resize)
- (UIImage*) scaleToSize:(CGSize)size;
@end