text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gov.hhs.fha.nhinc.transform.subdisc;

import javax.xml.bind.JAXBElement;
import junit.framework.Assert;
import org.hl7.v3.MCCIMT000100UV01Device;
import org.hl7.v3.MCCIMT000100UV01Receiver;
import org.hl7.v3.MCCIMT000100UV01Sender;
import org.hl7.v3.PRPAIN201305UV02;
import org.hl7.v3.PRPAIN201306UV02;
import org.hl7.v3.PRPAMT201301UV02Patient;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hl7.v3.ActRelationshipMitigates;
import org.hl7.v3.CS;
import org.hl7.v3.II;
import org.hl7.v3.MCAIMT900001UV01DetectedIssueEvent;
import org.hl7.v3.MCAIMT900001UV01DetectedIssueManagement;
import org.hl7.v3.PRPAMT201301UV02Person;
import org.hl7.v3.TSExplicit;
import org.hl7.v3.XActMoodDefEvn;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;

/**
 *
 * @author dunnek
 */
public class HL7PRPA201306TransformsTest {

    private Mockery context;

    private static Log log = LogFactory.getLog(HL7PRPA201306TransformsTest.class);
    private String localDeviceId = "2.16.840.1.113883.3.200.1";
    private String senderOID = "2.16.840.1.113883.3.200";
    private String receiverOID = "2.16.840.1.113883.3.184";
    private String patientFirstName = "Thomas";
    private String patientLastName = "Kirtland";
    private String gender = "M";
    private String birthTime = "19261225";
    private String ssn = "134679852";
    private String patId = "46821564";

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
        context = new Mockery() {

            {
                setImposteriser(ClassImposteriser.INSTANCE);
            }
        };
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testCreatePRPA201306() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }
        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                will(returnValue(with(any(PRPAIN201306UV02.class))));
            }
        });
        log.info("testCreatePRPA201306");

        JAXBElement<PRPAMT201301UV02Person> person = HL7PatientTransforms.create201301PatientPerson(patientFirstName, patientLastName, gender, birthTime, ssn);
        PRPAMT201301UV02Patient patient = HL7PatientTransforms.create201301Patient(person, patId, localDeviceId);

        PRPAIN201305UV02 query = HL7PRPA201305Transforms.createPRPA201305(patient, senderOID, receiverOID, localDeviceId);
        PRPAIN201306UV02 result = HL7PRPA201306Transforms.createPRPA201306(patient, senderOID, receiverOID, receiverOID, localDeviceId, query);

        context.assertIsSatisfied();

        TestHelper.assertReceiverIdEquals(receiverOID, result);
        TestHelper.assertSenderIdEquals(senderOID, result);
    /*
    TestHelper.assertPatientIdEquals(patId, localDeviceId, result);
    TestHelper.assertBirthTimeEquals(birthTime, result);
    TestHelper.assertPatientNameEquals(patientFirstName, patientLastName, result);
    TestHelper.assertGenderEquals(gender, result);
     */
    }

    @Test
    public void testcreatePRPA201306ForPatientNotFoundWillPass() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected String getReceiverOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {
                return receiverOID;
            }

            protected String getSenderOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {
                return senderOID;
            }

            protected II getHL7MessageId(String receiverOID) {
                II oII = new II();
                oII.setRoot(receiverOID);

                return oII;
            }

            protected TSExplicit getHL7CreationTime() {
                return new TSExplicit();
            }

            protected II getHL7InteractionId() {
                return new II();
            }

            protected CS getHL7ProcessingCode() {
                return new CS();
            }

            protected CS getHL7ProcessingModeCode() {
                return new CS();
            }

            protected CS getHL7AcceptAckCode() {
                return new CS();
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                will(returnValue(with(any(PRPAIN201306UV02.class))));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        JAXBElement<PRPAMT201301UV02Person> person = HL7PatientTransforms.create201301PatientPerson(patientFirstName, patientLastName, gender, birthTime, ssn);
        PRPAMT201301UV02Patient patient = HL7PatientTransforms.create201301Patient(person, patId, localDeviceId);

        PRPAIN201305UV02 query = HL7PRPA201305Transforms.createPRPA201305(patient, senderOID, receiverOID, localDeviceId);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        //reverse the sender and receiver expectations
        TestHelper.assertReceiverIdEquals(senderOID, result);
        TestHelper.assertSenderIdEquals(receiverOID, result);

        //AA (application accept) is returned in Acknowledgement.typeCode (transmission wrapper).
        Assert.assertNotNull(result.getAcknowledgement());
        Assert.assertEquals("AA", result.getAcknowledgement().get(0).getTypeCode().getCode());
        //OK (data found, no errors) is returned in QueryAck.queryResponseCode (control act wrapper)
        Assert.assertNotNull(result.getControlActProcess());
        Assert.assertNotNull(result.getControlActProcess().getQueryAck());
        Assert.assertEquals("OK", result.getControlActProcess().getQueryAck().getQueryResponseCode().getCode());
        //There is no RegistrationEvent returned in the response
        Assert.assertNotNull(result.getControlActProcess().getSubject());
        Assert.assertNotNull(result.getControlActProcess().getSubject().get(0));
        Assert.assertNull(result.getControlActProcess().getSubject().get(0).getRegistrationEvent());

    }

    @Test
    public void testcreatePRPA201306ForPatientNotFoundWillFailForNullRequest() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The incomming patient discovery request, PRPAIN201305UV02, message was null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(null);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testcreatePRPA201306ForPatientNotFoundWillFailForNullRequiredFields() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areIncommingRequiredPRPAIN201305FieldsNull(PRPAIN201305UV02 oRequest) {
                return true;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullReceiver() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return true;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("One or more request receiver fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullSender() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }
            protected boolean areSenderFieldsNull(PRPAIN201305UV02 oRequest){
                return true;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("One or more request sender fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullControlActProcess() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }
            protected boolean areSenderFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }

            protected boolean areControlActProcessFieldsNull (PRPAIN201305UV02 oRequest){
                return true;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("One or more ControlActProcess fields from the incomming request were null.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreRequiredPRPAIN201305FieldsForPatientNotFoundNullWillFailForNullInteractionId() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }
            protected boolean areSenderFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }

            protected boolean areControlActProcessFieldsNull (PRPAIN201305UV02 oRequest){
                return false;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The InteractionId object from the incomming request message is null.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreReceiverFieldsNullWillFailForEmptyReceiverList() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The list of receiver objects from the incomming request message were null or empty.");
                one(mockLogger).error("One or more request receiver fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        query.getReceiver().clear();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreReceiverFieldsNullWillFailForNullReceiver() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The request's receiver object is null.");
                one(mockLogger).error("One or more request receiver fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        query.getReceiver().add(null);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreReceiverFieldsNullWillFailForNullReceiverDevice() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The request's receiver device object is null.");
                one(mockLogger).error("One or more request receiver fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Device oDevice = null;
        MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();
        oReceiver.setDevice(oDevice);
        query.getReceiver().add(oReceiver);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreReceiverFieldsNullWillFailForEmptyReceiverDeviceIds() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The list of device ids from the receiver object were null or empty.");
                one(mockLogger).error("One or more request receiver fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();
        oDevice.getId().clear();
        MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();
        oReceiver.setDevice(oDevice);
        query.getReceiver().add(oReceiver);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreReceiverFieldsNullWillFailForNullReceiverDeviceId() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The device II id object is null.");
                one(mockLogger).error("One or more request receiver fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();
        II oII = null;
        oDevice.getId().add(oII);
        MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();
        oReceiver.setDevice(oDevice);
        query.getReceiver().add(oReceiver);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreReceiverFieldsNullWillFailForNullReceiverDeviceIdGetRoot() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The device II id getRoot value is null.");
                one(mockLogger).error("One or more request receiver fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();
        II oII = new II();
        oDevice.getId().add(oII);
        MCCIMT000100UV01Receiver oReceiver = new MCCIMT000100UV01Receiver();
        oReceiver.setDevice(oDevice);
        query.getReceiver().add(oReceiver);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreSenderFieldsNullWillFailForNullSender() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The sender object from the incomming request message was null.");
                one(mockLogger).error("One or more request sender fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        query.setSender(null);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreSenderFieldsNullWillFailForNullSenderDevice() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The request's sender device object is null.");
                one(mockLogger).error("One or more request sender fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();
        query.setSender(oSender);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreSenderFieldsNullWillFailForEmptySenderDeviceIds() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The list of device ids from the sender object were null or empty.");
                one(mockLogger).error("One or more request sender fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();
        oDevice.getId().clear();
        MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();
        oSender.setDevice(oDevice);
        query.setSender(oSender);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreSenderFieldsNullWillFailForNullSenderDeviceId() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The sender device id (II) object is null.");
                one(mockLogger).error("One or more request sender fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();
        II oII = null;
        oDevice.getId().add(oII);
        MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();
        oSender.setDevice(oDevice);
        query.setSender(oSender);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testAreSenderFieldsNullWillFailForNullSenderDeviceIdGetRoot() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areReceiverFieldsNull(PRPAIN201305UV02 oRequest){
                return false;
            }
        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The device id value (i.e. II.getRoot() or " +
                    "oRequest.getSender().getDevice().getId().get(0).getRoot()) is null.");
                one(mockLogger).error("One or more request sender fields are null or empty.");
                one(mockLogger).error("One or more required fields from the patient discovery request " +
                    "for the patient not found scenario are null.");
                will(returnValue(null));
            }
        });

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        MCCIMT000100UV01Device oDevice = new MCCIMT000100UV01Device();
        II oII = new II();
        oDevice.getId().add(oII);
        MCCIMT000100UV01Sender oSender = new MCCIMT000100UV01Sender();
        oSender.setDevice(oDevice);
        query.setSender(oSender);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForPatientNotFound(query);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testCreatePRPA201306ForErrorsWillPass()
    {

        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected String getReceiverOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {
                return receiverOID;
            }

            protected String getSenderOIDFromPRPAIN201305UV02Request(PRPAIN201305UV02 oRequest) {
                return senderOID;
            }

            protected II getHL7MessageId(String receiverOID) {
                II oII = new II();
                oII.setRoot(receiverOID);

                return oII;
            }

            protected TSExplicit getHL7CreationTime() {
                return new TSExplicit();
            }

            protected II getHL7InteractionId() {
                return new II();
            }

            protected CS getHL7ProcessingCode() {
                return new CS();
            }

            protected CS getHL7ProcessingModeCode() {
                return new CS();
            }

            protected CS getHL7AcceptAckCode() {
                return new CS();
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                will(returnValue(with(any(PRPAIN201306UV02.class))));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        JAXBElement<PRPAMT201301UV02Person> person = HL7PatientTransforms.create201301PatientPerson(patientFirstName, patientLastName, gender, birthTime, ssn);
        PRPAMT201301UV02Patient patient = HL7PatientTransforms.create201301Patient(person, patId, localDeviceId);

        MCAIMT900001UV01DetectedIssueEvent oDetectedIssueEvent = new MCAIMT900001UV01DetectedIssueEvent();
        //<detectedIssueEvent classCode="ALRT" moodCode="EVN">
        oDetectedIssueEvent.getClassCode().add(HL7Constants.DETECTED_ISSUE_CLASSCODE_ALRT);
        oDetectedIssueEvent.getMoodCode().add(HL7Constants.DETECTED_ISSUE_MOODCODE_EVN);
        MCAIMT900001UV01DetectedIssueManagement oDetectedIssueManagement = new MCAIMT900001UV01DetectedIssueManagement();
        oDetectedIssueManagement.getClassCode().add(HL7Constants.DETECTEDISSUEMANAGEMENT_CLASSCODE);

        PRPAIN201305UV02 query = HL7PRPA201305Transforms.createPRPA201305(patient, senderOID, receiverOID, localDeviceId);
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForErrors(query,HL7Constants.DETECTEDISSUEMANAGEMENT_CODE_RESPONDER_BUSY);

        context.assertIsSatisfied();

        //reverse the sender and receiver expectations
        TestHelper.assertReceiverIdEquals(senderOID, result);
        TestHelper.assertSenderIdEquals(receiverOID, result);

        //AA (application accept) is returned in Acknowledgement.typeCode (transmission wrapper).
        Assert.assertNotNull(result.getAcknowledgement());
        Assert.assertEquals("AA", result.getAcknowledgement().get(0).getTypeCode().getCode());
        //QE (application error) is returned in QueryAck.queryResponseCode (control act wrapper)
        Assert.assertNotNull(result.getControlActProcess());
        Assert.assertNotNull(result.getControlActProcess().getQueryAck());
        Assert.assertEquals("QE", result.getControlActProcess().getQueryAck().getQueryResponseCode().getCode());
        //There is no RegistrationEvent returned in the response
        Assert.assertNotNull(result.getControlActProcess().getSubject());
        Assert.assertNotNull(result.getControlActProcess().getSubject().get(0));
        Assert.assertNull(result.getControlActProcess().getSubject().get(0).getRegistrationEvent());

        // verify that the responderBusy code is returned
         Assert.assertNotNull(result.getControlActProcess().getReasonOf());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0));
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getClassCode());
         Assert.assertEquals(oDetectedIssueEvent.getClassCode(),
                 result.getControlActProcess().getReasonOf().get(0).getDetectedIssueEvent()
                 .getClassCode());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMoodCode());
         Assert.assertEquals(oDetectedIssueEvent.getMoodCode(),
                 result.getControlActProcess().getReasonOf().get(0).getDetectedIssueEvent()
                 .getMoodCode());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getCode());
         Assert.assertEquals(HL7Constants.DETECTED_ISSUE_CODE_ADMINISTRATIVE,result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getCode().getCode());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getCode().getCodeSystem());
         Assert.assertEquals(HL7Constants.DETECTED_ISSUE_CODESYSTEM_ERROR_CODE,result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getCode().getCodeSystem());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0));
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0).getTypeCode());
         Assert.assertEquals(ActRelationshipMitigates.MITGT, result.getControlActProcess()
                 .getReasonOf().get(0).getDetectedIssueEvent().getMitigatedBy().get(0).getTypeCode());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0).getDetectedIssueManagement());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0).getDetectedIssueManagement().getClassCode());
         Assert.assertEquals(oDetectedIssueManagement.getClassCode(), result.getControlActProcess()
                 .getReasonOf().get(0).getDetectedIssueEvent().getMitigatedBy().get(0)
                 .getDetectedIssueManagement().getClassCode());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0).getDetectedIssueManagement().getMoodCode());
         Assert.assertEquals(XActMoodDefEvn.EVN, result.getControlActProcess()
                 .getReasonOf().get(0).getDetectedIssueEvent().getMitigatedBy().get(0)
                 .getDetectedIssueManagement().getMoodCode());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0).getDetectedIssueManagement().getCode());

         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0).getDetectedIssueManagement()
                 .getCode().getCode());
         Assert.assertEquals(HL7Constants.DETECTEDISSUEMANAGEMENT_CODE_RESPONDER_BUSY, result.getControlActProcess()
                 .getReasonOf().get(0).getDetectedIssueEvent().getMitigatedBy().get(0)
                 .getDetectedIssueManagement().getCode().getCode());
         Assert.assertNotNull(result.getControlActProcess().getReasonOf().get(0)
                 .getDetectedIssueEvent().getMitigatedBy().get(0).getDetectedIssueManagement()
                 .getCode().getCodeSystem());
         Assert.assertEquals(HL7Constants.DETECTEDISSUEMANAGEMENT_CODESYSTEM, result.getControlActProcess()
                 .getReasonOf().get(0).getDetectedIssueEvent().getMitigatedBy().get(0).getDetectedIssueManagement()
                 .getCode().getCodeSystem());

    }

    @Test
    public void testCreatePRPA201306ForErrorsWillFailForNullRequest() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The incomming patient discovery request, PRPAIN201305UV02, message was null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201306UV02 result = testSubject.createPRPA201306ForErrors(null,HL7Constants.DETECTEDISSUEMANAGEMENT_CODE_RESPONDER_BUSY);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testCreatePRPA201306ForErrorsWillFailForNullRequiredFields() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areIncommingRequiredPRPAIN201305FieldsNull(PRPAIN201305UV02 oRequest) {
                return true;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("One or more required fields from the patient discovery request are null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForErrors(query, HL7Constants.DETECTEDISSUEMANAGEMENT_CODE_RESPONDER_BUSY);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

    @Test
    public void testCreatePRPA201306ForErrorsWillFailForNullErrorCodeParameter() {
        final Log mockLogger = context.mock(Log.class);
        HL7PRPA201306Transforms testSubject = new HL7PRPA201306Transforms() {

            @Override
            protected Log createLogger() {
                return mockLogger;
            }

            protected boolean areIncommingRequiredPRPAIN201305FieldsNull(PRPAIN201305UV02 oRequest) {
                return false;
            }

        };
        context.checking(new Expectations() {

            {
                allowing(mockLogger).debug(with(any(String.class)));
                one(mockLogger).error("The sErrorCode parameter was null.");
                will(returnValue(null));
            }
        });
        log.info("testcreatePRPA201306ForPatientNotFoundWillPass");

        PRPAIN201305UV02 query = new PRPAIN201305UV02();
        PRPAIN201306UV02 result = testSubject.createPRPA201306ForErrors(query, null);

        context.assertIsSatisfied();

        Assert.assertNull(result);

    }

}


text:
<?php

namespace App\Models\TeamSpeak;

use App\Models\Model as Model;

/**
 * App\Models\TeamSpeak\Channel
 *
 * @property int $id
 * @property int|null $parent_id
 * @property string $name
 * @property bool $protected
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\TeamSpeak\Channel[] $children
 * @property-read \App\Models\TeamSpeak\Channel|null $parent
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TeamSpeak\Channel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TeamSpeak\Channel whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TeamSpeak\Channel whereParentId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TeamSpeak\Channel whereProtected($value)
 * @mixin \Eloquent
 */
class Channel extends Model
{
    public $timestamps = false;
    public $incrementing = false;
    protected $table = 'teamspeak_channel';
    protected $primaryKey = 'id';
    protected $guarded = [];

    /**
     * The parent of the current channel.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function parent()
    {
        return $this->belongsTo(self::class, 'parent_id', 'id');
    }

    /**
     * The children (sub-channels) of the current channel.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }

    /**
     * Accessor for channel protection inheritance. If the database field is null, protection is inherited.
     *
     * @param bool|null $value
     * @return bool
     */
    public function getProtectedAttribute($value)
    {
        if (is_null($value) && !is_null($this->parent)) {
            return $this->parent->protected;
        } else {
            if (is_null($value) && is_null($this->parent)) {
                return false;
            } else {
                return (bool) $value;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var apiKey = '75E5696EB9377FC04B31439534D5DB91'
var apiDomain = 'keenmate.com'

var heroesAPI = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=' + apiKey + '&language=en'

var source   = $("#heroes-template").html();
var template = Handlebars.compile(source);

$.ajax({
	dataType: 'json',
	url: heroesAPI,
}).done(function(data){
	console.log(data.result.heroes);
	var html = template(data.result);

	$("#heroes-list tbody").append(html);
}).fail(function(){
	console.log("Not working!");
});


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

<link   rel="stylesheet"
        href="../../css/style.min.0a7442460ca45a8d1ffa9d4f0a0163976899fc7820ce2bb76f693ba0527afb57.css"
        integrity="sha256-CnRCRgykWo0f+p1PCgFjl2iZ/Hggziu3b2k7oFJ6+1c="
        type="text/css"
        media="screen">

<link   rel="stylesheet"
        href="../../css/mobile.min.9d1271f82d33327493aaf7c1818ceac101a822559d694bd14a222d686e28c391.css"
        integrity="sha256-nRJx+C0zMnSTqvfBgYzqwQGoIlWdaUvRSiItaG4ow5E="
        type="text/css"
        media="handheld, only screen and (max-device-width: 960px)">

    <link href="https://unwiredcouch.com/atom.xml" type="application/atom+xml" rel="alternate" title="unwiredcouch.com: All Posts" />

    <title>Physics and Philosophy: The Revolution in Modern Science on unwiredcouch.com</title>

Writing

Reading

Setup

About

Drawing

Mastodon

 Physics and Philosophy: The Revolution in Modern Science

 by
           Werner Heisenberg

 Read: Feb 9, 2020

This book was just plain amazing. I didn't know what to expect when I found this at the book store and I was reading books about (quantum) physics at the time, so I was curious to see that Heisenberg had written a book. A lot of the (quantum) physics details went over my head. But I loved the discussion of its implications on “reality” and the philosophy of being. It's an extremely dense read but I got so much out of it.

Imprint


text:
/**
 * Configuration to list which sails components to rewire.
 *
 * You can rewire models, polices, adapters, hooks, blueprints, and responses.
 * You can also choose to have models and services rewired in the global object. Sails only injects models and services
 * in the global obejct.
 *
 * @type {Object}
 */
module.exports.rewire = {
  // List services to be rewired
  services: [
    {
      name: 'FileService',
      global: true    // replace the global FileService with the rewired version
    },
    {
      name: 'FetchService',
      global: false   // don't replace the global FetchService with the rewired version
    }
  ],
  // List controllers to be rewired
  controllers: [
    {
      name: 'FileController'
    },
    {
      name: 'DNSLookUpController',
      global: true    // this does nothing as only models and services are injected into the global object by sails
    }
  ]
};


text:
	<title>Nigel Dodds's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Nigel Dodds's panel show appearances

Nigel Dodds (born 1958-08-20[ref]) has appeared in 4 episodes between 2003-2016.  Nigel Dodds on Wikipedia.

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2016-01-21 / Question Time

2011-09-15 / Question Time

2003-11-13 / Question Time

2003-01-09 / Question Time


text:
/**
 * Data objects used by Gaffer which are related to graph analysis concepts.
 */
package uk.gov.gchq.gaffer.data.graph;


text:
package com.yanzhenjie.album.widget.divider;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.View;

/**
 * Created by YanZhenjie on 2018/4/20.
 */
class Drawer {

    private final Drawable mDivider;
    private final int mWidth;
    private final int mHeight;

    public Drawer(Drawable divider, int width, int height) {
        this.mDivider = divider;
        this.mWidth = width;
        this.mHeight = height;
    }

    /**
     * Draw the divider on the left side of the Item.
     */
    public void drawLeft(View view, Canvas c) {
        int left = view.getLeft() - mWidth;
        int top = view.getTop() - mHeight;
        int right = left + mWidth;
        int bottom = view.getBottom() + mHeight;
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }

    /**
     * Draw the divider on the top side of the Item.
     */
    public void drawTop(View view, Canvas c) {
        int left = view.getLeft() - mWidth;
        int top = view.getTop() - mHeight;
        int right = view.getRight() + mWidth;
        int bottom = top + mHeight;
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }

    /**
     * Draw the divider on the top side of the Item.
     */
    public void drawRight(View view, Canvas c) {
        int left = view.getRight();
        int top = view.getTop() - mHeight;
        int right = left + mWidth;
        int bottom = view.getBottom() + mHeight;
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }

    /**
     * Draw the divider on the top side of the Item.
     */
    public void drawBottom(View view, Canvas c) {
        int left = view.getLeft() - mWidth;
        int top = view.getBottom();
        int right = view.getRight() + mWidth;
        int bottom = top + mHeight;
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}


text:
/*
 * slist.c
 *
 * SOFTWARE RIGHTS
 *
 * We reserve no LEGAL rights to SORCERER -- SORCERER is in the public
 * domain.  An individual or company may do whatever they wish with
 * source code distributed with SORCERER or the code generated by
 * SORCERER, including the incorporation of SORCERER, or its output, into
 * commerical software.
 *
 * We encourage users to develop software with SORCERER.  However, we do
 * ask that credit is given to us for developing SORCERER.  By "credit",
 * we mean that if you incorporate our source code into one of your
 * programs (commercial product, research project, or otherwise) that you
 * acknowledge this fact somewhere in the documentation, research report,
 * etc...  If you like SORCERER and have developed a nice tool with the
 * output, please mention that you developed it using SORCERER.  In
 * addition, we ask that this header remain intact in our source code.
 * As long as these guidelines are kept, we expect to continue enhancing
 * this system and expect to make other tools available as they are
 * completed.
 *
 * SORCERER 1.00B
 * Terence Parr
 * AHPCRC, University of Minnesota
 * 1992-1994
 */
#include <stdio.h>
#include <setjmp.h>

#ifdef PCCTS_USE_STDARG
#include <stdarg.h>
#else
#include <varargs.h>
#endif

#include "CASTBase.h"
#include "sorlist.h"

/* Iterate over a list of elements; returns ptr to a new element
 * in list upon every call and NULL when no more are left.
 * Very useful like this:
 *
 *    cursor = mylist;
 *    while ( (p=slist_iterate(mylist,&cursor)) ) {
 *      / * place with element p * /
 *    }
 *
 * The cursor must be initialized to point to the list to iterate over.
 */
void *
#ifdef __USE_PROTOS
slist_iterate(SList *list, SList **cursor)
#else
slist_iterate(list, cursor)
SList *list, **cursor;
#endif
{
  void *e;

  if ( list==NULL || cursor == NULL || *cursor==NULL ) return NULL;
  if ( list== *cursor ) { *cursor = (*cursor)->next; }
  e = (*cursor)->elem;
  (*cursor) = (*cursor)->next;
  return e;
}

/*
 * add an element to a list.
 *
 * Any non-empty list has a sentinel node whose 'elem' pointer is really
 * a pointer to the last element.  (i.e. length(list) = #elemIn(list)+1).
 * Elements are appended to the list.
 */
void
#ifdef __USE_PROTOS
slist_add( SList **list, void *e )
#else
slist_add( list, e )
SList **list;
void *e;
#endif
{
  SList *p, *tail;
  require(e!=NULL, "slist_add: attempting to add NULL list element");

  p = newSList;
  require(p!=NULL, "slist_add: cannot alloc new list node");
  p->elem = e;
  if ( *list == NULL )
  {
    SList *sentinel = newSList;
    require(sentinel!=NULL, "slist_add: cannot alloc sentinel node");
    *list=sentinel;
    sentinel->next = p;
    sentinel->elem = (char *)p;    /* set tail pointer */
  }
  else                /* find end of list */
  {
    tail = (SList *) (*list)->elem;  /* get tail pointer */
    tail->next = p;
    (*list)->elem = (char *) p;    /* reset tail */
  }
}

void
#ifdef __USE_PROTOS
slist_free(SList *list)
#else
slist_free(list)
SList *list;
#endif
{
  SList *p,*q;

  if ( list==NULL ) return;  /* empty list */
  for (p = list->next; p!=NULL; p=q)
  {
    q = p->next;
    free(p);
  }
}


text:
<?Php
//birds.php
class Birds extends CI_Controller{
  function index(){
    //$this->load->view('birds_view');
  }

  function get_birds(){
    $this->load->model('birds_model');
    if (isset($_GET['term'])){
      $q = strtolower($_GET['term']);
      $this->birds_model->get_bird($q);
    }
  }
}


text:
'use strict';

angular.module('com.teachscape.coding.confirmation', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/confirmation', {
    templateUrl: 'views/confirmation/confirmation.html',
    controller: 'ConfirmationCtrl'
  });
}])

.controller('ConfirmationCtrl', [
	'$scope',
	'$routeParams',
	'$location',
	'reservationModel',
	function(
		$scope,
		$routeParams,
		$location,
		reservationModel
	) {
		console.log( "reservationModel.conf_number ", reservationModel.conf_number)
		if( !reservationModel.conf_number ){
			$location.url( "restaurants" );
		}
		$scope.reservationModel = reservationModel;
		console.log( parseInt( reservationModel.number, 10 ), typeof reservationModel.number );
	}
]);


text:
package tech.anima.tinytypes;

/**
 * Sample TinyTypes (and not) for use in test cases.
 */
public class Samples {

    public static class Str extends StringTinyType {

        public Str(String value) {
            super(value);
        }

    }

    public static class OtherStr extends StringTinyType {

        public OtherStr(String value) {
            super(value);
        }

    }

    public static class StrIndirectAncestor extends Samples.Str {

        public StrIndirectAncestor(String value) {
            super(value);
        }
    }

    public static abstract class AbstractStr extends StringTinyType {

        public AbstractStr(String value) {
            super(value);
        }
    }

    public static class NoOneArgCtorStr extends StringTinyType {

        public NoOneArgCtorStr() {
            super("1");
        }
    }

    public static class Boolean extends BooleanTinyType {

        public Boolean(boolean value) {
            super(value);
        }

    }

    public static class OtherBoolean extends BooleanTinyType {

        public OtherBoolean(boolean value) {
            super(value);
        }

    }

    public static class BooleanIndirectAncestor extends Samples.Boolean {

        public BooleanIndirectAncestor(boolean value) {
            super(value);
        }
    }

    public static abstract class AbstractBoolean extends BooleanTinyType {

        public AbstractBoolean(boolean value) {
            super(value);
        }
    }

    public static class NoOneArgCtorBoolean extends BooleanTinyType {

        public NoOneArgCtorBoolean() {
            super((boolean) true);
        }
    }

    public static class Byte extends ByteTinyType {

        public Byte(byte value) {
            super(value);
        }

    }

    public static class OtherByte extends ByteTinyType {

        public OtherByte(byte value) {
            super(value);
        }

    }

    public static class ByteIndirectAncestor extends Samples.Byte {

        public ByteIndirectAncestor(byte value) {
            super(value);
        }
    }

    public static abstract class AbstractByte extends ByteTinyType {

        public AbstractByte(byte value) {
            super(value);
        }
    }

    public static class NoOneArgCtorByte extends ByteTinyType {

        public NoOneArgCtorByte() {
            super((byte) 1);
        }
    }

    public static class Short extends ShortTinyType {

        public Short(short value) {
            super(value);
        }

    }

    public static class OtherShort extends ShortTinyType {

        public OtherShort(short value) {
            super(value);
        }

    }

    public static class ShortIndirectAncestor extends Samples.Short {

        public ShortIndirectAncestor(short value) {
            super(value);
        }
    }

    public static abstract class AbstractShort extends ShortTinyType {

        public AbstractShort(short value) {
            super(value);
        }
    }

    public static class NoOneArgCtorShort extends ShortTinyType {

        public NoOneArgCtorShort() {
            super((short) 1);
        }
    }

    public static class Integer extends IntTinyType {

        public Integer(int value) {
            super(value);
        }

    }

    public static class OtherInteger extends IntTinyType {

        public OtherInteger(int value) {
            super(value);
        }

    }

    public static class IntIndirectAncestor extends Samples.Integer {

        public IntIndirectAncestor(int value) {
            super(value);
        }
    }

    public static abstract class AbstractInteger extends IntTinyType {

        public AbstractInteger(int value) {
            super(value);
        }
    }

    public static class NoOneArgCtorInteger extends IntTinyType {

        public NoOneArgCtorInteger() {
            super((int) 1);
        }
    }

    public static class Long extends LongTinyType {

        public Long(long value) {
            super(value);
        }

    }

    public static class OtherLong extends LongTinyType {

        public OtherLong(long value) {
            super(value);
        }

    }

    public static class LongIndirectAncestor extends Samples.Long {

        public LongIndirectAncestor(long value) {
            super(value);
        }
    }

    public static abstract class AbstractLong extends LongTinyType {

        public AbstractLong(long value) {
            super(value);
        }
    }

    public static class NoOneArgCtorLong extends LongTinyType {

        public NoOneArgCtorLong() {
            super((long) 1);
        }
    }

}


text:
FROM buildkite/agent:3
MAINTAINER Jason Cox <jason.cox@panoply.fm>

ADD VERSION .

# ruby
# -----------
RUN mkdir -p /usr/local/etc \
  && { \
    echo 'install: --no-document'; \
    echo 'update: --no-document'; \
  } >> /usr/local/etc/gemrc

ENV RUBY_VERSION 2.3.3
ENV NEW_RUBY_VERSION 2.5.3
ENV RUBYGEMS_VERSION 2.6.10

RUN set -ex \
  && apk add --update --no-cache \
    autoconf \
    bash \
    bison \
    bzip2 \
    bzip2-dev \
    ca-certificates \
    coreutils \
    curl \
    gcc \
    git \
    gdbm-dev \
    glib-dev \
    libc-dev \
    libffi-dev \
    libxml2-dev \
    libxslt-dev \
    linux-headers \
    make \
    ncurses-dev \
    postgresql-dev \
    procps \
    readline-dev \
    yaml-dev \
    zlib-dev \
    ruby \
    ruby-dev

ENV PATH /usr/local/rbenv/shims:/usr/local/rbenv/bin:$PATH
ENV RBENV_ROOT /usr/local/rbenv
ENV CONFIGURE_OPTS="ac_cv_func_isnan=yes ac_cv_func_isinf=yes --disable-install-doc"

RUN git clone --depth 1 git://github.com/sstephenson/rbenv.git ${RBENV_ROOT} \
&&  git clone --depth 1 https://github.com/sstephenson/ruby-build.git ${RBENV_ROOT}/plugins/ruby-build \
&&  git clone --depth 1 git://github.com/jf/rbenv-gemset.git ${RBENV_ROOT}/plugins/rbenv-gemset \
&& ${RBENV_ROOT}/plugins/ruby-build/install.sh

RUN echo 'eval "$(rbenv init -)"' >> /etc/profile.d/rbenv.sh

RUN rbenv install $RUBY_VERSION && \
  rbenv install $NEW_RUBY_VERSION && \
  rbenv global $RUBY_VERSION

RUN gem install bundler

# faster nokogiri installs
RUN bundle config --global build.nokogiri --use-system-libraries

# configure default bundle location
RUN bundle config --global path .bundle

# node
# ----------
RUN set -ex \
  && apk add --no-cache --virtual .build-deps \
    binutils-gold \
    curl \
    g++ \
    gcc \
    gnupg \
    libgcc \
    linux-headers \
    make \
    python \
    libstdc++ \
    ncurses \
    ca-certificates \
    openssl \
    coreutils \
    python2 \
    grep \
    util-linux \
    binutils \
    findutils

# nvm node version manager
RUN wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | /bin/bash
ENV NVM_DIR /root/.nvm
RUN [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" && \
  nvm install -s 9.11 && nvm use 9.11
RUN [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" && \
  npm install -g yarn@1.7
RUN echo "source $NVM_DIR/nvm.sh" >> /etc/profile.d/nvm.sh
RUN echo "source $NVM_DIR/nvm.sh" >> $HOME/.bashrc
# ----------

# golang
# ----------
ENV GOLANG_VERSION 1.9.4
RUN set -eux; \
	apk add --no-cache --virtual .build-deps \
		bash \
		gcc \
		musl-dev \
		openssl \
		go

ENV GOROOT_BOOTSTRAP=/usr/lib/go GOOS=linux GOARCH=amd64 GOHOSTOS=linux GOHOSTARCH=amd64 GO386=387
ENV GOPATH $HOME/go
ENV PATH $GOPATH/bin:$PATH

RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"

RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]
RUN ["/bin/bash", "-c", "source /root/.gvm/scripts/gvm && gvm install go1.10 && gvm use go1.10"]
RUN echo "source /root/.gvm/scripts/gvm" >> /etc/profile.d/gvm.sh
RUN echo "source /root/.gvm/scripts/gvm" >> $HOME/.bashrc

# install dep
RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
# ----------

# set up phantomjs
RUN apk update && apk add --no-cache fontconfig && \
  wget -qO- "https://github.com/dustinblackman/phantomized/releases/download/2.1.1a/dockerized-phantomjs.tar.gz" | tar xz -C / && \
  [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" && \
  npm config set user 0 && \
  npm install -g phantomjs-prebuilt

RUN apk add --update -X http://dl-cdn.alpinelinux.org/alpine/edge/main	libvpx
RUN apk add --update -X http://dl-cdn.alpinelinux.org/alpine/edge/community ffmpeg-libs
RUN apk add --update -X http://dl-cdn.alpinelinux.org/alpine/edge/testing chromaprint-dev
RUN apk add --no-cache tini sudo chromaprint
# add psql support
RUN apk add --no-cache postgresql-client

# allow ssh config
RUN curl -fL "https://raw.githubusercontent.com/buildkite/docker-ssh-env-config/d06f20bdc7457a647bfe3724d94525f83c863091/ssh-env-config.sh" -o /usr/local/bin/ssh-env-config.sh \
    && chmod +x /usr/local/bin/ssh-env-config.sh

ADD init.sh /usr/local/bin/init.sh
RUN chmod +x /usr/local/bin/init.sh
ENTRYPOINT ["/sbin/tini", "--", "init.sh"]
CMD ["start"]


text:
import assert from "assert";
import sinon from "sinon";
import { EventEmitter } from "events";
import NeuContext from "../../../src/neume/core/NeuContext";
import NeuBus from "../../../src/neume/core/NeuBus";
import { AUDIO, CONTROL } from "../../../src/neume/constants";
import * as commands from "../../../src/scsynth/commands";

class TestServer extends EventEmitter {
  constructor() {
    super();
    this.commands = commands;
    this.sendOSC = sinon.spy();
  }
}

class TestContext extends NeuContext {
  constructor() {
    super({ ServerClass: TestServer });
    Object.getOwnPropertyNames(NeuContext.prototype).forEach((name) => {
      this[name] = sinon.spy(this[name].bind(this));
    });
  }
}

describe("neume/core/NeuBus", () => {
  describe("constructor(context, rate, index, length)", () => {
    it("should create NeuBus instance", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, AUDIO, 0, 2);

      assert(bus instanceof NeuBus);
      assert(bus.rate === AUDIO);
      assert(bus.index === 0);
      assert(bus.length === 2);
    });
  });

  describe(".in", () => {
    it("should create In.ar", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, AUDIO, 0, 2);
      const node = bus.in;

      assert(Array.isArray(node) && node.length === 2);
      assert(node[0].type === "OutputProxy");
      assert(node[0].rate === "audio");
      assert(node[0].props[0].type === "In");
    });

    it("should create In.kr", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, CONTROL, 0, 2);
      const node = bus.in;

      assert(Array.isArray(node) && node.length === 2);
      assert(node[0].type === "OutputProxy");
      assert(node[0].rate === "control");
      assert(node[0].props[0].type === "In");
    });
  });

  describe(".value", () => {
    it("should call .set() when set", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, CONTROL, 0, 2);

      bus.set = sinon.spy();

      bus.value = 1;

      assert(bus.set.args[0], [ 1 ]);
    });
  });

  describe(".set(value)", () => {
    it("should send c_set command to server", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, CONTROL, 0, 2);

      bus.set(1);

      assert.deepEqual(context.sendOSC.args[0], [ {
        address: "/c_set",
        args: [
          { type: "integer", value: bus.index },
          { type: "float"  , value: 1 },
        ]
      } ]);
    });

    it("should throw Error when rate is AUDIO", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, AUDIO, 0, 2);

      assert.throws(() => {
        bus.set(1);
      }, TypeError);
    });
  });

  describe(".setAt(index, value)", () => {
    it("should send c_set command to server", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, CONTROL, 0, 2);

      bus.setAt(1, 2);

      assert.deepEqual(context.sendOSC.args[0], [ {
        address: "/c_set",
        args: [
          { type: "integer", value: bus.index + 1 },
          { type: "float"  , value: 2 },
        ]
      } ]);
    });

    it("should throw Error when index is out of range", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, CONTROL, 0, 2);

      assert.throws(() => {
        bus.setAt(10, 2);
      }, TypeError);
    });

    it("should throw Error when rate is AUDIO", () => {
      const context = new TestContext();
      const bus = new NeuBus(context, AUDIO, 0, 2);

      assert.throws(() => {
        bus.setAt(1, 2);
      }, TypeError);
    });
  });
});


