text:
package de.iftm.dcm4che.services;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.Socket;
import java.net.URL;
import java.net.ConnectException;
import java.security.GeneralSecurityException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.text.ParseException;

import org.dcm4che.data.Command;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmDecodeParam;
import org.dcm4che.data.DcmElement;
import org.dcm4che.data.DcmEncodeParam;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.data.DcmParseException;
import org.dcm4che.data.DcmParser;
import org.dcm4che.data.DcmParserFactory;
import org.dcm4che.data.FileFormat;
import org.dcm4che.dict.DictionaryFactory;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDDictionary;
import org.dcm4che.dict.UIDs;
import org.dcm4che.dict.VRs;
import org.dcm4che.net.AAssociateAC;
import org.dcm4che.net.AAssociateRQ;
import org.dcm4che.net.ActiveAssociation;
import org.dcm4che.net.Association;
import org.dcm4che.net.AssociationFactory;
import org.dcm4che.net.Dimse;
import org.dcm4che.net.DataSource;
import org.dcm4che.net.FutureRSP;
import org.dcm4che.net.PDU;
import org.dcm4che.net.PresContext;
import org.dcm4che.server.PollDirSrv;
import org.dcm4che.server.PollDirSrvFactory;
import org.dcm4che.util.DcmURL;
import org.dcm4che.util.SSLContextAdapter;

import org.apache.log4j.Logger;

/**
 * Implementation of C-DIMSE services.
 *

 *
 Usage:
 *
 1. Create a new instance of this class.
 *
 2. Use the aASSOCIATE method to establish an association.
 *
 3. Use the cFIND method to query  the archive.
 *
 4. Use the cMOVE method to move an object from the archive to a destination server.
 *
 5. Use the cSTORE to store an object into an archive.
 *
 6. Use the cECHO to verfy a association.
 *
 7. If you are ready with the C-DIMSE services use the aRELEASE method to close the association.
 *

 *
Based on dcm4che 1.4.0 sample: MoveStudy.java revision date 2005-10-05
 *
Based on dcm4che 1.4.0 sample: DcmSnd.java revision date 2005-10-05
 *

 *
See: PS 3.4 - Annex B STORAGE SERVICE CLASS
 *
See: PS 3.4 - Annex C QUERY/RETRIEVE SERVICE CLASS
 *
See: PS 3.4 - C.6 SOP CLASS DEFINITIONS
 *
See: PS 3.4 - C.6.2 Study Root SOP Class Group
 *

 *
Details of how to run the services is given in a configuration property file.
 * A sample may be found at "./resources/CDimseService.cfg".
 *
 *
 * @author Thomas Hacklaender
 * @version 2006-06-28
 */
public class CDimseService {

    static final Logger log = Logger.getLogger("CDimseService");

    /** The DEBUG flag is set, if the logging level of this class is Debug */
    final static boolean DEBUG = log.isDebugEnabled();

    //>>>> Factorys >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private static final UIDDictionary uidDict = DictionaryFactory.getInstance().getDefaultUIDDictionary();
    private static final AssociationFactory aFact = AssociationFactory.getInstance();
    private static final DcmObjectFactory oFact = DcmObjectFactory.getInstance();
    private static final DcmParserFactory pFact = DcmParserFactory.getInstance();
    private final static DcmObjectFactory dof = DcmObjectFactory.getInstance();

    /** Default AE title used for the association if it is not explicit given in the url filed. */
    private final static String DEFAULT_CALLING_AET = "MYAET";

    /** Query/Retrieve Level Values for Study. See PS 3.4 - C.6 SOP CLASS DEFINITIONS*/
    private final static String STUDY_LEVEL = "STUDY";

    /** Query/Retrieve Level Values for Series. See PS 3.4 - C.6 SOP CLASS DEFINITIONS*/
    private final static String SERIES_LEVEL = "SERIES";

    /** Query/Retrieve Level Values for Image. See PS 3.4 - C.6 SOP CLASS DEFINITIONS*/
    private final static String IMAGE_LEVEL = "IMAGE";

    /** DICOM URL to define a communication partner for an association.
     *
PROTOCOL://CALLED[:CALLING]@HOST[:PORT]
     *

     *
PROTOCOL Specifies protocol. Possible values:
     *
   - dicom            DICOM default (without TLS)
     *
   - dicom-tls        DICOM on TLS (offer AES and DES encryption)
     *
   - dicom-tls.aes    DICOM on TLS (force AES or DES encryption)
     *
   - dicom-tls.3des   DICOM on TLS (force DES encryption)
     *
   - dicom-tls.nodes  DICOM on TLS (no encryption)
     *
CALLED  Called AET in association request (max 16 chars)
     *
CALLING Calling AET in association request (max 16 chars) [default id final field DEFAULT_CALLING_AET = MYAET]
     *
HOST    Name or IP address of host, where the server is running
     *
PORT    TCP port address, on which the server is listing for
     *
        incoming TCP Transport Connection Indication [default=104] */
    private DcmURL url = null;

    /** Message priority. Possible values Command.LOW = 2, Command.MEDIUM = 0, Command.HIGH = 1*/
    private int priority = Command.MEDIUM;

    /** Time-out waiting [in msec] for A-ASSOCIATE-AC acknowlage, 0 is interpreted
     * as an infinite timeout [default=5000]. */
    private int acTimeout = 5000;

    /** Time-out waiting [in msec] for DIMSE on aASSOCIATE association, 0 is
     * interpreted as an infinite timeout [default=0]. */
    private int dimseTimeout = 0;

    /** Time delay [in msec] for socket aRELEASE after sending A-ABORT [default=500]. */
    private int soCloseDelay = 500;

    /** Association Request package (A-ASSOCIATE-RQ) is part of the connection
     * service ACSE (Association Control Service Element). In TCP/IP networks
     * connection services are emulated by the "DICOM Upper Layer Service".
     * This presentation srvice encapsulats the data in PDUs (Protocol Data Unit). */
    private AAssociateRQ assocRQ = aFact.newAAssociateRQ();

    /** Association object for establishing an active association. */
    private Association assoc = null;

    /** Accepted association */
    private ActiveAssociation aassoc = null;

    /** Activates packing of command PDV (Presentation Data Value) + (first) data
     * PDV into one P-DATA-TF PDU (Protocol Data Unit) */
    private boolean packPDVs = false;

    /** TLS context. Set by method initTLS */
    private SSLContextAdapter tls = null;

    /** An array of implemented ciphers for the communication protocol (given in url). */
    private String[] cipherSuites = null;

    /** Specifies Key Attributes used for C-FIND.
     * Wildcards '*','?', '-' and '\' are allowed as element-values (see PS 3.4 - C.2.2.2 Attribute Matching).
     * If an key attribute is defined, but has an empty value, it matches every value at the storage side.
     *
Key attributes have a type (PS 3.4 - C.2.2.1 Attribute Types)
     *
  - U = one Attribute shall be defined as a Unique Key.
     *
  - R = a set of Attributes shall be defined as Required Keys.
     *
  - O = a set of Attributes shall be defined as Optional Keys.
     *
The complete list of Key Attributes can be found at PS 3.4 - C.6.2 Study Root SOP Class Group.
     *
As a result of C-FIND for each matching item in the archive a DIMSE object containing
     * the Key Attributes is send back. In this object the Key Attributes are set corresponding to
     * values found in the archive. Attributes of type "O" may be send back with empty value.
     * Only used by C-FIND. */
    private Dataset keys = dof.newDataset();

    /** Application Entity Title (AET) of the destination for the C-MOVE. The
     * AET must be known by the archive together with the host IP adress and the
     * port number. Only used by C-MOVE. */
    private String dest;

    //>>>> Constructor >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    /**
     *  Constructor for the StorageSCUServiceClass object. Initializes everything.
     *
     *
Details of how to run the server is given in another configuration property file.
     * A sample may be found at "./resources/StorageSCUServiceClass.cfg".
     *
     * @param cfg the configuration properties for this class.
     * @param url the DcmURL of the communication partner.
     * @throws ParseException
     */
    public CDimseService(ConfigProperties cfg, DcmURL url) throws ParseException {
        this.url = url;
        this.priority = Integer.parseInt(cfg.getProperty("prior", "0"));
        this.packPDVs = "true".equalsIgnoreCase(cfg.getProperty("pack-pdvs", "false"));
        initAssocParam(cfg, url);
        // initEchoAssocParam(cfg, url);
        initTLS(cfg);

        // Only used by C-FIND
        initKeys(cfg);

        // Only used by C-MOVE
        this.dest = cfg.getProperty("dest");
    }

    //>>>> Methods >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    /**
     * Initializes Association related parameters.
     *
     * @param cfg the configuration properties for this class.
     * @param url the DcmURL of the communication partner.
     */
    private final void initAssocParam(ConfigProperties cfg, DcmURL url) {
        String callingAET = null;

        //>>>> Get data for filling the Association object for establishing an
        //>>>> active association from configuration file

        acTimeout = Integer.parseInt(cfg.getProperty("ac-timeout", "5000"));
        dimseTimeout = Integer.parseInt(cfg.getProperty("dimse-timeout", "0"));
        soCloseDelay = Integer.parseInt(cfg.getProperty("so-close-delay", "500"));

        //>>>> Fill the Association Request package (A-ASSOCIATE-RQ)

        // Identifying the communication partner by an AET (Application Entity Title)
        assocRQ.setCalledAET(url.getCalledAET());

        // Identifying ourselves by an AET (Application Entity Title)
        if (url.getCallingAET() != null) {
            callingAET = url.getCallingAET();
        } else {
            callingAET = DEFAULT_CALLING_AET;
        }
        assocRQ.setCallingAET(callingAET);

        // Maximum size of one PDU (Protocol Data Unit)
        assocRQ.setMaxPDULength(Integer.parseInt(cfg.getProperty("max-pdu-len", "16352")));

        // Defines possibilities for asynchron DIMSE communication. Noramly synchron DIMSE communication is used.
        // API doc: AssociationFactory.newAsyncOpsWindow(int maxOpsInvoked, int maxOpsPerfomed)
        // PS 3.7 - Annex D.3.3.3 ASYNCHRONOUS OPERATIONS WINDOW NEGOTIATION
        // maxOpsInvoked: This field shall contain the Maximum-number-operationsinvoked as defined for the Association-requester
        // maxOpsPerfomed: This field shall contain the Maximum-number-operationsperformed as defined for the Association-requester
        assocRQ.setAsyncOpsWindow(aFact.newAsyncOpsWindow(Integer.parseInt(cfg.getProperty("max-op-invoked", "0")), 1));

        for (Enumeration it = cfg.keys(); it.hasMoreElements();) {
            String key = (String) it.nextElement();

            // Setup available transfer syntaces for storage SOP classes
            // PS 3.4 - Annex B STORAGE SERVICE CLASS
            // PS 3.4 - B.5 STANDARD SOP CLASSES
            if (key.startsWith("pc.")) {
                initPresContext(Integer.parseInt(key.substring(3)), cfg.tokenize(cfg.getProperty(key), new LinkedList()));
            }
        }
    }

    /**
     * Only used by method initAssocParam:
     * Sets up available transfer syntaces for storage SOP classes.
     * @param pcid is a for the association unique odd number between 1 and 255.
     * @param val a list: First element is the symbolic name of the UID of the
     *            SOP to transmit, the following elements are the supportet
     *            transfer syntax for that SOP.
     */
    private final void initPresContext(int pcid, List val) {
        Iterator it = val.iterator();
        String as = UIDs.forName((String) it.next());
        String[] tsUIDs = new String[val.size() - 1];
        for (int i = 0; i < tsUIDs.length; ++i) {
            tsUIDs[i] = UIDs.forName((String) it.next());
        }
        // API doc: AssociationFactory.newPresContext(int pcid, String asuid, String[] tsuid)
        // pcid is a for the association unique odd number between 1 and 255.
        // asuid is the UID of a SOP class
        // TS list of transfer syntaces supported by this class for asuid.
        assocRQ.addPresContext(aFact.newPresContext(pcid, as, tsUIDs));
    }

    /**
     * Initializes TLS (Transport Layer Security, predecessor of SSL, Secure
     * Sockets Layer) connection related parameters. TLS expects RSA (Ron Rivest,
     * Adi Shamir and Len Adleman) encoded keys and certificates.
     *
Keys and certificates may be stored in PKCS #12 (Public Key
     * Cryptography Standards) or JKS (Java Keystore) containers.
     *
     * @param cfg the configuration properties for this class.
     * @throws ParseException
     */
    private void initTLS(ConfigProperties cfg) throws ParseException {
        char[]  keystorepasswd;
        char[]  keypasswd;
        char[]  cacertspasswd;
        URL     keyURL;
        URL     cacertURL;
        String  value;

        try {

            // Cipher suites for protokoll:
            // dicom = null
            // dicom-tls = SSL_RSA_WITH_NULL_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA
            // dicom-tls.3des = SSL_RSA_WITH_3DES_EDE_CBC_SHA
            // dicom-tls.aes = TLS_RSA_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA
            // dicom-tls.nodes = SSL_RSA_WITH_NULL_SHA
            cipherSuites = url.getCipherSuites();
            if (cipherSuites == null) {
                return;
            }

            // Get a new TLS context
            tls = SSLContextAdapter.getInstance();

            //>>>> Managing the keystore file containing the privat key and
            //>>>> public certificate to establish the communication

            // Password for keystore [default: secret]
            keystorepasswd = cfg.getProperty("tls-keystore-passwd", "secret").toCharArray();

            // Password the private key [default: secret]
            keypasswd = cfg.getProperty("tls-key-passwd", "secret").toCharArray();

            // URL of the file containing the keystore
            keyURL = CDimseService.class.getResource("resources/identity.p12");

            // If availabel, replace URL with the one specified in the configuration file
            if ((value = cfg.getProperty("tls-key")) != null) {
                try {
                    // Property specified, try to set to specified value
                    keyURL = ConfigProperties.fileRefToURL(CDimseService.class.getResource(""), value);
                } catch (Exception e) {
                    log.warn("Wrong value for tls-key: " + value + ". tls-key was set to default value.");
                }
            }

            // log.info("Key URL: " + keyURL.toString());

            // Sets the key attribute of the SSLContextAdapter object
            // API doc: SSLContextAdapter.loadKeyStore(java.net.URL url, char[] password)
            // API doc: SSLContextAdapter.setKey(java.security.KeyStore key, char[] password)
            tls.setKey(tls.loadKeyStore(keyURL, keystorepasswd), keypasswd);

            //>>>> Managing the keystore containing the public certificates of the Ceritifying
            //>>>> Authorities used for signing the public certificates of the public keys

            // Get the password of the keystore
            cacertspasswd = cfg.getProperty("tls-cacerts-passwd", "secret").toCharArray();

            // URL of the file containing the keystore
            cacertURL = CDimseService.class.getResource("resources/cacerts.jks");

            // If availabel, replace URL with the one specified in the configuration file
            if ((value = cfg.getProperty("tls-cacerts")) != null) {
                try {
                    // Property specified, try to set to specified value
                    cacertURL = ConfigProperties.fileRefToURL(CDimseService.class.getResource(""), value);
                } catch (Exception e) {
                    log.warn("Wrong value for tls-cacerts: " + value + ". tls-cacerts was set to default value.");
                }
            }

            // log.info("Trust certificate URL: " + cacertURL.toString());

            // Sets the trust attribute of the SSLContextAdapter object
            // API doc: SSLContextAdapter.loadKeyStore(java.net.URL url, char[] password)
            // API doc: SSLContextAdapter.setTrust(java.security.KeyStore cacerts)
            tls.setTrust(tls.loadKeyStore(cacertURL, cacertspasswd));

            // Init TLS context adapter
            tls.init();

        } catch (Exception ex) {
            throw new ParseException("Could not initalize TLS configuration.", 0);
        }
    }

    /**
     * Prepares the Dataset representing the search key in C-FIND. As no values are
     * set, the keys match to every content in the archive. The user has to specify
     * concret values to limit the searchSee PS 3.4 - C.6.2.1.2 Study level.
     *
As the result for C-FIND these keys are filled with the values found in the archive.
     * @param cfg the configuration properties for this class.
     * @throws ParseException if a given properties for the keys was not found.
     */
    private void initKeys(ConfigProperties cfg) throws ParseException {

        // Query/Retrieve Level. PS 3.4 - C.6.2 Study Root SOP Class Group
        keys.putCS(Tags.QueryRetrieveLevel, STUDY_LEVEL);

        // UNIQUE STUDY LEVEL KEY FOR THE STUDY. See PS 3.4 - C.6.2.1.2 Study level
        keys.putUI(Tags.StudyInstanceUID);

        // REQUIRED STUDY LEVEL KEY FOR THE STUDY. See PS 3.4 - C.6.2.1.2 Study level
        keys.putDA(Tags.StudyDate);
        // Not defined: StudyTime
        // Not defined: AccessionNumber
        keys.putPN(Tags.PatientName);
        keys.putLO(Tags.PatientID);
        // Not defined: StudyID

        // OPTIONAL STUDY LEVEL KEY FOR THE STUDY. See PS 3.4 - C.6.2.1.2 Study level
        keys.putUS(Tags.NumberOfStudyRelatedSeries);
        keys.putUS(Tags.NumberOfStudyRelatedInstances);
        // mutch more defined...

        // Add/replace keys found in the configuration file. Syntax key.<element name> = <element value>
        for (Enumeration it = cfg.keys(); it.hasMoreElements(); ) {
            String key = (String) it.nextElement();
            if (key.startsWith("key.")) {
                try {
                    keys.putXX(Tags.forName(key.substring(4)), cfg.getProperty(key));
                } catch (Exception e) {
                    throw new ParseException("Illegal entry in configuration filr: " + key + "=" + cfg.getProperty(key), 0);
                }
            }
        }
    }

    /**
     * Starts a active association to a communication partner.
     * See PS 3.8 - 7.1 A-ASSOCIATE SERVICE
     *
     * @return true, if association was successful established.
     * @exception  ConnectException
     * @exception  IOException
     * @exception  GeneralSecurityException
     */
    public boolean aASSOCIATE() throws ConnectException, IOException, GeneralSecurityException {

        // No association may be active
        if (assoc != null) {
            throw new ConnectException("Association already established");
        }

        // New Association object for establishing an active association
        assoc = aFact.newRequestor(newSocket(url.getHost(), url.getPort()));

        //>>>> Fill the Association object with relevant data
        assoc.setAcTimeout(acTimeout);
        assoc.setDimseTimeout(dimseTimeout);
        assoc.setSoCloseDelay(soCloseDelay);
        assoc.setPackPDVs(packPDVs);

        // 1. Create an communication channel to the communication partner defined in the Association object
        // 2. Send the A-ASSOCIATE-RQ package
        // 3. Receive the aAssociation acknowlage/reject package from the communication partner as a PDU (Protocol Data Unit)
        PDU assocAC = assoc.connect(assocRQ);

        if (!(assocAC instanceof AAssociateAC)) {
            // Acknowlage is A-ASSOCIATE-RJ
            // Association rejected
            assoc = null;

            // Return aASSOCIATE faild
            return false;
        }
        // Acknowlage is A-ASSOCIATE_AC
        // Association accepted

        // Start the accepted association
        // API doc: AssociationFactory.newActiveAssociation(Association assoc, DcmServiceRegistry services)
        aassoc = aFact.newActiveAssociation(assoc, null);
        aassoc.start();

        // Return successfull opened
        return true;
    }

    /**
     * Creates a stream socket and connects it to the specified port number on the named host.
     * @param host the IP address.
     * @param port the port number.
     * @return the Socket.
     * @exception  IOException
     * @exception  GeneralSecurityException
     */
    private Socket newSocket(String host, int port) throws IOException, GeneralSecurityException {

        // Test, if a secured connection is needed
        if (cipherSuites != null) {

            // Creates a socket for secured connection.
            // The SSLContextAdapter tls uses the javax.net.ssl package for establishing
            // the connection.
            return tls.getSocketFactory(cipherSuites).createSocket(host, port);
        } else {

            // Creates a standard Java socket for unsecured connection.
            return new Socket(host, port);
        }
    }

    /**
     * Releases the active association.
     * See PS 3.8 - 7.2 A-RELEASE SERVICE
     *
     * @param waitOnRSP if true, method waits until it receives the responds
     *                  to the release request.
     * @exception  InterruptedException  Description of the Exception
     * @exception  IOException           Description of the Exception
     */
    public void aRELEASE(boolean waitOnRSP) throws InterruptedException, IOException {
        if (assoc != null) {
            try {
                aassoc.release(waitOnRSP);
            } finally {
                assoc = null;
                aassoc = null;
            }
        }
    }

    /**
     * Stores a DICOM object in an archive (Storage SCP).
     *
See PS 3.4 - Annex B STORAGE SERVICE CLASS.
     *
     * @param ds the Dataset to store.
     * @throws ConnectException
     * @throws ParseException
     * @throws IOException
     * @throws InterruptedException
     * @throws IllegalStateException
     */
    public void cSTORE(Dataset ds) throws InterruptedException, IOException, ConnectException, ParseException {
        String  sopClassUID;
        String  sopInstUID;
        PresContext pc = null;

        // An association must be active
        if (aassoc == null) {
            throw new ConnectException("No Association established");
        }

        // SOP Class UID must be given
        if ((sopClassUID = ds.getString(Tags.SOPClassUID)) == null) {
            throw new ParseException("No SOP Class UID in Dataset", 0);
        }

        // SOP Instance UID must be given
        if ((sopInstUID = ds.getString(Tags.SOPInstanceUID)) == null) {
            throw new ParseException("No SOP Instance UID in Dataset", 0);
        }

        // Test, if applicable presentation context was found
        if ((pc = aassoc.getAssociation().getAcceptedPresContext(sopClassUID, UIDs.ImplicitVRLittleEndian)) == null &&
                (pc = aassoc.getAssociation().getAcceptedPresContext(sopClassUID, UIDs.ExplicitVRLittleEndian)) == null &&
                (pc = aassoc.getAssociation().getAcceptedPresContext(sopClassUID, UIDs.ExplicitVRBigEndian)) == null) {

            throw new ConnectException("No applicable presentation context found");
        }

        // New Cammand Set, see: DICOM Part 7: Message Exchange, 6.3.1 Command Set Structure
        Command cStoreRQ = oFact.newCommand();
        // API doc: Command.initCStoreRQ(int msgID, String sopClassUID, String sopInstUID, int priority)
        cStoreRQ.initCStoreRQ(assoc.nextMsgID(), sopClassUID, sopInstUID, priority);

        // API doc: AssociationFactorynewDimse(int pcid, Command cmd, Dataset ds)
        // DIMSE (DICOM Message Service Element) ist ein Nachrichtendienst in DICOM
        Dimse storeRq = aFact.newDimse(pc.pcid(), cStoreRQ, ds);

        // PS 3.7 - 9.3.1 C-STORE PROTOCOL, 9.3.1.2 C-STORE-RSP
        // Always returns SUCESS result code.
        // Invoke active association with echo request Dimse
        FutureRSP future = aassoc.invoke(storeRq);

        // Response to the C-ECHO request.
        // The result cannot be accessed until it has been set.
        Dimse storeRsp = future.get();
        Command rspCmd = storeRsp.getCommand();

        // PS 3.7 - 9.3.5 C-MOVE PROTOCOL, 9.3.5.2 C-ECHO-RSP
        int status = rspCmd.getStatus();
        switch (status) {
            case 0x0000:
                // Success
                break;
            default:
                log.error("C-STORE failed: " + Integer.toHexString(status));
                break;
        }

    }