text:
#include <lk/err.h>
#include <lk/debug.h>
#include <lk/trace.h>
#include <stdio.h>
#include <string.h>
#include <lib/watchdog.h>
#include <platform.h>
#include <platform/zynq.h>

/* Driver for the system wide watchdog timer for Zynq */

#define LOCAL_TRACE 0

/* three magic values for the MODE, CONTROL, and RESTART registers */
#define SWDT_MODE_ZKEY      (0xabc << 12)
#define SWDT_CONTROL_CKEY   (0x248 << 14)
#define SWDT_RESTART_RSTKEY (0x1999)

/* reserved field in the MODE register */
#define SWDT_MODE_RESERVED  (0x4 << 4)

/* routines called from lib/watchdog */
status_t platform_watchdog_init(lk_time_t  target_timeout,
                                lk_time_t *recommended_pet_period) {
    LTRACEF("target_timeout %u\n", (uint32_t)target_timeout);

    /* make sure the swdt is stopped */
    SWDT->MODE = SWDT_MODE_ZKEY | SWDT_MODE_RESERVED;

    /* make sure swdt has the proper clock */
    SLCR->WDT_CLK_SEL = 0; // cpu 1x

    uint32_t swdt_clock = zynq_get_swdt_freq();

    /* assuming a prescalar of / 4096, figure out the restart value */
    uint32_t restart = ((swdt_clock / 4096) * target_timeout) / 1000;

    /* make sure the restart value is <= 24 bits */
    if (restart > 0x00ffffff)
        restart = 0x00ffffff;

    LTRACEF("restart value %u\n", restart);

    /* the bottom 12 bits of restart are set to 0xfff by hardware */
    restart |= 0xfff;

    /* pet period is / 2 the computed restart value */
    if (recommended_pet_period)
        *recommended_pet_period = ((restart * 1000) / (swdt_clock / 4096)) / 2;

    LTRACEF("recommended pet period %u\n", (uint32_t)*recommended_pet_period);

    /* set up the swdt */

    /* load counter restart (top 12 bits of restart count), pclk / 4096 */
    SWDT->CONTROL = SWDT_CONTROL_CKEY | ((restart >> 12) << 2) | 3;

    /* zero it out */
    SWDT->RESTART = SWDT_RESTART_RSTKEY;

    DMB;

    return NO_ERROR;
}

void platform_watchdog_set_enabled(bool enabled) {
    LTRACEF("enabled %u\n", enabled);

    if (enabled) {
        /* wide irq length, reset enable on counter zero, enable */
        SWDT->MODE = SWDT_MODE_ZKEY | SWDT_MODE_RESERVED | (3 << 7) | (1<<1) | 1;

        /* start it by petting it once, in case it already latched */
        SWDT->RESTART = SWDT_RESTART_RSTKEY;
    } else {
        /* disable everything */
        SWDT->MODE = SWDT_MODE_ZKEY | SWDT_MODE_RESERVED;
    }
    DMB;
}

void platform_watchdog_pet(void) {
    //LTRACEF("pet\n");
    SWDT->RESTART = SWDT_RESTART_RSTKEY;
    DMB;
}


text:
import {Loading} from './loading.js';

const PAGINATION_ENDPOINT = '/devices';
const BLANK_PAGE_TOKEN = '';
const MAX_DEVICE_COUNT_PARAMETER_NAME = 'maxDeviceCount';
const PAGE_TOKEN_PARAMETER_NAME = 'pageToken';

/*
 * Table Column Organization:
 * Aggregation table has Field 1 | ... | Field n | deviceCount | Button | deviceIds | serialNumbers | Row #
 * Normal view has Field 1 | ... | Field n
 */