    /**
     * Queries the archive for DICOM objects matching Attribute Keys.
     * See PS 3.4 - Annex C QUERY/RETRIEVE SERVICE CLASS.
     *
The method returns, when the result is received from the communication partner.
     *
     * @return the result of the cFIND as a Vector of Dataset objects each specifying
     *         one matching DICOM object. If no matching objects are found an empty Vector is returned.
     * @throws ConnectException
     * @throws IOException
     */
    public Vector cFIND() throws ConnectException, IOException, InterruptedException {
        PresContext pc;
        List dimseList;
        Vector datasetVector;

        // An association must be active
        if (aassoc == null) {
            throw new ConnectException("No Association established");
        }

        // Test, if Presentation Context for C-FIND is supported
        // API doc: Association.getAcceptedPresContext(String asuid, String tsuid)
        if ((pc = aassoc.getAssociation().getAcceptedPresContext(UIDs.StudyRootQueryRetrieveInformationModelFIND, UIDs.ExplicitVRLittleEndian)) == null &&
                (pc = aassoc.getAssociation().getAcceptedPresContext(UIDs.StudyRootQueryRetrieveInformationModelFIND, UIDs.ImplicitVRLittleEndian)) == null) {
            throw new ConnectException("Association does not support presentation context for StudyRootQueryRetrieveInformationModelFIND SOP.");
        }

        // New Cammand Set, see: DICOM Part 7: Message Exchange, 6.3.1 Command Set Structure
        Command rqCmd = dof.newCommand();
        // API doc: Command.initCFindRQ(int msgID, String sopClassUID, int priority)
        rqCmd.initCFindRQ(assoc.nextMsgID(), UIDs.StudyRootQueryRetrieveInformationModelFIND, priority);
        // API doc: AssociationFactorynewDimse(int pcid, Command cmd, Dataset ds)
        // DIMSE (DICOM Message Service Element) ist ein Nachrichtendienst in DICOM
        Dimse findRq = aFact.newDimse(pc.pcid(), rqCmd, keys);

        if (DEBUG) {
            StringWriter w = new StringWriter();
            w.write("C-FIND RQ Identifier:\n");
            keys.dumpDataset(w, null);
            log.debug(w.toString());
        }

        // Invoke active association with find request Dimse
        FutureRSP future = aassoc.invoke(findRq);
        // Response to the C-FIND request.
        // The result cannot be accessed until it has been set.
        Dimse findRsp = future.get();

        // Get the list of found objects
        dimseList = future.listPending();

        //>>>> Extract Dataset from Dimse

        datasetVector = new Vector();

        // If no List of DIMSE objects was generated or it is empty return an empty Vector
        if (dimseList == null || dimseList.isEmpty()) {
            return datasetVector;
        }

        // Process all elements
        for (int i = 0; i < dimseList.size(); i++) {
            datasetVector.addElement(((Dimse) dimseList.get(i)).getDataset());
        }

        return datasetVector;
    }

    /**
     * Ask archive to move one DICOM object to the destination (C-MOVE).
     * See PS 3.4 - Annex C QUERY/RETRIEVE SERVICE CLASS.
     *
Use the Study Root Query/Retrieve Information Model to communicate with the archive.
     * See PS 3.4 - C.6.2 Study Root SOP Class Group.
     *
     * @param ds the DICOM object represented as a Dataset.
     * @return a result-code: 0x0000 = SUCCESS sub-operations complete –no failures,
     *                        0xB000 = WARNING sub-operations complete – one or more failures,
     *                        other = errors defined in PS 3.4 - C.4.2.1.5 Status
     * @throws ConnectException
     * @throws InterruptedException
     * @throws IOException
     */
    public int cMOVE(Dataset ds) throws ConnectException, InterruptedException, IOException {
        PresContext pc;

        // An association must be active
        if (aassoc == null) {
            throw new ConnectException("No Association established");
        }

        // Test, if Presentation Context for C-MOVE is supported
        // API doc: Association.getAcceptedPresContext(String asuid, String tsuid)
        if ((pc = aassoc.getAssociation().getAcceptedPresContext(UIDs.StudyRootQueryRetrieveInformationModelMOVE, UIDs.ExplicitVRLittleEndian)) == null &&
                (pc = aassoc.getAssociation().getAcceptedPresContext(UIDs.StudyRootQueryRetrieveInformationModelMOVE, UIDs.ImplicitVRLittleEndian)) == null) {
            throw new ConnectException("Association does not support presentation context for StudyRootQueryRetrieveInformationModelMOVE SOP.");
        }

        // Get the Study Instance UID of the study to mode
        String suid = ds.getString(Tags.StudyInstanceUID);

        // Prepare info for logging
        String patName = ds.getString(Tags.PatientName);
        String patID = ds.getString(Tags.PatientID);
        String studyDate = ds.getString(Tags.StudyDate);
        String prompt = "Study[" + suid + "] from " + studyDate + " for Patient[" + patID + "]: " + patName;

        // log.info("Moving: " + prompt);

        // New Cammand Set, see: DICOM Part 7: Message Exchange, 6.3.1 Command Set Structure
        Command rqCmd = dof.newCommand();
        // API doc: Command.initCMoveRQ(int msgID, String sopClassUID, int priority, String moveDest)
        rqCmd.initCMoveRQ(assoc.nextMsgID(), UIDs.StudyRootQueryRetrieveInformationModelMOVE, priority, dest);
        Dataset rqDs = dof.newDataset();
        rqDs.putCS(Tags.QueryRetrieveLevel, STUDY_LEVEL);
        // Only Unique Key allowed in C-MOVE. PS 3.4 -C.2.2.1 Attribute Types
        rqDs.putUI(Tags.StudyInstanceUID, suid);
        // API doc: AssociationFactorynewDimse(int pcid, Command cmd, Dataset ds)
        // DIMSE (DICOM Message Service Element) ist ein Nachrichtendienst in DICOM
        Dimse moveRq = aFact.newDimse(pc.pcid(), rqCmd, rqDs);

        // Invoke active association with move request Dimse
        FutureRSP future = aassoc.invoke(moveRq);
        // Response to the C-MOVE request.
        // The result cannot be accessed until it has been set.
        Dimse moveRsp = future.get();
        Command rspCmd = moveRsp.getCommand();

        // PS 3.7 - 9.3.4 C-MOVE PROTOCOL, 9.3.4.2 C-MOVE-RSP
        int status = rspCmd.getStatus();
        switch (status) {
            case 0x0000:
                // log.info("Moved: " + prompt);
                break;
            case 0xB000:
                log.error("One or more failures during move of " + prompt);
                break;
            default:
                log.error("Failed to move " + prompt + "\n\terror tstatus: " + Integer.toHexString(status));
                break;
        }
        return status;
    }

    /**
     * Implements the ECHO service. The C-ECHO service is invoked by a DIMSE-service-user
     * to verify end-to-end communications with a peer DIMSE-service-user.
     * See PS 3.7 - 9.1.5 C-ECHO SERVICE
     *
     * @exception ConnectException
     * @exception InterruptedException
     * @exception IOException
     */
    public long cECHO() throws ConnectException, InterruptedException, IOException {
        PresContext pc;
        long t1 = System.currentTimeMillis();

        // An association must be active
        if (aassoc == null) {
            throw new ConnectException("No Association established");
        }

        // Test, if Presentation Context for C-ECHO is supported
        // API doc: Association.getAcceptedPresContext(String asuid, String tsuid)
        if ((pc = aassoc.getAssociation().getAcceptedPresContext(UIDs.Verification, UIDs.ImplicitVRLittleEndian)) == null) {
            throw new ConnectException("Association does not support presentation context: Verification SOP/ImplicitVRLittleEndian.");
        }

        // New Cammand Set, see: DICOM Part 7: Message Exchange, 6.3.1 Command Set Structure
        Command cEchoRQ = oFact.newCommand();
        // API doc: Command.initCEchoRQ(int msgID)
        cEchoRQ.initCEchoRQ(1);

        // API doc: AssociationFactorynewDimse(int pcid, Command cmd)
        // DIMSE (DICOM Message Service Element) ist ein Nachrichtendienst in DICOM
        Dimse echoRq = aFact.newDimse(pc.pcid(), cEchoRQ);

        // PS 3.7 - 9.3.5 C-ECHO PROTOCOL, 9.3.5.2 C-ECHO-RSP
        // Always returns SUCESS result code.
        // Invoke active association with echo request Dimse
        FutureRSP future = aassoc.invoke(echoRq);

        // Response to the C-ECHO request.
        // The result cannot be accessed until it has been set.
        Dimse echoRsp = future.get();
        Command rspCmd = echoRsp.getCommand();

        // PS 3.7 - 9.3.5 C-MOVE PROTOCOL, 9.3.5.2 C-ECHO-RSP
        int status = rspCmd.getStatus();
        switch (status) {
            case 0x0000:
                // Success
                break;
            default:
                log.error("C-ECHO failed: " + Integer.toHexString(status));
                break;
        }

        return System.currentTimeMillis() - t1;
    }

}


text:
namespace vanilla {
class MutexLockGuard {
 public:
   explicit MutexLockGuard(Mutex &m);
   ~MutexLockGuard();

 private:
   MutexLockGuard(const MutexLockGuard &) = delete;
   MutexLockGuard& operator = (const MutexLockGuard &) = delete;
   Mutex &mutex_;
};
}  // namespace vanilla

#endif  // UTILS_MUTEXLOCKGUARD_H_

redpajama_set_name: RedPajamaGithub


text:
import React    from "react"
import { Link } from "react-router"
import Select   from "react-select"

const protocolOptions = [
  { value: 'tcp', label: 'TCP' },
  { value: 'udp', label: 'UDP' }
]

export default class Ports extends React.Component {

  logChange (val) {
    console.log("Selected: ", val)
  }