class TableManager {
  constructor(containerId) {
    this.container = document.getElementById(containerId);
    this.table = this.createNewTable(containerId);
    this.baseDataTable = new google.visualization.DataTable();
    this.currPage = 0;
    this.pageSize = 10;
    this.aggregating = false;

    this.pageLeft = document.getElementById('page-left');
    this.pageRight = document.getElementById('page-right');
    this.pageNumber = document.getElementById('page-number');
    this.pageSizeSelect = document.getElementById('page-size-select');

    this.nextPageToken = BLANK_PAGE_TOKEN;

    google.visualization.events.addOneTimeListener(this.table, 'ready', () => {
      google.visualization.events.addListener(
          this.table.getChart(), 'page', this.onPageChange.bind(this));
    });

    google.visualization.events.addListener(this.table, 'ready', this.makeTableAccessible.bind(this));

    this.pageLeft.onclick = () => {
      google.visualization.events.trigger(this.table.getChart(), 'page', {'pageDelta': -1});
    };
    this.pageRight.onclick = () => {
      google.visualization.events.trigger(this.table.getChart(), 'page', {'pageDelta': 1});
    };
    this.pageSizeSelect.onchange = () => {
      this.onPageSizeChange(parseInt(this.pageSizeSelect.value));
    };
  }

  draw() {
    this.table.draw();
    this.pageNumber.innerText = this.currPage + 1;

    this.drawArrows();
  }

  drawArrows() {
    if (this.aggregating) {
      this.pageLeft.disabled = true;
      this.pageRight.disabled = true;
    } else {
      this.pageLeft.disabled = this.currPage == 0;
      this.pageRight.disabled = !this.hasNextPage();
    }
  }

  updateAggregation(dataTable) {
    this.currPage = 0;
    this.aggregating = true;
    // Google charts API has a bug where setting pageSize will cause the table to be
    // paginated, regardles of if the 'page' property is set to 'disable'.  Thus, we
    // must remove the pageSize property entirely.
    let currOptions = this.table.getOptions();

    delete currOptions['pageSize'];
    currOptions['page'] = 'disable';

    this.table.setOptions(currOptions);
    this.setTableView(dataTable.getNumberOfColumns());
    this.setDataTable(dataTable);
  }

  async updateNormal() {
    this.aggregating = false;

    this.table.setOption('page', 'event');
    this.table.setOption('pageSize', this.pageSize);

    await this.resetNormalData();
    this.setTableView(this.baseDataTable.getNumberOfColumns());
    this.setDataTable();
  }

  setDataTable(dataTable) {
    if (dataTable != null) {
      this.baseDataTable = dataTable;
    }

    if (this.aggregating) {
      this.table.setDataTable(this.baseDataTable);
    } else {
      let view = new google.visualization.DataView(this.baseDataTable);
      const startIndex = this.currPage * this.pageSize;
      const endIndex = Math.min(
          this.currPage * this.pageSize + this.pageSize - 1,
          this.baseDataTable.getNumberOfRows() - 1);
      view.setRows(startIndex, endIndex);
      this.table.setDataTable(view);
    }
  }