	render() {
		return (

              Ports

                    Container
                    Protocol
                    Publish
                    Host

                    3306
                    TCP
                    YES
                    3306

                              <button
                                  aria-hidden="true"
                                  data-dismiss="modal"
                                  className="close"
                                  type="button">
                                ×
                              </button>

Edit Port

                              <form className="form-horizontal" role="form">

                                    Container

                                    <input
                                      type="text"
                                      className="form-control"
                                      id="inputContainerPort"
                                      placeholder="Container Port"
                                      defaultValue="3306" />

                                    Protocol

                                    <Select
                                      name="protocol"
                                      value="TCP"
                                      options={protocolOptions}
                                      onChange={this.logChange} />

                                    Publish Port

                                        <input
                                          type="checkbox"
                                          id="inputIsPublished"
                                          defaultChecked="true" />
                                            Yes

                                    Host

                                    <input
                                      type="text"
                                      className="form-control"
                                      id="inputHostPort"
                                      placeholder="Host Port"
                                      defaultValue="3306" />

                                    <button
                                        type="submit"
                                        className="btn btn-block btn-success create-button">
                                      Edit Port
                                    </button>

                              </form>

                Add New Port

                      <button
                          aria-hidden="true"
                          data-dismiss="modal"
                          className="close"
                          type="button">
                        ×
                      </button>

Add New Port

                      <form className="form-horizontal" role="form">

                            Container

                            <input
                              type="text"
                              className="form-control"
                              id="inputContainerPort"
                              placeholder="Container Port" />

                            Protocol

                            <Select
                              name="protocol"
                              value="TCP"
                              options={protocolOptions}
                              onChange={this.logChange} />

                            Publish Port

                                <input
                                    type="checkbox"
                                    id="inputIsPublished" />
                                    Yes

                            Host

                            <input
                              type="text"
                              className="form-control"
                              id="inputHostPort"
                              placeholder="Host Port" />

                            <button
                                type="submit"
                                className="btn btn-block btn-success create-button">
                              Add Port
                            </button>

                      </form>

		)
	}
}


text:
<?php

/*
Plugin Name: LayerSlider WP
Plugin URI: http://codecanyon.net/user/kreatura/
Description: LayerSlider is the most advanced responsive WordPress slider plugin with the famous Parallax Effect and over 200 2D & 3D transitions.
Version: 5.6.5
Author: Kreatura Media
Author URI: http://kreaturamedia.com/
Text Domain: LayerSlider
*/

if(defined('LS_PLUGIN_VERSION') || isset($GLOBALS['lsPluginPath'])) {
	die('ERROR: It looks like you already have one instance of LayerSlider installed. WordPress cannot activate and handle two instanced at the same time, you need to remove the old version first.');
}

if(!defined('ABSPATH')) {
	header('HTTP/1.0 403 Forbidden');
	exit;
}

/********************************************************/
/*                        Actions                       */
/********************************************************/

	// Action to redirect to Layerslider's admin page after activation
	add_action('admin_init', 'layerslider_activation_redirect');

	// Legacy, will be dropped
	$GLOBALS['lsAutoUpdateBox'] = true;

	// Basic configuration
	define('LS_DB_TABLE', 'layerslider');
	define('LS_PLUGIN_VERSION', '5.6.5');

	// Path info
	define('LS_ROOT_FILE', __FILE__);
	define('LS_ROOT_PATH', dirname(__FILE__));
	define('LS_ROOT_URL', plugins_url('', __FILE__));

	// Other constants
	define('LS_PLUGIN_SLUG', basename(dirname(__FILE__)));
	define('LS_PLUGIN_BASE', plugin_basename(__FILE__));
	define('LS_MARKETPLACE_ID', '1362246');
	define('LS_TEXTDOMAIN', 'LayerSlider');
	define('LS_REPO_BASE_URL', 'http://repository.kreaturamedia.com/v3/');

	if(!defined('NL')) { define("NL", "\r\n"); }
	if(!defined('TAB')) { define("TAB", "\t"); }

	// Shared
	include LS_ROOT_PATH.'/wp/scripts.php';
	include LS_ROOT_PATH.'/wp/menus.php';
	include LS_ROOT_PATH.'/wp/hooks.php';
	include LS_ROOT_PATH.'/wp/widgets.php';
	include LS_ROOT_PATH.'/wp/compatibility.php';

	include LS_ROOT_PATH.'/classes/class.ls.posts.php';
	include LS_ROOT_PATH.'/classes/class.ls.sliders.php';
	include LS_ROOT_PATH.'/classes/class.ls.sources.php';

	// Register WP shortcode
	include LS_ROOT_PATH.'/wp/shortcodes.php';
	LS_Shortcode::registerShortcode();

	// Add demo sliders and skins
	LS_Sources::addDemoSlider(LS_ROOT_PATH.'/demos/');
	LS_Sources::addSkins(LS_ROOT_PATH.'/static/skins/');
	LS_Sources::removeSkin('preview');

	// Back-end only
	if(is_admin()) {
		include LS_ROOT_PATH.'/wp/activation.php';
		include LS_ROOT_PATH.'/wp/tinymce.php';
		include LS_ROOT_PATH.'/wp/notices.php';
		include LS_ROOT_PATH.'/wp/actions.php';

	// Front-end only
	} else {

	}

	// Auto update
	if(!class_exists('KM_PluginUpdatesV3')) {
		require_once LS_ROOT_PATH.'/classes/class.km.autoupdate.plugins.v3.php';
	}

		new KM_PluginUpdatesV3(array(
			'repoUrl' => LS_REPO_BASE_URL,
			'root' => LS_ROOT_FILE,
			'version' => LS_PLUGIN_VERSION,
			'itemID' => LS_MARKETPLACE_ID,
			'codeKey' => 'layerslider-purchase-code',
			'authKey' => 'layerslider-authorized-site',
			'channelKey' => 'layerslider-release-channel'
		));

	// Hook to trigger plugin override functions
	add_action('after_setup_theme', 'layerslider_loaded');
	add_action('plugins_loaded', 'layerslider_load_lang');

// Redirect to LayerSlider's main admin page after plugin activation.
// Should not trigger on multisite bulk activation or after upgrading
// the plugin to a newer versions.
function layerslider_activation_redirect() {
	if(get_option('layerslider_do_activation_redirect', false)) {
		delete_option('layerslider_do_activation_redirect');
		if(isset($_GET['activate']) && !isset($_GET['activate-multi'])) {
			wp_redirect(admin_url('admin.php?page=layerslider'));
		}
	}
}

function layerslider_load_lang() {
	load_plugin_textdomain('LayerSlider', false, LS_PLUGIN_SLUG . '/locales/' );
}

/********************************************************/
/*          WPML Layer's String Translation             */
/********************************************************/
function layerslider_register_wpml_strings($sliderID, $data) {

	if(!empty($data['layers']) && is_array($data['layers'])) {
		foreach($data['layers'] as $slideIndex => $slide) {

			if(!empty($slide['sublayers']) && is_array($slide['sublayers'])) {
				foreach($slide['sublayers'] as $layerIndex => $layer) {
					if($layer['type'] != 'img') {
						icl_register_string('LayerSlider WP', '<'.$layer['type'].':'.substr(sha1($layer['html']), 0, 10).'> layer on slide #'.($slideIndex+1).' in slider #'.$sliderID.'', $layer['html']);
					}
				}
			}
		}
	}
}

/********************************************************/
/*                        MISC                          */
/********************************************************/

function layerslider_builder_convert_numbers(&$item, $key) {
	if(is_numeric($item)) {
		$item = (float) $item;
	}
}

function ls_ordinal_number($number) {
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');
    $mod100 = $number % 100;
    return $number . ($mod100 >= 11 && $mod100 <= 13 ? 'th' :  $ends[$number % 10]);
}

function layerslider_check_unit($str) {

	if(strstr($str, 'px') == false && strstr($str, '%') == false) {
		return $str.'px';
	} else {
		return $str;
	}
}

function layerslider_convert_urls($arr) {

	// Global BG
	if(!empty($arr['properties']['backgroundimage']) && strpos($arr['properties']['backgroundimage'], 'http://') !== false) {
		$arr['properties']['backgroundimage'] = parse_url($arr['properties']['backgroundimage'], PHP_URL_PATH);
	}

	// YourLogo img
	if(!empty($arr['properties']['yourlogo']) && strpos($arr['properties']['yourlogo'], 'http://') !== false) {
		$arr['properties']['yourlogo'] = parse_url($arr['properties']['yourlogo'], PHP_URL_PATH);
	}

	if(!empty($arr['layers'])) {
		foreach($arr['layers'] as $key => $slide) {

			// Layer BG
			if(strpos($slide['properties']['background'], 'http://') !== false) {
				$arr['layers'][$key]['properties']['background'] = parse_url($slide['properties']['background'], PHP_URL_PATH);
			}

			// Layer Thumb
			if(strpos($slide['properties']['thumbnail'], 'http://') !== false) {
				$arr['layers'][$key]['properties']['thumbnail'] = parse_url($slide['properties']['thumbnail'], PHP_URL_PATH);
			}

			// Image sublayers
			if(!empty($slide['sublayers'])) {
				foreach($slide['sublayers'] as $subkey => $layer) {
					if($layer['media'] == 'img' && strpos($layer['image'], 'http://') !== false) {
						$arr['layers'][$key]['sublayers'][$subkey]['image'] = parse_url($layer['image'], PHP_URL_PATH);
					}
				}
			}
		}
	}

	return $arr;
}


text:
function showColorInfo(e) {
	var color = e.row.model.color;
	var collection = Alloy.createCollection('color');

	// fetch() color info from the color collection based on the
	// given color from the user model. We can use a plain query string
	// like the commented property, or a prepared statement like the
	// one in use below.
	collection.fetch({
		// query: 'SELECT * FROM colors WHERE color = "' + color + '"'
		query: {
			statement: 'SELECT * FROM colors WHERE color = ?',
			params: [color]
		}
	});
	var colorModel = collection.at(0);

	// open the color info window
	if (colorModel) {
		var win = Alloy.createController('color', colorModel).getView();
		OS_IOS ? Alloy.Globals.navgroup.open(win) : win.open();
	} else {
		alert('No color info found!');
	}
}

Alloy.Collections.user.fetch();


text:
package com.ibm.database.compatibility;

public class TestResult {

	private String language = "java";
	private String client = null;
	private String server = "Informix";
	private String test = null;
	private boolean result;
	private String detail = null;

	public TestResult(String driverName, String testName, boolean result, String detail) {
		this.client = driverName;
		this.test = testName;
		this.result = result;
		this.detail = detail;
	}

	public String getLanguage() {
		return language;
	}

	public String getClient() {
		return client;
	}

	public String getServer() {
		return server;
	}

	public String getTest() {
		return test;
	}

	public boolean getResult() {
		return result;
	}

	public String getDetail() {
		return detail;
	}

}


text:
<?php
namespace Tabloz\MainBundle\Entity;

use Doctrine\ORM\EntityRepository;

class TabloCollectionRepository extends EntityRepository {

	/*public function getLatestTablos($limit = 0, $offset = 0) {
		return $this->createQueryBuilder('t')
		->where('t.enable = 1')
		->andWhere('t.private = 0')
		->orderBy('t.published_at', 'DESC')
		->setFirstResult( $offset )
		->setMaxResults( $limit )
    	->getQuery()
    	->getResult();
	}

	public function getPopularTablos($limit = 0, $offset = 0) {
		return $this->createQueryBuilder('t')
		->where('t.enable = 1')
		->andWhere('t.private = 0')
		->orderBy('t.favorite_count', 'DESC')
		->addOrderBy('t.view_count', 'DESC')
		->setFirstResult( $offset )
		->setMaxResults( $limit )
		->getQuery()
		->getResult();
	}

	public function getPopularWeekTablos($limit = 0, $offset = 0) {
		$last_week = date('Y-m-d H:i:s', strtotime('-1 week'));
		return $this->createQueryBuilder('t')
		->where('t.enable = 1')
		->andWhere('t.private = 0')
		->andWhere('t.published_at >= :last_week')->setParameter('last_week', $last_week)
		->addOrderBy('t.favorite_count', 'DESC')
		->addOrderBy('t.view_count', 'DESC')
		->setFirstResult( $offset )
		->setMaxResults( $limit )
		->getQuery()
		->getResult();
	}

	public function getLatestPopularTablos($limit = 0, $offset = 0) {
		return $this->createQueryBuilder('t')
		->where('t.enable = 1')
		->andWhere('t.private = 0')
		->orderBy('t.published_at', 'DESC')
		->addOrderBy('t.favorite_count', 'DESC')
		->addOrderBy('t.view_count', 'DESC')
		->setFirstResult( $offset )
		->setMaxResults( $limit )
		->getQuery()
		->getResult();
	}

	public function getTablos($category_descriptor = 'all', $order = 'latest', $limit = 0, $offset = 0) {
		$query = $this->createQueryBuilder('t');
		$query->where('t.enable = 1')
		->andWhere('t.private = 0');
		if ($category_descriptor != 'all'){
			$query->innerJoin('t.category', 'tc', 'WITH', 'tc.descriptor = :descriptor')->setParameter('descriptor', $category_descriptor);
		}
		if ($order == 'latest'){
			$query->orderBy('t.published_at', 'DESC');
		} elseif ($order == 'popular_all_time') {
			$query->orderBy('t.favorite_count', 'DESC')
			->addOrderBy('t.view_count', 'DESC');
		} elseif ($order == 'latest_popular') {
			$query->orderBy('t.published_at', 'DESC')
			->addOrderBy('t.favorite_count', 'DESC')
			->addOrderBy('t.view_count', 'DESC');
		}
		$query->setFirstResult( $offset )
		->setMaxResults( $limit );
		return $query->getQuery()->getResult();
	}*/

	function search($text, $order = 'latest', $limit = 0, $offset = 0){
		$search_fields = array('title');
		$criteria = array();
		foreach($search_fields as $field){
			if( isset( $this->_class->fieldNames[$field] ) && !empty($text) ){
				$criteria[$field] = explode(' ', $text);
			}
		}
		if(empty($criteria)){
			return null;
		}
		$alias = "t";
		$query = $this->createQueryBuilder($alias);
		//andx is used to build a WHERE clause like (expression 1 AND expression 2)
		//Alternatively you can use orx for (expression 1 OR expression 2)
		//Also you can next either inside of each other...so ->where(andx(orx("expression1","expression2),"expression3"))
		//would be WHERE ( ( expression 1 OR expression 2 ) AND expression 3  )
		$or = $query->expr()->orx();
		/**
		 *@note Example of programmatic Doctrine2 Like expression
		*/
		foreach($criteria as $key => $arr){
			foreach ($arr as $value){
				$or->add($query->expr()->like("{$alias}.{$key}", ":{$key}" ));
				$query->setParameter($key, "%{$value}%");
			}
		}
		$query->where($or)
		->andWhere('t.enable = 1')
		->andWhere('t.private = 0');
		if ($order == 'latest'){
			$query->orderBy('t.updated_at', 'DESC');
		} elseif ($order == 'popular_all_time') {
			$query//->orderBy('t.favorite_count', 'DESC')
			->addOrderBy('t.view_count', 'DESC');
		} elseif ($order == 'latest_popular') {
			$query->orderBy('t.updated_at', 'DESC')
			//->addOrderBy('t.favorite_count', 'DESC')
			->addOrderBy('t.view_count', 'DESC');
		}
		$query->setFirstResult( $offset )
		->setMaxResults( $limit );
		return $query->getQuery()->getResult();
	}
}


text:
require 'faraday'

module Truck
  def agent
    @agent ||= Agent.new
  end

  class << self
    attr_writer :configuration
  end

  def self.configuration
    @configuration ||= Configuration.new
  end

  def self.configure
    yield(configuration)
  end

  class Configuration
    attr_accessor :host, :agent
  end

  class Agent
    def deliver agent = {}, payload = {}
      connection.post "", agent.merge(payload)
    end

    def connection
      @connection ||= Faraday.new(:url => "http://#{Truck.configuration.host}") do |faraday|
        faraday.request  :url_encoded             # form-encode POST params
        faraday.response :logger                  # log requests to STDOUT
        faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
      end
    end
  end

end


text:
package org.trustedanalytics.sparktk.frame.internal.constructors

import org.apache.commons.lang.StringUtils
import org.apache.spark.SparkContext
import org.trustedanalytics.sparktk.frame._
import org.apache.spark.sql.types.{ StructType, StructField }
import org.trustedanalytics.sparktk.frame.{ DataTypes, Schema, Frame }
import org.trustedanalytics.sparktk.frame.internal.rdd.FrameRdd

object Import {

  /**
   * Creates a frame by importing data from a CSV file
   *
   * @param path Full path to the csv file
   * @param delimiter A string which indicates the separation of data fields.  This is usually a single
   *                  character and could be a non-visible character, such as a tab. The default delimiter
   *                  is a comma (,).
   * @param header Boolean value indicating if the first line of the file will be used to name columns,
   *               and not be included in the data.  The default value is false.
   * @param inferSchema Boolean value indicating if the column types will be automatically inferred.  It
   *                    requires one extra pass over the data and is false by default.
   * @param dateTimeFormat String specifying how date/time columns are formatted, using the java.text.SimpleDateFormat
   * specified at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
   * @return Frame with data from the csv file
   */
  def importCsv(sc: SparkContext,
                path: String,
                delimiter: String = ",",
                header: Boolean = false,
                inferSchema: Boolean = false,
                schema: Option[Schema] = None,
                dateTimeFormat: String = "yyyy-MM-dd'T'HH:mm:ss.SSSX"): Frame = {

    // If a custom schema is provided there's no reason to infer the schema during the load
    val loadWithInferSchema = if (schema.isDefined) false else inferSchema

    // Load from csv
    import org.apache.spark.sql.SQLContext
    val sqlContext = new SQLContext(sc)
    val headerStr = header.toString.toLowerCase
    val inferSchemaStr = inferSchema.toString.toLowerCase

    var dfr = sqlContext.read.format("com.databricks.spark.csv.org.trustedanalytics.sparktk")
      .option("header", headerStr)
      .option("inferSchema", inferSchemaStr)
      .option("delimiter", delimiter)
      .option("dateFormat", dateTimeFormat)

    if (!inferSchema && schema.isDefined) {
      dfr = dfr.schema(StructType(schema.get.columns.map(column =>
        StructField(column.name, FrameRdd.schemaDataTypeToSqlDataType(column.dataType), true))))
    }

    val df = dfr.load(path)
    val frameRdd = FrameRdd.toFrameRdd(df)

    if (schema.isDefined) {
      val numSpecifiedColumns = schema.get.columns.length
      val numColumnsFromLoad = frameRdd.frameSchema.columns.length
      if (numSpecifiedColumns != numColumnsFromLoad)
        throw new IllegalArgumentException("""The number of columns specified in the schema ($numSpecifiedColumns) does
                                           not match the number of columns found in the csv file ($numColumnsFromLoad).""")
    }
    val frameSchema = if (schema.isDefined) schema.get else frameRdd.frameSchema

    new Frame(frameRdd, frameSchema)
  }

  /**
   * Creates a frame by importing data from a parquet file
   *
   * @param path Full path to the parquet file
   */
  def importParquet(sc: SparkContext, path: String): FrameRdd = {
    val sqlContext = new org.apache.spark.sql.SQLContext(sc)
    val df = sqlContext.read.parquet(path)
    FrameRdd.toFrameRdd(df)
  }

  /**
   * Load data from hbase table into frame
   *
   * @param tableName hbase table name
   * @param schema hbase schema as a list of tuples (columnFamily, columnName, dataType for cell value)
   * @param startTag optional start tag for filtering
   * @param endTag optional end tag for filtering
   * @return frame with data from hbase table
   */
  def importHbase(sc: SparkContext,
                  tableName: String,
                  schema: Seq[Seq[String]],
                  startTag: Option[String] = None,
                  endTag: Option[String] = None): Frame = {

    require(StringUtils.isNotEmpty(tableName), "hbase name is required")
    require(schema != null, "hbase table schema cannot be null")
    require(startTag != null, "hbase table startTag cannot be null")
    require(endTag != null, "hbase table endTag cannot be null")

    //Map seq[seq[string]] to List[HBaseSchemaArgs]
    val finalSchema: Seq[HBaseSchemaArgs] = schema.map(item => HBaseSchemaArgs(item(0), item(1), DataTypes.toDataType(item(2))))
    val hBaseRdd = HbaseHelper.createRdd(sc, tableName, finalSchema.toVector, startTag, endTag).map(DataTypes.parseMany(finalSchema.map(_.dataType).toArray))
    val hBaseSchema = new FrameSchema(finalSchema.toVector.map {
      case x => Column(x.columnFamily + "_" + x.columnName, x.dataType)
    })
    val frameRdd = FrameRdd.toFrameRdd(hBaseSchema, hBaseRdd)
    new Frame(frameRdd, frameRdd.frameSchema)
  }

  /**
   * Loads data from given jdbc table into frame
   *
   * @param connectionUrl : Jdbc connection url to connect to database
   * @param tableName :Jdbc table name to import
   * @return Frame with data from jdbc table
   */
  def importJdbc(sc: SparkContext, connectionUrl: String, tableName: String): Frame = {

    require(StringUtils.isNotEmpty(connectionUrl), "connection url is required")
    require(StringUtils.isNotEmpty(tableName), "table name is required")

    // Load from jdbc table
    import org.apache.spark.sql.SQLContext
    val sqlContext = new SQLContext(sc)

    val sqlDataframe = sqlContext.read.format("jdbc")
      .option("url", connectionUrl)
      .option("dbtable", tableName)
      .load()

    val frameRdd = FrameRdd.toFrameRdd(sqlDataframe)
    new Frame(frameRdd, frameRdd.frameSchema)
  }

  /**
   * Loads data from hive using given hive query
   *
   * @param hiveQuery hive query
   * @return Frame with data based on hiveQL query
   */
  def importHive(sc: SparkContext, hiveQuery: String): Frame = {

    require(StringUtils.isNotEmpty(hiveQuery), "hive query is required")

    //Load data from hive using given hiveQL query
    val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
    val sqlDataframe = sqlContext.sql(hiveQuery)
    val frameRdd = FrameRdd.toFrameRdd(sqlDataframe)
    new Frame(frameRdd, frameRdd.frameSchema)
  }
}


text:
{% extends "settings/base_template.html" %}
{% load url from future %}
{% load hqstyle_tags %}
{% load hq_shared_tags %}
{% load i18n %}

{% block js-inline %} {{ block.super }}

{% endblock %}

{% block main_column %}

<button type="button" id="load-all-btn" class="btn btn-primary">{% trans 'Load EVERYTHING' %}</button>

        {% for calc_tag in order %}

                {{ calcs|dict_lookup:calc_tag }}

                        <button class="btn btn-info load-calc-btn" data-calc-tag="{{ calc_tag }}">
                            {% trans "Load Property" %}
                        </button>

        {% endfor %}

{% endblock %}


text:
#import <Foundation/Foundation.h>
#import <libARDiscovery/ARDISCOVERY_Error.h>
#import <libARDiscovery/ARDISCOVERY_Discovery.h>

@class USBAccessoryManager;

/**
 internal USBAccessoryManager category to notify delegate
 */
@interface USBAccessoryManager (USBAccessoryManagerImpl)
-(void)notifyDidAddDeviceWithConnectionId:(NSUInteger)connectionId name:(NSString *)name mux:(struct mux_ctx *)mux serial:(NSString *)serial productType:(eARDISCOVERY_PRODUCT)productType;
- (void)notifyDidRemoveDeviceWithConnectionId:(NSUInteger)connectionId;
@end

/**
 Protocol defining a USBAccessoryManager implementation
 */