  setTableView(numOfCols) {
    // See guide at top of file for table layout.  In normal view, we want to display all columns;
    // in aggregation view, we ignore the last 4 columns which are used for internal purposes
    let viewableCols;
    if (!this.aggregating) {
      viewableCols = [...Array(numOfCols).keys()];
    } else {
      // Skip over deviceIds, serialNumbers, and Row #
      viewableCols = [...Array(numOfCols - 3).keys()];
    }

    this.table.setView({'columns': viewableCols});
  }

  hasNextPageCached() {
    return (this.currPage + 1) * this.pageSize < this.baseDataTable.getNumberOfRows();
  }

  hasNextPageRemote() {
    return this.nextPageToken != BLANK_PAGE_TOKEN;
  }

  hasNextPage() {
    return this.hasNextPageRemote() || this.hasNextPageCached();
  }

  async onPageChange(properties) {
    const pageDelta = properties['pageDelta']; // 1 or -1
    const newPage = this.currPage + pageDelta;

    if (newPage < 0 || (pageDelta > 0 && !this.hasNextPage()) ) {
      return;
    }

    // Check if we have the necessary data to change the page.  If we dont, get it.
    if (pageDelta > 0 && !this.hasNextPageCached()) {
      await new Loading(this.addDataToTable.bind(this), true).load();
    }
    this.currPage = newPage;
    this.setDataTable();

    this.draw();
  }

  async onPageSizeChange(newPageSize) {
    this.pageSize = newPageSize;
    this.table.setOption('pageSize', newPageSize);

    await this.updateNormal();

    this.draw();
  }

  async resetNormalData() {
    this.currPage = 0;
    this.nextPageToken = BLANK_PAGE_TOKEN;

    this.baseDataTable = new google.visualization.DataTable();
    this.baseDataTable.addColumn('string', 'Serial Number');
    this.baseDataTable.addColumn('string', 'Status');
    this.baseDataTable.addColumn('string', 'Asset ID');
    this.baseDataTable.addColumn('string', 'User');
    this.baseDataTable.addColumn('string', 'Location');

    let loader = new Loading(this.addDataToTable.bind(this), true);
    await loader.load();
  }

  async addDataToTable() {
    if (this.aggregating) {
      throw new Error('Method addDataToTable should not be called while table is in aggregation mode');
    }

    let url = this.buildNextPageURL();
    await fetch(url)
        .then(response => response.json())
        .then(json => {
          this.nextPageToken = json.nextPageToken == null ? BLANK_PAGE_TOKEN : json.nextPageToken;
          for (let device of json.chromeosdevices) {
            this.baseDataTable.addRow([
                device.serialNumber,
                device.status,
                device.annotatedAssetId,
                device.annotatedUser,
                device.annotatedLocation]);
          }
        });
  }

  buildNextPageURL() {
    let url = new URL(PAGINATION_ENDPOINT, window.location.href);

    let params = new URLSearchParams();
    params.append(MAX_DEVICE_COUNT_PARAMETER_NAME, this.pageSize);
    params.append(PAGE_TOKEN_PARAMETER_NAME, this.nextPageToken);

    url.search = params;

    return url;
  }

  makeTableAccessible() {
    let table = this.container.getElementsByTagName('table')[0];
    let tableHeaders = table.getElementsByTagName('th');
    let idPrefix = 'tableHeaderSpan';
    for (let [index, th] of Object.entries(tableHeaders)) {
      let nameId = idPrefix + (2 * index);
      let instructionsId = idPrefix + (2 * index + 1);
      let container = document.createElement('span');

      let nameSpanAria = document.createElement('span');
      nameSpanAria.innerText = th.innerText;
      nameSpanAria.setAttribute('id', nameId);
      nameSpanAria.classList.add('hidden');

      let innerContainer = document.createElement('span');
      innerContainer.setAttribute('aria-labelledby', instructionsId);
      innerContainer.setAttribute('role', 'button');
      innerContainer.setAttribute('tabindex', 0);

      let nameSpanDisplay = document.createElement('span');
      nameSpanDisplay.setAttribute('aria-hidden', 'true');
      nameSpanDisplay.innerText = th.innerText;

      let instructionsSpan = document.createElement('span');
      instructionsSpan.innerText = 'Activate to sort by column.';
      instructionsSpan.classList.add('hidden');
      instructionsSpan.setAttribute('id', instructionsId);

      th.innerHTML = '';

      innerContainer.append(nameSpanDisplay, instructionsSpan);
      container.append(nameSpanAria, innerContainer);
      th.appendChild(container);

      th.setAttribute('aria-labelledby', nameId);
      th.setAttribute('role', 'columnheader');
      th.removeAttribute('aria-label');
      th.removeAttribute('tabindex');
    }
  }

  createNewTable(containerId) {
    return new google.visualization.ChartWrapper({
        'chartType': 'Table',
        'containerId': containerId,
        'options': {
            'title': 'Sample Table',
            'page': 'event',
            'pageSize': 10,
            'width': '100%',
            'allowHtml': 'true',
            'cssClassNames': {
                'headerRow': 'table-header-row',
                'tableRow': 'table-row',
                'oddTableRow': 'table-row',
                'tableCell': 'table-cell'
            }
        }
    });
  }
}

export {TableManager};


text:
package me.zhanghai.android.materialprogressbar;

abstract class BaseProgressDrawable extends BasePaintDrawable implements IntrinsicPaddingDrawable {

    protected boolean mUseIntrinsicPadding = true;

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean getUseIntrinsicPadding() {
        return mUseIntrinsicPadding;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setUseIntrinsicPadding(boolean useIntrinsicPadding) {
        if (mUseIntrinsicPadding != useIntrinsicPadding) {
            mUseIntrinsicPadding = useIntrinsicPadding;
            invalidateSelf();
        }
    }
}


text:
require "spec_helper"

describe "The Books Resource Routes" do
  let(:books) { Smooth("Books") }

  let(:session) do
    Rack::MockSession.new(books.api.sinatra)
  end

  let(:client) do
    Rack::Test::Session.new(session)
  end

  it "should make a request to the show action" do
    book = Book.create(title:"Cristian The LionHeart")
    response = client.get("/books/#{ book.id }")
    json = JSON.parse(response.body) rescue {}
    book = json.fetch("book")

    expect(response.status).to eq(200)
    expect(book["title"]).to eq("Cristian The LionHeart")
  end

  it "should make a request to the books query" do
    Book.create(title:"Luca The Coming Champ", year_published: 1895)
    response = client.get("/books", title: "Luca")
    json = JSON.parse(response.body) rescue {}

    expect(json).not_to be_empty
    expect(response.status).to eq(200)
  end

  it "should make a request to the create command" do
    response = client.post("/books", title: "The Biography of Jon Soeder")

    json = JSON.parse(response.body) rescue {}

    book = json.fetch("book")

    expect(response.status).to eq(200)
    expect(book).to have_key("author_id")
    expect(book["id"]).not_to be_nil
    expect(book["title"]).to eq("The Biography of Jon Soeder")
  end

  it "should return errors if i don't include the right params" do
    response = client.post("/books")
    expect(response.status).not_to eq(200)
  end
end


text:
import vmprof

import os
import six
from _prof_imports import TreeStats, CallTreeStat
import tempfile
import shutil

class VmProfProfile(object):
    """ Wrapper class that represents VmProf Python profiling backend with API matching
        the cProfile.
    """

    def __init__(self):
        self.stats = None
        self.basepath = None
        self.file = None
        self.is_enabled = False