@protocol USBAccessoryManagerImpl <NSObject>
@required
- (eARDISCOVERY_ERROR)muxDiscoveryConnect:(NSString*)name model:(NSString*)model deviceId:(NSString*)serial json:(NSString*)jsonStr callback:(void (^)(uint32_t status, const char* json))connectionCbBlock;
- (void)muxDiscoveryCancelConnect;
- (void)delegateDidChange;
@end

/**
 Real implementation based on External Accessory
 */
@interface USBAccessoryManagerEA : NSObject <USBAccessoryManagerImpl>
- (instancetype)initWithOwner:(USBAccessoryManager*)owner;
@end

/**
 Debug implementation using mux proxy on ip
 */
@interface USBAccessoryManagerProxy : NSObject <USBAccessoryManagerImpl>
- (instancetype)initWithOwner:(USBAccessoryManager*)owner ipAddr:(NSString*)ipAddr;
@end


text:
package org.socraticgrid.hl7.services.orders.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.socraticgrid.hl7.services.orders.dao.OrderCatalogDao;
import org.socraticgrid.hl7.services.orders.interfaces.OrderCatalogQueryIFace;
import org.socraticgrid.hl7.services.orders.model.CatalogItem;
import org.socraticgrid.hl7.services.orders.model.CatalogItemTree;
import org.socraticgrid.hl7.services.orders.model.CatalogItemType;
import org.socraticgrid.hl7.services.orders.model.Order;
import org.socraticgrid.hl7.services.orders.model.OrderModel;
import org.socraticgrid.hl7.services.orders.model.primatives.Identifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderCatalogQueryImpl implements OrderCatalogQueryIFace {

	private final Logger logger = LoggerFactory
			.getLogger(OrderCatalogQueryImpl.class);

	@Autowired
	private OrderCatalogDao orderCatalogDao;

	@Override
	public CatalogItem getItemDetail(Identifier itemId) {
		CatalogItem catalogItem = null;
		try {
			catalogItem = orderCatalogDao.getItemDetail(itemId);
			logger.debug("CatalogItem : " + catalogItem);
		} catch (Exception e) {
			logger.error(
					"Some error occurred while fetching Item Detail from database! Reason : "
							+ e.getMessage(), e);
		}
		return catalogItem;
	}

	@Override
	public <T extends Order> OrderModel<T> getItemPrototype(Identifier itemId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CatalogItemTree queryItemTree(Identifier itemId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CatalogItemType> queryItemTypes(String query) {
		List<CatalogItemType> result = new ArrayList<CatalogItemType>();
		try {
			result = orderCatalogDao.getAllCatalogItemTypes();
			logger.debug("CatalogItemTypes : " + result);
		} catch (Exception e) {
			logger.error(
					"Some error occurred while fetching Catalog Item Types from database! Reason : "
							+ e.getMessage(), e);
		}
		return result;
	}

}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Digital Media || Responsive HTML 5 item</title>

	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link rel="stylesheet" href="css/style.css">
	<link rel="stylesheet" href="css/responsive.css">

Best Digital Marketing Theme Forever!

					login
					register

					<select class="selectpicker" title="Language">
					  <option>English</option>
					  <option>Arabic</option>
					  <option>Hindi</option>
					</select>

					Home

Home One

Home Two

Home Three

About

					Services

Web Development

Web Design & Development Solutions

 Content Marketing

 Web Design

 Web Development

 Mobile Marketing

 Digital Consultancy

 Reputation Marketing

Online Marketing

Get More Traffic Boost Your Sales

 Search Engine Optimization

 Pay Per Click

 Local Seo

 Social Media Marketing

 Email Marketing

Sales Improvment

We do targeting for getting audience

 Conversation Rate Optimization

 Online Presense Analysis

 Affiliate Marketing

					Case Studies

Case Studies Masonary

Case Studies Sidebar

Case Studies 3 Col

Case Studies 5 Col

Case Studies Details

					Pages

Pricing Package

					News

News Details

Contact

					   			<form action="#" class="clearfix">
					   				<input type="text" class="pull-left" placeholder="Type Something"/>
					   				<button class="pull-right" type="submit"></button>
					   			</form>

Services

Home

Services

Pay Per Click

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

					Read More

Pay Per Click

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

					Read More

Pay Per Click

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

					Read More

Search Engine Optimization

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

					Read More

Keyword Analysis

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

					Read More

Email Marketing

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

					Read More

Words Form Our Clients

"We enjoy sharing the projects and posts we make just as much
 as we enjoy creating them. Sit back & take a moment to browse through
 some of our recent completed work."

Rick Grimes

				CEO-Founder

Our Work Process

Grow your business and save time with seamless experience

Planning

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

Design & Develpoment

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

Final Product

Duis eget purus non est pellentesque egestas Maecenas venenatis ante urna tincidunt viverra quam mattisat pellentesque tempor

Do you need more SEO Analytics?

We have larger plans made specifically for agency and enterprise use.

			Learn More

The first mate and his Skipper too will do their very best to make the others comfortable in their tropic island nest. Fleeing from the Cylon tyranny

Contact Us

Address

DigitalMedia Inc, 06 Highley St,
Victoria, Australia.

Email Us

Info@Digitalmedia.Com
Support@Digital Media.Com

Call Us

+(10) 123 456 7896

Quick Links

SEO

PPC

Web Analytics

Social Media

Web Design

Development

Contant Marketing

KeyWord Analytics

Email Marketing

Pay Per Click

Subscribe Us

Signup for our mailing list to get latest
updates and news.

	                        <input type="email" placeholder="Email Address">
	                        <button type="submit" class="message"></button>

Your Email id is confidential!

© 2016 All Rights Reserved

Home

about

Services

Case Studies

privacy policy

Terms&condition


text:
//----------------------------------------------------------------------------
// Copyright (C) 2004  Yasser EL-Manzalawy.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Contact the Author:
// Yasser EL-Manzalawy
// e-mail: ymelmanz@yahoo.com
//----------------------------------------------------------------------------

/*
 * Project: GraphPlan 1.0
 * Class:   graphplan.Action
 *
 * Date:    2004-03-31
 *
 * Author:  Yasser EL-Manzalawy
 * Email:   ymelmanz@yahoo.com
 */

package graphplan;

import java.util.*;

/**
 * Class Action.
 *
 * @author  Yasser EL-Manzalawy
 */
public class Action {

    // ------------------------------------------------------------------------
    // --- fields                                                           ---
    // ------------------------------------------------------------------------
    /**
     * The pre condition.
     */
    private Conjunction preCondition;

    /**
     * The add effects.
     */
    private Conjunction addEffects;

    /**
     * The del effects.
     */
    private Conjunction delEffects;

    /**
     * The head.
     */
    private String head;

    /**
     * The op type.
     */
    private int opType;

    /**
     * The mutex ops.
     */
    private Vector mutexOps;

    /**
     * The pre props.
     */
    private Vector preProps;

    /**
     * The add props.
     */
    private Vector addProps;

    /**
     * The del props.
     */
    private Vector delProps;

    // ------------------------------------------------------------------------
    // --- constructors                                                     ---
    // ------------------------------------------------------------------------
    /**
     * Creates a new instance of Action.
     *
     * @param theHead The the head.
     * @param thePre The the pre.
     * @param theAdd The the add.
     * @param theDel The the del.
     */
    public Action(String theHead, String thePre, String theAdd, String theDel) {
        opType = 0;
        head = theHead;
        preCondition = new Conjunction (thePre);
        addEffects = new Conjunction (theAdd);
        delEffects = new Conjunction (theDel);
        init();
    }

    /**
     * Creates a new instance of Action.
     *
     * @param name The name.
     */
    public Action(String name) {
        head = name;
        opType = 1;
        preCondition = new Conjunction ();
        addEffects = new Conjunction ();
        delEffects = new Conjunction ();
        init();
    }

    // ------------------------------------------------------------------------
    // --- methods                                                          ---
    // ------------------------------------------------------------------------
    /**
     * Returns the header.
     *
     * @return  The header.
     */
    public String getHeader() {
        return head;
    }

    /**
     * Returns the type.
     *
     * @return  The type.
     */
    public int getType() {
        return opType;
    }

    /**
     * Returns the pre conditions.
     *
     * @return  The pre conditions.
     */
    public Conjunction getPreConditions() {
        return preCondition;
    }

    /**
     * Sets the pre conditions.
     *
     * @param conjunction The pre conditions.
     */
    public void setPreConditions(Conjunction conjunction) {
        preCondition = conjunction;
    }

    /**
     * Returns the pre props.
     *
     * @return  The pre props.
     */
    public Vector getPreProps() {
        return preProps;
    }

    /**
     * Returns the add effects.
     *
     * @return  The add effects.
     */
    public Conjunction getAddEffects() {
        return addEffects;
    }

    /**
     * Sets the add effects.
     *
     * @param conjunction The add effects.
     */
    public void setAddEffects(Conjunction conjunction) {
        addEffects = conjunction;
    }

    /**
     * Returns the add props.
     *
     * @return  The add props.
     */
    public Vector getAddProps() {
        return addProps;
    }

    /**
     * Returns the del effects.
     *
     * @return  The del effects.
     */
    public Conjunction getDelEffects() {
        return delEffects;
    }

    /**
     * Sets the del effects.
     *
     * @param conjunction The del effects.
     */
    public void setDelEffects(Conjunction conjunction) {
        delEffects = conjunction;
    }

    /**
     * Returns the del props.
     *
     * @return  The del props.
     */
    public Vector getDelProps() {
        return delProps;
    }

    /**
     * Returns the mutex ops.
     *
     * @return  The mutex ops.
     */
    public Vector getMutexOps() {
        return mutexOps;
    }

    /**
     * Sets the mutex ops.
     *
     * @param vector The mutex ops.
     */
    public void setMutexOps(Vector vector) {
        mutexOps = vector;
    }

    /**
     * Adds a mutex op.
     *
     * @param action The action.
     */
    public void addMutexOp(Action action) {
        if(!mutexOps.contains(action))
        {
            mutexOps.addElement(action);
            action.getMutexOps().addElement(this);
        }
    }

    /**
     * Returns the mutex op.
     *
     * @param i The int.
     * @return  The mutex op.
     */
    public Action getMutexOp(int i) {
        return (Action)mutexOps.elementAt(i);
    }

    /**
     * Tests if ...
     *
     * @param action The action.
     * @return  The boolean.
     */
    public boolean isMutex(Action action) {
        return mutexOps.contains(action);
    }

    /**
     * Adds a pre prop.
     *
     * @param proposition The proposition.
     */
    public void addPreProp(Proposition proposition) {
        preProps.addElement(proposition);
    }

    /**
     * Adds a add prop.
     *
     * @param proposition The proposition.
     */
    public void addAddProp(Proposition proposition) {
        addProps.addElement(proposition);
    }

    /**
     * Adds a del prop.
     *
     * @param proposition The proposition.
     */
    public void addDelProp(Proposition proposition) {
        addProps.addElement(proposition);
    }

    /**
     * Returns the pre prop.
     *
     * @param i The int.
     * @return  The pre prop.
     */
    public Proposition getPreProp(int i) {
        return (Proposition)preProps.elementAt(i);
    }

    /**
     * ...
     *
     * @param i The int.
     * @return  The proposition.
     */
    public Proposition getaddProp(int i) {
        return (Proposition)addProps.elementAt(i);
    }

    /**
     * ...
     *
     * @param i The int.
     * @return  The proposition.
     */
    public Proposition delPreProp(int i) {
        return (Proposition)delProps.elementAt(i);
    }

    /**
     * ...
     *
     * @return  The string.
     */
    public String toString() {
        String s = head + "\n Mutex With: ";
        int len = mutexOps.size();
        for (int i = 0; i <len; i++)
        {
            Action act = (Action) mutexOps.elementAt(i);
            s += act.getHeader() + ", ";
        }
        return s;
    }

    /**
     * ...
     */
    private void init() {
        mutexOps = new Vector();
        preProps = new Vector();
        addProps = new Vector();
        delProps = new Vector();
    }

} // end Action


text:
package com.intellij.execution.impl;

import com.intellij.execution.ExecutionManager;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ScriptRunnerUtil;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;

import java.util.List;
import java.util.Objects;

public class ExecutionTestUtil {
  private ExecutionTestUtil() {
  }

  @NotNull
  public static RunContentDescriptor getSingleRunContentDescriptor(@NotNull ExecutionManager executionManager) {
    List<RunContentDescriptor> descriptors = ((ExecutionManagerImpl)executionManager).getRunningDescriptors(Conditions.alwaysTrue());
    String actualDescriptorsMsg = stringifyDescriptors(descriptors);
    Assert.assertEquals(actualDescriptorsMsg, 1, descriptors.size());
    RunContentDescriptor descriptor = ContainerUtil.getFirstItem(descriptors);
    return Objects.requireNonNull(descriptor);
  }

  public static void terminateAllRunningDescriptors(@NotNull ExecutionManager executionManager) {
    List<RunContentDescriptor> descriptors = ((ExecutionManagerImpl)executionManager).getRunningDescriptors(Conditions.alwaysTrue());
    for (RunContentDescriptor descriptor : descriptors) {
      ProcessHandler processHandler = descriptor.getProcessHandler();
      if (processHandler != null) {
        ScriptRunnerUtil.terminateProcessHandler(processHandler, 0, null);
      }
    }
  }

  @NotNull
  private static String stringifyDescriptors(@NotNull List<? extends RunContentDescriptor> descriptors) {
    return "Actual descriptors: " + StringUtil.join(descriptors, descriptor -> {
      if (descriptor == null) {
        return "null";
      }
      ProcessHandler processHandler = descriptor.getProcessHandler();
      return String.format("[%s, %s]",
                           descriptor.getDisplayName(),
                           processHandler != null ? processHandler.getClass().getName() : null);
    }, ", ");
  }
}


text:
using namespace v8;

std::vector<CassLogMessage> queue_;
uv_async_t* async_ = NULL;
uv_mutex_t lock_;
NanCallback* callback_;

void on_log_message(const CassLogMessage* message, void* data)
{
    uv_mutex_lock(&lock_);
    queue_.push_back(*message);
    uv_mutex_unlock(&lock_);
    uv_async_send(async_);
}

void
#if UV_VERSION_MAJOR == 0
async_ready(uv_async_t* handle, int status)
#else
async_ready(uv_async_t* handle)
#endif
{
    NanScope();
    uv_mutex_lock(&lock_);

    for (size_t i = 0; i < queue_.size(); i++) {
        CassLogMessage* log = &queue_[i];
        Local<Object> info = NanNew<Object>();

        static PersistentString time_ms("time_ms");
        static PersistentString severity("severity");
        static PersistentString message("message");

        info->Set(time_ms.handle(), NanNew<Number>(log->time_ms));
        info->Set(severity.handle(), NanNew<String>(cass_log_level_string(log->severity)));
        info->Set(message.handle(), NanNew<String>(log->message));

        Handle<Value> argv[] = {
            NanNull(),
            info
        };
        callback_->Call(2, argv);
    }
    queue_.clear();

    uv_mutex_unlock(&lock_);
}

NAN_METHOD(SetLogCallback) {
    NanScope();

    if (callback_) {
        return NanThrowError("callback already registered");
    }

    if (args.Length() != 1) {
        return NanThrowError("missing required argument: callback");
    }
    callback_ = new NanCallback(args[0].As<Function>());
    if (! callback_) {
        return NanThrowError("callback is not a function");
    }

    uv_mutex_init(&lock_);

    async_ = new uv_async_t();
    uv_async_init(uv_default_loop(), async_, async_ready);

    cass_log_set_callback(on_log_message, NULL);

    NanReturnNull();
}

NAN_METHOD(SetLogLevel) {
    NanScope();
    if (args.Length() != 1) {
        return NanThrowError("missing required argument: level");
    }

    String::Utf8Value level_str(args[0].As<String>());

    CassLogLevel level = CASS_LOG_DISABLED;

    // The cassandra.h API includes a CASS_LOG_LEVEL_MAP macro that defines
    // the log level enum values and corresponding strings.
    //
    // Take advantage of that to verify and convert the level argument string.
    if (false) {}
#define CONVERT(_level, _str) \
    else if (!strcasecmp(*level_str, _str)) { \
        level = _level; \
    }
    CASS_LOG_LEVEL_MAP(CONVERT)
    else {
        return NanThrowError("invalid level");
    }

    cass_log_set_level(level);

    NanReturnNull();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Podospora absimilis Cain

### Remarks
null


text:
package pl.wurmonline.deedplanner.graphics;

import com.jogamp.opengl.GL2;
import org.joml.Vector2f;
import org.joml.Vector2i;
import org.joml.Vector3d;
import pl.wurmonline.deedplanner.*;
import pl.wurmonline.deedplanner.data.Map;
import pl.wurmonline.deedplanner.data.Tile;
import pl.wurmonline.deedplanner.input.*;
import pl.wurmonline.deedplanner.logic.TileFragment;

public final class UpCamera implements Camera {

    private static final float TILE_TO_SCREEN_RATIO = 4.0f;
    private static final float SCREEN_TO_TILE_RATIO = 1.0f / TILE_TO_SCREEN_RATIO;

    private static final int OFFSCREEN_TILES_RENDERED = 3;

    public float x=0;
    public float y=0;

    public Tile tile;
    public float xTile;
    public float yTile;
    public float xMap;
    public float yMap;

    private float tileScaler;

    public void update(MapPanel panel, Mouse mouse, Keybindings keybindings) {
        Map map = panel.getMap();

        tileScaler = (float) panel.getWidth() / panel.getHeight();

        float screenTileSize = (float) panel.getHeight() / Properties.scale;
        float tileSize = screenTileSize * SCREEN_TO_TILE_RATIO;
        float tileX = ((mouse.x + x * tileSize) / ((float) panel.getWidth() / Properties.scale / tileScaler));
        float tileY = (((panel.getHeight() - mouse.y) + y * tileSize) / ((float) panel.getHeight() / Properties.scale));

        double keyboardFraction = Properties.keyboardFractionUp;
        if (keybindings.hold(Keybindings.UP_SPEED_MOD1)) {
            keyboardFraction *= Properties.mod1Fpp;
        }
        else if (keybindings.hold(Keybindings.UP_SPEED_MOD2)) {
            keyboardFraction *= Properties.mod2Fpp;
        }

        if (mouse.scrollDown || keybindings.pressed(Keybindings.UP_SCALE_MORE)) {
            if (Properties.scale > 5) {
                x += (tileX - x * tileSize / ((float) panel.getWidth() / Properties.scale / tileScaler)) * TILE_TO_SCREEN_RATIO / Properties.scale;
                y += (tileY - y * tileSize / ((float) panel.getHeight() / Properties.scale)) * TILE_TO_SCREEN_RATIO / Properties.scale;
                Properties.scale--;
            }
        }
        else if (mouse.scrollUp || keybindings.pressed(Keybindings.UP_SCALE_LESS)) {
            if (Properties.scale < 200) {
                Properties.scale++;
            }
        }

        int currX = (int) tileX;
        int currY = (int) tileY;

        if (currX >= 0 && currX < map.getWidth() && currY >= 0 && currY < map.getHeight()) {
            tile = map.getTile(currX, currY);
            xMap = tileX;
            yMap = tileY;
            xTile = tileX%1f;
            yTile = tileY%1f;
        }
        else {
            tile = null;
        }

        if (mouse.pressed.middle) {
            mouse.setGrabbed(true);
        }
        else if (mouse.hold.middle) {
            x -= mouse.diffX * Properties.mouseFractionUp;
            y += mouse.diffY * Properties.mouseFractionUp;
        }
        else if (mouse.released.middle && !mouse.hold.middle) {
            mouse.setGrabbed(false);
        }

        if (keybindings.hold(Keybindings.UP_MOVE_UP)) {
            y += keyboardFraction;
        }
        if (keybindings.hold(Keybindings.UP_MOVE_DOWN)) {
            y -= keyboardFraction;
        }

        if (keybindings.hold(Keybindings.UP_MOVE_RIGHT)) {
            x += keyboardFraction;
        }
        if (keybindings.hold(Keybindings.UP_MOVE_LEFT)) {
            x -= keyboardFraction;
        }

        float totalWidth = map.getWidth() * screenTileSize;
        float totalHeight = map.getHeight() * screenTileSize;
        boolean fitsHorizontally = totalWidth < panel.getWidth();
        boolean fitsVertically = totalHeight < panel.getHeight();

        if (x < 0 && !fitsVertically) {
            x = 0;
        }
        if (y < 0 && !fitsVertically) {
            y = 0;
        }

        if (x > 4 * (map.getWidth() - Properties.scale * tileScaler) && !fitsVertically) {
            x = 4 * (map.getWidth() - Properties.scale * tileScaler);
        }
        if (y > 4 * (map.getHeight() - Properties.scale) && !fitsVertically) {
            y = 4 * (map.getHeight() - Properties.scale);
        }

        if (fitsHorizontally) {
            float tilesOnScreen = panel.getWidth() / screenTileSize;
            float unboundTiles = tilesOnScreen - map.getWidth();
            x = -unboundTiles / 2 * TILE_TO_SCREEN_RATIO;
        }
        if (fitsVertically) {
            float tilesOnScreen = panel.getHeight() / screenTileSize;
            float unboundTiles = tilesOnScreen - map.getHeight();
            y = -unboundTiles / 2 * TILE_TO_SCREEN_RATIO;
        }
    }

    public void set(GL2 g, MapPanel panel) {
        g.glMatrixMode(GL2.GL_PROJECTION);
        g.glLoadIdentity();
        g.glOrtho(0, Properties.scale * TILE_TO_SCREEN_RATIO * (float)panel.getWidth() / (float)panel.getHeight(), 0, Properties.scale * TILE_TO_SCREEN_RATIO, 0.001f, 8192);
        g.glTranslatef(-x, -y, -4000);
        g.glMatrixMode(GL2.GL_MODELVIEW);
        g.glLoadIdentity();
    }

    public void reset() {
        x=0;
        y=0;
    }

    public boolean isEditingCapable() {
        return true;
    }

    public Tile getHoveredTile() {
        return tile;
    }

    public TileFragment getHoveredTileFragment() {
        return TileFragment.calculateTileFragment(xTile, yTile);
    }

    public Vector2f getHoveredTilePosition() {
        return new Vector2f(xTile, yTile);
    }

    public float getLevelVisibility(int level) {
        switch (Math.abs(Globals.floor) - Math.abs(level)) {
            case 0:
                return 1;
            case 1:
                return 0.6f;
            case 2:
                return 0.25f;
            default:
                return 0;
        }
    }

    public Vector2i getLowerRenderBounds() {
        int currX = (int) (x * SCREEN_TO_TILE_RATIO);
        int currY = (int) (y * SCREEN_TO_TILE_RATIO);

        return new Vector2i(currX - OFFSCREEN_TILES_RENDERED, currY - OFFSCREEN_TILES_RENDERED);
    }

    public Vector2i getUpperRenderBounds() {
        int currX = (int) (x * SCREEN_TO_TILE_RATIO);
        int currY = (int) (y * SCREEN_TO_TILE_RATIO);

        int upperXBound = currX + (int) (Properties.scale * tileScaler) + OFFSCREEN_TILES_RENDERED;
        int upperYBound = currY + Properties.scale + OFFSCREEN_TILES_RENDERED;
        return new Vector2i(upperXBound, upperYBound);
    }

    public boolean isSkyboxRendered() {
        return false;
    }

    public CameraType getCameraType() {
        return CameraType.TOP_VIEW;
    }

    public Vector3d getPosition() {
        return new Vector3d(xMap, yMap, 0);
    }

}


text:
/* globals __non_webpack_require__ */

let fs = __non_webpack_require__('fs');
let http = __non_webpack_require__('http');
let https = __non_webpack_require__('https');
let url = __non_webpack_require__('url');

import {
  AbortException, assert, createPromiseCapability
} from '../shared/util';
import { validateRangeRequestCapabilities } from './network_utils';

class PDFNodeStream {
  constructor(source) {
    this.source = source;
    this.url = url.parse(source.url);
    this.isHttp = this.url.protocol === 'http:' ||
                  this.url.protocol === 'https:';
    // Check if url refers to filesystem.
    this.isFsUrl = this.url.protocol === 'file:' || !this.url.host;
    this.httpHeaders = (this.isHttp && source.httpHeaders) || {};

    this._fullRequest = null;
    this._rangeRequestReaders = [];
  }

  getFullReader() {
    assert(!this._fullRequest);
    this._fullRequest = this.isFsUrl ?
      new PDFNodeStreamFsFullReader(this) :
      new PDFNodeStreamFullReader(this);
    return this._fullRequest;
  }

  getRangeReader(start, end) {
    let rangeReader = this.isFsUrl ?
      new PDFNodeStreamFsRangeReader(this, start, end) :
      new PDFNodeStreamRangeReader(this, start, end);
    this._rangeRequestReaders.push(rangeReader);
    return rangeReader;
  }

  cancelAllRequests(reason) {
    if (this._fullRequest) {
      this._fullRequest.cancel(reason);
    }

    let readers = this._rangeRequestReaders.slice(0);
    readers.forEach(function(reader) {
      reader.cancel(reason);
    });
  }
}

class BaseFullReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._errored = false;
    this._reason = null;
    this.onProgress = null;
    let source = stream.source;
    this._contentLength = source.length; // optional
    this._loaded = 0;

    this._disableRange = source.disableRange || false;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }

    this._isStreamingSupported = !source.disableStream;
    this._isRangeSupported = !source.disableRange;

    this._readableStream = null;
    this._readCapability = createPromiseCapability();
    this._headersCapability = createPromiseCapability();
  }

  get headersReady() {
    return this._headersCapability.promise;
  }

  get contentLength() {
    return this._contentLength;
  }

  get isRangeSupported() {
    return this._isRangeSupported;
  }

  get isStreamingSupported() {
    return this._isStreamingSupported;
  }

  read() {
    return this._readCapability.promise.then(() => {
      if (this._done) {
        return Promise.resolve({ value: undefined, done: true, });
      }
      if (this._errored) {
        return Promise.reject(this._reason);
      }

      let chunk = this._readableStream.read();
      if (chunk === null) {
        this._readCapability = createPromiseCapability();
        return this.read();
      }
      this._loaded += chunk.length;
      if (this.onProgress) {
        this.onProgress({
          loaded: this._loaded,
          total: this._contentLength,
        });
      }
      // Ensure that `read()` method returns ArrayBuffer.
      let buffer = new Uint8Array(chunk).buffer;
      return Promise.resolve({ value: buffer, done: false, });
    });
  }

  cancel(reason) {
    // Call `this._error()` method when cancel is called
    // before _readableStream is set.
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }

  _error(reason) {
    this._errored = true;
    this._reason = reason;
    this._readCapability.resolve();
  }

  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on('readable', () => {
      this._readCapability.resolve();
    });

    readableStream.on('end', () => {
      // Destroy readable to minimize resource usage.
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });

    readableStream.on('error', (reason) => {
      this._error(reason);
    });

    // We need to stop reading when range is supported and streaming is
    // disabled.
    if (!this._isStreamingSupported && this._isRangeSupported) {
      this._error(new AbortException('streaming is disabled'));
    }

    // Destroy ReadableStream if already in errored state.
    if (this._errored) {
      this._readableStream.destroy(this._reason);
    }
  }
}

class BaseRangeReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._errored = false;
    this._reason = null;
    this.onProgress = null;
    this._loaded = 0;
    this._readableStream = null;
    this._readCapability = createPromiseCapability();
    let source = stream.source;
    this._isStreamingSupported = !source.disableStream;
  }

  get isStreamingSupported() {
    return this._isStreamingSupported;
  }

  read() {
    return this._readCapability.promise.then(() => {
      if (this._done) {
        return Promise.resolve({ value: undefined, done: true, });
      }
      if (this._errored) {
        return Promise.reject(this._reason);
      }

      let chunk = this._readableStream.read();
      if (chunk === null) {
        this._readCapability = createPromiseCapability();
        return this.read();
      }
      this._loaded += chunk.length;
      if (this.onProgress) {
        this.onProgress({ loaded: this._loaded, });
      }
      // Ensure that `read()` method returns ArrayBuffer.
      let buffer = new Uint8Array(chunk).buffer;
      return Promise.resolve({ value: buffer, done: false, });
    });
  }

  cancel(reason) {
    // Call `this._error()` method when cancel is called
    // before _readableStream is set.
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }

  _error(reason) {
    this._errored = true;
    this._reason = reason;
    this._readCapability.resolve();
  }

  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on('readable', () => {
      this._readCapability.resolve();
    });

    readableStream.on('end', () => {
      // Destroy readableStream to minimize resource usage.
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });

    readableStream.on('error', (reason) => {
      this._error(reason);
    });

    // Destroy readableStream if already in errored state.
    if (this._errored) {
      this._readableStream.destroy(this._reason);
    }
  }
}