    def runcall(self, func, *args, **kw):
        self.enable()
        try:
            return func(*args, **kw)
        finally:
            self.disable()

    def enable(self):
        if not self.is_enabled:
            if not os.path.exists(self.basepath):
                os.makedirs(self.basepath)
            self.file = tempfile.NamedTemporaryFile(delete=False, dir=self.basepath)
            vmprof.enable(self.file.fileno())
            self.is_enabled = True

    def disable(self):
        if self.is_enabled:
            vmprof.disable()
            self.file.close()
            self.is_enabled = False

    def create_stats(self):
        return None

    def getstats(self):
        self.create_stats()

        return self.stats

    def dump_stats(self, file):
        shutil.copyfile(self.file.name, file)

    def _walk_tree(self, parent, node, callback):
        tree = callback(parent, node)
        for c in six.itervalues(node.children):
            self._walk_tree(node, c, callback)
        return tree

    def tree_stats_to_response(self, filename, response):
        tree_stats_to_response(filename, response)

    def snapshot_extension(self):
        return '.prof'

def _walk_tree(parent, node, callback):
    if node is None:
        return None
    tree = callback(parent, node)
    for c in six.itervalues(node.children):
        _walk_tree(tree, c, callback)
    return tree

def tree_stats_to_response(filename, response):
    stats = vmprof.read_profile(filename)

    response.tree_stats = TreeStats()
    response.tree_stats.sampling_interval = vmprof.DEFAULT_PERIOD

    try:
        tree = stats.get_tree()
    except vmprof.stats.EmptyProfileFile:
        tree = None

    def convert(parent, node):
        tstats = CallTreeStat()
        tstats.name = node.name
        tstats.count = node.count
        tstats.children = []
        tstats.line_count = getattr(node, 'lines', {})

        if parent is not None:
            if parent.children is None:
                parent.children = []
            parent.children.append(tstats)

        return tstats

    response.tree_stats.call_tree = _walk_tree(None, tree, convert)


text:
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 * @version $Id: Translate.php 6300 2012-05-23 21:19:25Z SteveG $
 *
 * @category Piwik
 * @package Piwik
 */

/**
 * @package Piwik
 */
class Piwik_Translate
{
	static private $instance = null;
	static private $languageToLoad = null;
	private $loadedLanguage = false;

	/**
	 * @return Piwik_Translate
	 */
	static public function getInstance()
	{
		if (self::$instance == null)
		{
			self::$instance = new self;
		}
		return self::$instance;
	}

	public function loadEnglishTranslation()
	{
		$this->loadTranslation('en');
	}

	public function unloadEnglishTranslation()
	{
		$GLOBALS['Piwik_translations'] = array();
	}

	public function reloadLanguage($language = false)
	{
		if(empty($language))
		{
			$language = $this->getLanguageToLoad();
		}
		$this->unloadEnglishTranslation();
		$this->loadEnglishTranslation();
		$this->loadCoreTranslation($language);
		Piwik_PluginsManager::getInstance()->loadPluginTranslations($language);
	}

	/**
	 * Reads the specified code translation file in memory.
	 *
	 * @param bool|string $language 2 letter language code. If not specified, will detect current user translation, or load default translation.
	 * @return void
	 */
	public function loadCoreTranslation($language = false)
	{
		if(empty($language))
		{
			$language = $this->getLanguageToLoad();
		}
		if($this->loadedLanguage == $language)
		{
			return;
		}
		$this->loadTranslation($language);
	}

	private function loadTranslation($language)
	{
		$path = PIWIK_INCLUDE_PATH . '/lang/' . $language . '.php';
		if(!Piwik_Common::isValidFilename($language) || !is_readable($path))
		{
			throw new Exception(Piwik_TranslateException('General_ExceptionLanguageFileNotFound', array($language)));
		}
		require $path;
		$this->mergeTranslationArray($translations);
		$this->setLocale();
		$this->loadedLanguage = $language;
	}

	public function mergeTranslationArray($translation)
	{
		if(!isset($GLOBALS['Piwik_translations']))
		{
			$GLOBALS['Piwik_translations'] = array();
		}
		// we could check that no string overlap here
		$GLOBALS['Piwik_translations'] = array_merge($GLOBALS['Piwik_translations'], array_filter($translation, 'strlen'));
	}

	/**
	 * @return string the language filename prefix, eg 'en' for english
	 * @throws exception if the language set is not a valid filename
	 */
	public function getLanguageToLoad()
	{
		if(is_null(self::$languageToLoad))
		{
			$lang = Piwik_Common::getRequestVar('language', '', 'string');

			Piwik_PostEvent('Translate.getLanguageToLoad', $lang);

			self::$languageToLoad = $lang;
		}

		return self::$languageToLoad;
	}

	/** Reset the cached language to load. Used in tests. */
	static public function reset()
	{
		self::$languageToLoad = null;
	}

	public function getLanguageLoaded()
	{
		return $this->loadedLanguage;
	}

	public function getLanguageDefault()
	{
		return Piwik_Config::getInstance()->General['default_language'];
	}

	/**
	 * Generate javascript translations array
	 *
	 * @param array $moduleList
	 * @return string containing javascript code with translations array (including <script> tag)
	 */
	public function getJavascriptTranslations(array $moduleList)
	{
		if(!in_array('General', $moduleList))
		{
			$moduleList[] = 'General';
		}

		$js = 'var translations = {';

		$moduleRegex = '#^(';
		foreach($moduleList as $module)
		{
			$moduleRegex .= $module.'|';
		}
		$moduleRegex = substr($moduleRegex, 0, -1);
		$moduleRegex .= ')_.*_js$#i';

		// Hack: common translations used in JS but not only, force as them to be defined in JS
		$translations = $GLOBALS['Piwik_translations'];
		$toSetInJs = array('General_Save', 'General_OrCancel');
		foreach($toSetInJs as $toSetId)
		{
    		$translations[$toSetId.'_js'] = $translations[$toSetId];
		}
		foreach($translations as $key => $value)
		{
			if( preg_match($moduleRegex,$key) ) {
				$js .= '"'.$key.'": "'.str_replace('"','\"',$value).'",';
			}
		}
		$js = substr($js,0,-1);
		$js .= '};';
		$js .=	'if(typeof(piwik_translations) == \'undefined\') { var piwik_translations = new Object; }'.
				'for(var i in translations) { piwik_translations[i] = translations[i];} ';
		$js .= 'function _pk_translate(translationStringId) { '.
			'if( typeof(piwik_translations[translationStringId]) != \'undefined\' ){  return piwik_translations[translationStringId]; }'.
			'return "The string "+translationStringId+" was not loaded in javascript. Make sure it is suffixed with _js and that you called  {loadJavascriptTranslations plugins=\'\$YOUR_PLUGIN_NAME\'} before your javascript code.";}';

		return $js;
	}

	/**
	 * Set locale
	 *
	 * @see http://php.net/setlocale
	 */
	private function setLocale()
	{
		$locale = $GLOBALS['Piwik_translations']['General_Locale'];
		$locale_variant = str_replace('UTF-8', 'UTF8', $locale);
		setlocale(LC_ALL, $locale, $locale_variant);
		setlocale(LC_CTYPE, '');
	}
}

/**
 * Returns translated string or given message if translation is not found.
 *
 * @param string $string Translation string index
 * @param array $args sprintf arguments
 * @return string
 */
function Piwik_Translate($string, $args = array())
{
	if(!is_array($args))
	{
		$args = array($args);
	}
	if(isset($GLOBALS['Piwik_translations'][$string]))
	{
		$string = $GLOBALS['Piwik_translations'][$string];
	}
	if(count($args) == 0)
	{
		return $string;
	}
	return vsprintf($string, $args);
}

/**
 * Returns translated string or given message if translation is not found.
 * This function does not throw any exception. Use it to translate exceptions.
 *
 * @param string $message Translation string index
 * @param array $args sprintf arguments
 * @return string
 */
function Piwik_TranslateException($message, $args = array())
{
	try
	{
		return Piwik_Translate($message, $args);
	}
	catch(Exception $e)
	{
		return $message;
	}
}


text:
import unittest

from onnx import defs, helper

class TestRelu(unittest.TestCase):
    def test_relu(self) -> None:
        self.assertTrue(defs.has("Relu"))
        helper.make_node("Relu", ["X"], ["Y"])

if __name__ == "__main__":
    unittest.main()


text:
<?php

/**
 * Created by PhpStorm.
 * User: Leonardo Shinagawa
 * Date: 21/04/14
 * Time: 22:33
 */
class InfinityTest extends PHPUnit_Framework_TestCase
{

    public function testGeneralUse()
    {
        $infinity = new \ebussola\common\datatype\number\Infinity('+');
        $this->assertTrue($infinity->isPositive());
        $infinity = new \ebussola\common\datatype\number\Infinity('-');
        $this->assertTrue($infinity->isNegative());
    }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Triton Engine: Tri::Graphic::IDraw Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Triton Engine
    Test Version 1.0.0-pa1

The open-source game engine by Triant Entertainment

Main Page

Modules

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Public Member Functions |
Public Attributes |
Protected Attributes |
List of all members

Tri::Graphic::IDraw Class Referenceabstract

#include <render.h>

Inheritance diagram for Tri::Graphic::IDraw:

  <map id="Tri::Graphic::IDraw_map" name="Tri::Graphic::IDraw_map">
<area href="class_tri_1_1_graphic_1_1_draw2_d.html" alt="Tri::Graphic::Draw2D" shape="rect" coords="0,56,130,80"/>
<area href="class_tri_1_1_graphic_1_1_draw3_d.html" alt="Tri::Graphic::Draw3D" shape="rect" coords="140,56,270,80"/>
<area href="class_tri_1_1_graphic_1_1_text.html" alt="Tri::Graphic::Text" shape="rect" coords="0,112,130,136"/>
</map>

Public Member Functions

virtual void 	Update (int tick)=0

 	The logical update function for IDraw.  More...

virtual void 	Render ()=0

 	The graphical function for IDraw.  More...

Shader::ShaderProgram 	GetShader ()

virtual Mat4 	GetModelMatrix ()=0

Public Attributes

bool 	mKeepUp = false

 	Boolean to determine whether to keep the object up after closing the Graphic Engine.  More...

Protected Attributes

unsigned long 	mId

Shader::ShaderProgram 	mShaderProgram

Detailed Description

Definition at line 44 of file render.h.

Member Function Documentation

          virtual Mat4 Tri::Graphic::IDraw::GetModelMatrix
          (
          	)

pure virtual

Implemented in Tri::Graphic::Draw3D, and Tri::Graphic::Draw2D.

          Shader::ShaderProgram Tri::Graphic::IDraw::GetShader
          (
          	)

          virtual void Tri::Graphic::IDraw::Render
          (
          	)

pure virtual

The graphical function for IDraw.

Use for Graphical Manipulations

          virtual void Tri::Graphic::IDraw::Update
          (
          int
          tick	)

pure virtual

The logical update function for IDraw.

Use for positional changes

Member Data Documentation

          unsigned long Tri::Graphic::IDraw::mId

protected

Definition at line 47 of file render.h.

          bool Tri::Graphic::IDraw::mKeepUp = false

Boolean to determine whether to keep the object up after closing the Graphic Engine.

Definition at line 50 of file render.h.

          Shader::ShaderProgram Tri::Graphic::IDraw::mShaderProgram

protected

Definition at line 48 of file render.h.

The documentation for this class was generated from the following file:

graphic/render.h

Tri

Graphic

IDraw

Generated on Mon May 4 2015 03:29:50 for Triton Engine by

     1.8.9.1


text:
import sys, os
import ConfigParser, argparse

sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import pre

# config files
config = ConfigParser.SafeConfigParser()
config.read('pre.cfg')

url       = config.get('pre', 'Url')
accesskey = config.get('pre', 'Accesskey')
verify    = config.getboolean('pre', 'VerifyCertificate')

# command line args
parser = argparse.ArgumentParser(description="Show Pre.im database information")
parser.add_argument('-s', '--sections', action='store_true', help='List all sections in the database')
args = parser.parse_args()

# query
r = pre.Releases(url, accesskey, verify)

# print the results
if args.sections:
    sections = r.sections()
    for section in sections: print section
else:
    stats = r.stats()
    print stats


text:
import sys
sys.path.append('../cvk2')
import cvk2
import cv2
import httplib
import microsoftCogServicesHelper as msCogServs
import numpy as np
import requests
import socket
import urllib
import utils
import time
import threading

_CVkey = 'e80f8ece393f4eebb3d98b0bb36f04d0'
_translatorKey = '420c6ab49ed1449db517207d6aef32d9'

token = None

# translatedLang = "ru"
translatedLang = "es"
# translatedLang = "fr"
# translatedLang = "no"

streamURLS = 'http://130.58.100.149:8080//video'

timeIntervals = [5, 120]

def processImages(img):
	# Computer Vision parameters
	params = { 'visualFeatures' : 'Categories, Tags, Description, Faces'}

	if translatedLang == 'chinese':
		params['language'] = 'zh'
	else:
		params['language'] = 'en'

	headers = dict()
	headers['Ocp-Apim-Subscription-Key'] = _CVkey
	headers['Content-Type'] = 'application/octet-stream'

	json = None

	img_str = cv2.imencode('.jpg', img)[1].tostring()
	result = msCogServs.processCVRequest( json, img_str, headers, params)

	return result

def translateSentence(sentence):
	textToTranslate = sentence

	translatorHeaders = dict()
	translatorHeaders['Accept'] = 'application/xml'
	translatorParameters = dict()
	translatorParameters['appid'] = 'Bearer' + ' ' + token
	translatorParameters['text'] = textToTranslate
	translatorParameters['to'] = translatedLang
	translatorParameters['contentType'] = "text/plain"

	translation = msCogServs.processTranslationRequest(translatorHeaders, translatorParameters)

	print "textToTranslate: ", textToTranslate, " and translation: ", translation.content
	length = len(translation.content)
	translationCleaned = translation.content[68:length - 10]
	return translationCleaned

def processImageDescriptions(processedImageDescriptions):

	description = processedImageDescriptions['description']
	caption = description['captions'][0]['text']
	print caption

	# tags = sorted(description['tags'], key=lambda x: x['confidence'])
	# print tags
	tags = [""]

	return caption, tags

def handleTranslations(sentence, wordArray):
	print "~~~~~~~~~~~~~~~ NOW TRANSLATING ~~~~~~~~~~~~~~~"

	return translateSentence(sentence), [""]

def runStream(debug = False):
	print "Hi streamURLS: ", streamURLS

	stream = urllib.urlopen(streamURLS)
	bytes = ''

	# for setting up udp
	# ip = "0.0.0.0"
	# port = 5005

	# sock = socket.socket(socket.AF_INET, # Internet
	#          socket.SOCK_DGRAM) # UDP
	# sock.bind((ip, port))
	# sock.setblocking(0)

	print "here2"

	startTime = time.time()

	i = 0

	while True:
		bytes += stream.read(1024)

		a = bytes.find('\xff\xd8')
		b = bytes.find('\xff\xd9')

		if a != -1 and b != -1:
			jpg = bytes[a:b + 2]
			bytes= bytes[b + 2:]
			img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)

			cv2.imshow('img ', img)

			nowTime = time.time()

			if nowTime - startTime > timeIntervals[i]: #TAKE A PICTURE!
				cv2.destroyAllWindows()
				processedImageDescriptions = processImages(img)
				print "take pic"

				print processedImageDescriptions
				caption, wordArray = processImageDescriptions(processedImageDescriptions)
				tCaption, tWordArray = handleTranslations(caption, wordArray)

				# overlay text
				h = img.shape[0]  #Get image height
				cv2.putText(img, tCaption, (16, 16),
	                cv2.FONT_HERSHEY_SIMPLEX, 0.75,
	                (0,100,0), 3, cv2.CV_AA)

				time.sleep(3)

				cv2.imshow('img', img)
				if cv2.waitKey(1000) == 27:
					print "you tried to exit........"
					exit(0)

				time.sleep(30)
				i += 1

				if i > len(timeIntervals):
					break

			# to exit press ESC!
			if cv2.waitKey(15) == 27:
				print "you tried to exit........"
				exit(0)

	# source.release()
	cv2.destroyAllWindows()

def eightMinTimer():
	textHeaders = dict()
	textHeaders['Content-Type'] = 'application/json'
	textHeaders['Accept'] = 'application/jwt'
	textHeaders['Ocp-Apim-Subscription-Key'] = _translatorKey

	while True:
		time.sleep(8 * 60) # sleep for 8 minutes, then get new token

		token = msCogServs.processTokenRequest(textHeaders)

		if token is not None:
			print "YAYAYAYA token worked"
			print token
			now = time.time()
			f = open("token.txt", "w")
			f.write(str(now) + "\n")
			f.write(token)
			f.close()

def translator():
	pass

if __name__ == "__main__":

	f = open("token.txt", 'r')
	firstLine = f.readline()
	lastTokenTime = float(firstLine)
	currentTime = time.time()
	if currentTime - lastTokenTime > 8 * 60: # need new token
		f.close()
		f = open("token.txt", "w")
		textHeaders = dict()
		textHeaders['Content-Type'] = 'application/json'
		textHeaders['Accept'] = 'application/jwt'
		textHeaders['Ocp-Apim-Subscription-Key'] = _translatorKey
		token = msCogServs.processTokenRequest(textHeaders)

		if token is not None:
			print "YAYAYAYA new token worked"
			print token
			now = time.time()
			f.write(str(now) + "\n")
			f.write(token)
		else:
			print "Could not get token for translation. Exiting."
			exit(0)
	else:
		token = f.readline()
		print "successfully read in token: ##", token, "##"

	f.close()

	worker = threading.Thread(target = eightMinTimer)
	worker.daemon = False
	worker.start()

	# worker = threading.Thread(target = translator)
	# worker.daemon = False
	# worker.start()

	runStream()

	if cv2.waitKey(1) == 27:
		exit(0)