function createRequestOptions(url, headers) {
  return {
    protocol: url.protocol,
    auth: url.auth,
    host: url.hostname,
    port: url.port,
    path: url.path,
    method: 'GET',
    headers,
  };
}

class PDFNodeStreamFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);

    let handleResponse = (response) => {
      this._headersCapability.resolve();
      this._setReadableStream(response);

      let { allowRangeRequests, suggestedLength, } =
      validateRangeRequestCapabilities({
        getResponseHeader: (name) => {
          // Make sure that headers name are in lower case, as mentioned
          // here: https://nodejs.org/api/http.html#http_message_headers.
          return this._readableStream.headers[name.toLowerCase()];
        },
        isHttp: stream.isHttp,
        rangeChunkSize: this._rangeChunkSize,
        disableRange: this._disableRange,
      });

      if (allowRangeRequests) {
        this._isRangeSupported = true;
      }
      // Setting right content length.
      this._contentLength = suggestedLength;
    };

    this._request = null;
    if (this._url.protocol === 'http:') {
      this._request = http.request(
        createRequestOptions(this._url, stream.httpHeaders),
        handleResponse);
    } else {
      this._request = https.request(
        createRequestOptions(this._url, stream.httpHeaders),
        handleResponse);
    }

    this._request.on('error', (reason) => {
      this._errored = true;
      this._reason = reason;
      this._headersCapability.reject(reason);
    });
    // Note: `request.end(data)` is used to write `data` to request body
    // and notify end of request. But one should always call `request.end()`
    // even if there is no data to write -- (to notify the end of request).
    this._request.end();
  }
}

class PDFNodeStreamRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);

    this._httpHeaders = {};
    for (let property in stream.httpHeaders) {
      let value = stream.httpHeaders[property];
      if (typeof value === 'undefined') {
        continue;
      }
      this._httpHeaders[property] = value;
    }
    this._httpHeaders['Range'] = `bytes=${start}-${end - 1}`;

    this._request = null;
    if (this._url.protocol === 'http:') {
      this._request = http.request(createRequestOptions(
        this._url, this._httpHeaders), (response) => {
          this._setReadableStream(response);
        });
    } else {
      this._request = https.request(createRequestOptions(
        this._url, this._httpHeaders), (response) => {
          this._setReadableStream(response);
        });
    }

    this._request.on('error', (reason) => {
      this._errored = true;
      this._reason = reason;
    });
    this._request.end();
  }
}

class PDFNodeStreamFsFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);
    let path = decodeURI(this._url.path);

    fs.lstat(path, (error, stat) => {
      if (error) {
        this._errored = true;
        this._reason = error;
        this._headersCapability.reject(error);
        return;
      }
      // Setting right content length.
      this._contentLength = stat.size;

      this._setReadableStream(fs.createReadStream(path));
      this._headersCapability.resolve();
    });
  }
}

class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);

    this._setReadableStream(
      fs.createReadStream(decodeURI(this._url.path), { start, end: end - 1, }));
  }
}

export {
  PDFNodeStream,
};


text:
var co = require('co');
var util = require('./util');

var commander = require('commander');
var command = new commander.Command("synchro delete");
command.usage('[options] <appContainer>')
command.description('Remove the app from the current configuration and delete the container from the module store');
command.option('-c, --config <value>', 'Use the specified configuration file');
command.on('--help', function()
{
    console.log('  Details:');
    console.log('');
    console.log('    If <appContainer> is not provided, you will be prompted for it.');
    console.log('');
    console.log('    Any installed apps referencing the module store container will be removed from the current configuation.');
    console.log('    The module store container will then be deleted whether or not any app referenced it.');
    console.log('');
});
command.parse(process.argv);

co(function * ()
{
	var config = util.getConfigOrExit(command.config);
	var modulesStore = yield util.getModulesStoreAwaitable(config);
	var appsConfig = yield util.getAppsConfig(config, modulesStore);

	var appContainer;
	if (command.args.length > 0)
	{
	    appContainer = command.args[0];
	}
	if (!appContainer)
	{
        appContainer = yield util.read({prompt: "App container: "});
	}

	if (!appContainer || (appContainer.length == 0))
	{
		console.log("Synchro app container name cannot be empty");
		process.exit(1);
	}

	if (command.args.length == 0)
	{
		// We only verify if the app name was gathered interactively.  We assume that if you pass it on the command line,
		// you know what you're doing.
		//
		var verifyAppContainer = yield util.read({prompt: "Warning: All files will be deleted!  To confirm, re-enter container name: "});
		if (verifyAppContainer != appContainer)
		{
			console.log("Synchro app container name verification failed");
			process.exit(1);
		}
	}

	var installedApps = appsConfig.installedAppsFromContainer(appContainer);
	if (installedApps.length > 0)
	{
		var apps = config.get("APPS") || {};
		for (var i = 0; i < installedApps.length; i++)
		{
			// We got these install apps from the config via installedAppsFromContainer above, so we can rely their existence below...
			//
			var appPath = installedApps[i];
			delete appsConfig.APPS[appPath]
			console.log("Synchro application '%s' removed from the active configuration", appPath);
		}
		yield appsConfig.save();
	}
	else
	{
		console.log("No Synchro applications currently installed in the active configuration reference the container: %s", appContainer);
	}

	yield modulesStore.deleteAppContainerAwaitable(appContainer);
	console.log("Synchro container '%s' successfully deleted from module store", appContainer);

}).catch(function(err)
{
	console.log(err);
	process.exit(1);
});