text:
/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package eu.scape_project.fcrepo.integration;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import gov.loc.mix.v20.Mix;
import info.lc.xmlns.textmd_v3.TextMD;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.util.Arrays;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.purl.dc.elements._1.ElementContainer;
import org.purl.dc.elements._1.SimpleLiteral;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import edu.harvard.hul.ois.xml.ns.fits.fits_output.Fits;
import eu.scape_project.model.BitStream;
import eu.scape_project.model.File;
import eu.scape_project.model.Identifier;
import eu.scape_project.model.IntellectualEntity;
import eu.scape_project.model.IntellectualEntityCollection;
import eu.scape_project.model.LifecycleState;
import eu.scape_project.model.LifecycleState.State;
import eu.scape_project.model.Representation;
import eu.scape_project.model.TestUtil;
import eu.scape_project.model.VersionList;

/**
 * @author frank asseg
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/integration-tests/managed-content/test-container.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class IntellectualEntitiesIT extends AbstractIT {

    private static final Logger LOG = LoggerFactory
            .getLogger(IntellectualEntitiesIT.class);

    @Test
    public void testIngestAndCheckNonExistantMetadata() throws Exception {
        Representation r = new Representation.Builder()
            .rights(TestUtil.createPremisRightsRecord())
            .identifier(new Identifier("rep-27"))
            .source(TestUtil.createDCSourceRecord())
            .build();
        IntellectualEntity ie = new IntellectualEntity.Builder(TestUtil.createTestEntity("entity-27"))
            .representations(Arrays.asList(r))
            .build();

        this.postEntity(ie);

        HttpGet get = new HttpGet(SCAPE_URL + "/metadata/entity-27/rep-27/RIGHTS");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        assertTrue(EntityUtils.toString(resp.getEntity()).length() > 0);
        get.releaseConnection();

        get = new HttpGet(SCAPE_URL + "/metadata/entity-27/rep-27/SOURCE");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        assertTrue(EntityUtils.toString(resp.getEntity()).length() > 0);
        get.releaseConnection();

        get = new HttpGet(SCAPE_URL + "/metadata/entity-27/rep-27/TECHNICAL");
        resp = this.client.execute(get);
        assertEquals(404, resp.getStatusLine().getStatusCode());
        get.releaseConnection();

        get = new HttpGet(SCAPE_URL + "/metadata/entity-27/rep-27/PROVENANCE");
        resp = this.client.execute(get);
        assertEquals(404, resp.getStatusLine().getStatusCode());
        get.releaseConnection();
}

    @Test
    public void testIngestIntellectualEntityAndCheckinFedora() throws Exception {
        IntellectualEntity ie = TestUtil.createTestEntity("entity-1");
        this.postEntity(ie);

        HttpGet get =
                new HttpGet(FEDORA_URL + "/objects/scape/entities/entity-1");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        assertTrue(EntityUtils.toString(resp.getEntity()).length() > 0);
        get.releaseConnection();
    }

    @Test
    public void testIngestAndRetrieveIntellectualEntity() throws Exception {
        IntellectualEntity ie =
                TestUtil.createTestEntityWithMultipleRepresentations("entity-2");
        this.postEntity(ie);

        HttpGet get = new HttpGet(SCAPE_URL + "/entity/entity-2");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        IntellectualEntity fetched =
                this.marshaller.deserialize(IntellectualEntity.class, resp
                        .getEntity().getContent());
        assertEquals(ie.getIdentifier(), fetched.getIdentifier());
        assertEquals(LifecycleState.State.INGESTED, fetched.getLifecycleState()
                .getState());
        assertEquals(ie.getRepresentations().size(), fetched
                .getRepresentations().size());
        assertNotNull(ie.getDescriptive());
        assertEquals(ElementContainer.class, ie.getDescriptive().getClass());

        for (Representation r : fetched.getRepresentations()) {
            assertTrue(r.getFiles().size() > 0);
            assertNotNull(r.getTechnical());
            assertNotNull(r.getProvenance());
            assertNotNull(r.getRights());
            assertNotNull(r.getSource());

            for (File f : r.getFiles()) {
                assertNotNull(f.getBitStreams());
                assertTrue(f.getBitStreams().size() > 0);
                assertNotNull(f.getTechnical());
                for (BitStream bs : f.getBitStreams()) {
                    assertNotNull(bs.getTechnical());
                }
            }
        }
        get.releaseConnection();
    }

    @Test
    public void testIngestAndRetrieveIntellectualEntityWithRefs()
            throws Exception {
        IntellectualEntity ie =
                TestUtil.createTestEntityWithMultipleRepresentations("entity-ref-1");
        this.postEntity(ie);

        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/entity/entity-ref-1?useReferences=yes");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String xml = EntityUtils.toString(resp.getEntity());
        System.out.println(xml);
        get.releaseConnection();
    }

    @Test
    public void testIngestAndRetrieveRepresentation() throws Exception {
        IntellectualEntity ie =
                TestUtil.createTestEntityWithMultipleRepresentations("entity-3");
        this.postEntity(ie);
        this.marshaller.serialize(ie, System.out);

        for (Representation rep : ie.getRepresentations()) {
            HttpGet get =
                    new HttpGet(SCAPE_URL + "/representation/entity-3/" +
                            rep.getIdentifier().getValue());
            HttpResponse resp = this.client.execute(get);
            assertEquals(200, resp.getStatusLine().getStatusCode());
            Representation fetched =
                    this.marshaller.deserialize(Representation.class, resp
                            .getEntity().getContent());
            assertEquals(rep.getIdentifier().getValue(), fetched
                    .getIdentifier().getValue());
            get.releaseConnection();
        }
    }

    @Test
    public void testIngestAndRetrieveFile() throws Exception {
        IntellectualEntity ie = TestUtil.createTestEntity("entity-4");
        this.postEntity(ie);

        Representation rep = ie.getRepresentations().get(0);
        File f = ie.getRepresentations().get(0).getFiles().get(0);
        HttpGet get =
                new HttpGet(SCAPE_URL + "/file/entity-4/" +
                        rep.getIdentifier().getValue() + "/" +
                        f.getIdentifier().getValue());
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        assertEquals("image/png", resp.getFirstHeader("Content-Type")
                .getValue());
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        IOUtils.copy(resp.getEntity().getContent(), sink);
        ByteArrayOutputStream orig =new ByteArrayOutputStream();
        IOUtils.copy(this.getClass().getClassLoader().getResourceAsStream("scape_logo.png"), orig);

        assertArrayEquals(sink.toByteArray(), orig.toByteArray());
    }

    @Test
    public void testIngestAndRetrieveBitstream() throws Exception {
        IntellectualEntity ie =
                TestUtil.createTestEntityWithMultipleRepresentations("entity-5");
        this.postEntity(ie);

        Representation rep = ie.getRepresentations().get(0);
        File f = rep.getFiles().get(0);
        BitStream bs = f.getBitStreams().get(0);
        HttpGet get =
                new HttpGet(SCAPE_URL + "/bitstream/entity-5/" +
                        rep.getIdentifier().getValue() + "/" +
                        f.getIdentifier().getValue() + "/" +
                        bs.getIdentifier().getValue());
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        BitStream fetched =
                (BitStream) this.marshaller.deserialize(resp.getEntity()
                        .getContent());
        assertEquals(bs.getIdentifier().getValue(), fetched.getIdentifier()
                .getValue());
        get.releaseConnection();
    }

    @Test
    public void testIngestAndRetrieveLifeCycle() throws Exception {
        IntellectualEntity ie =
                TestUtil.createTestEntityWithMultipleRepresentations("entity-6");
        this.postEntity(ie);

        /* check the lifecycle state */
        HttpGet get = new HttpGet(SCAPE_URL + "/lifecycle/entity-6");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        LifecycleState state =
                (LifecycleState) this.marshaller.deserialize(resp.getEntity()
                        .getContent());
        assertEquals(LifecycleState.State.INGESTED, state.getState());
        get.releaseConnection();
    }

    @Test
    public void testIngestAndRetrieveMetadata() throws Exception {
        IntellectualEntity ie =
                TestUtil.createTestEntityWithMultipleRepresentations("entity-7");
        this.postEntity(ie);

        /* check the desc metadata of the entity */
        HttpGet get = new HttpGet(SCAPE_URL + "/metadata/entity-7/DESCRIPTIVE");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());

        Object md = this.marshaller.deserialize(resp.getEntity().getContent());
        assertEquals(md.getClass(), ElementContainer.class);
        get.releaseConnection();

        /* check the tech metadata of the rep */
        get =
                new HttpGet(SCAPE_URL +
                        "/metadata/entity-7/" +
                        ie.getRepresentations().get(0).getIdentifier()
                                .getValue() + "/TECHNICAL");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());

        md = this.marshaller.deserialize(resp.getEntity().getContent());
        assertEquals(md.getClass(), TextMD.class);
        get.releaseConnection();
    }

    @Test
    public void testIngestAndRetrieveIntellectualEntityCollection()
            throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-8");
        this.postEntity(ie1);

        IntellectualEntity ie2 = TestUtil.createTestEntity("entity-9");
        this.postEntity(ie2);

        /* check the desc metadata of the entity */
        HttpPost post = new HttpPost(SCAPE_URL + "/entity-list");
        String uriList =
                FEDORA_URL + "/scape/entity/entity-8\n" + FEDORA_URL +
                        "scape/entity/entity-9";
        post.setEntity(new StringEntity(uriList, ContentType
                .parse("text/uri-list")));
        HttpResponse resp = this.client.execute(post);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        IntellectualEntityCollection coll =
                this.marshaller.deserialize(IntellectualEntityCollection.class,
                        resp.getEntity().getContent());
        post.releaseConnection();
        assertEquals(2, coll.getEntities().size());
    }

    @Test
    public void testIngestAsyncAndRetrieveLifeCycle() throws Exception {
        IntellectualEntity ie =
                TestUtil.createTestEntityWithMultipleRepresentations("entity-10");
        HttpPost post = new HttpPost(SCAPE_URL + "/entity-async");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(ie, sink);
        post.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size()));
        HttpResponse resp = this.client.execute(post);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String id = EntityUtils.toString(resp.getEntity());
        assertTrue(id.length() > 0);

        /* check the lifecycle state and wait for the entity to be ingested */
        LifecycleState state;
        long start = System.currentTimeMillis();
        do {
            HttpGet get = new HttpGet(SCAPE_URL + "/lifecycle/" + id);
            resp = this.client.execute(get);
            assertEquals(200, resp.getStatusLine().getStatusCode());
            state =
                    (LifecycleState) this.marshaller.deserialize(resp
                            .getEntity().getContent());
            get.releaseConnection();
        } while (!state.getState().equals(State.INGESTED) &&
                (System.currentTimeMillis() - start) < 60000);
        assertEquals(State.INGESTED, state.getState());
    }

    @Test
    public void testIngestAndSearchRepresentation() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-13");
        this.postEntity(ie1);

        IntellectualEntity ie2 = TestUtil.createTestEntity("entity-14");
        this.postEntity(ie2);

        /* search via SRU */
        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/sru/representations?version=1&operation=searchRetrieve&query=*");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String xml = EntityUtils.toString(resp.getEntity(), "UTF-8");
        System.out.println(xml);
        assertTrue(0 < xml.length());
        assertTrue(xml
                .indexOf("<scape:identifier type=\"String\"><scape:value>representation-1</scape:value></scape:identifier>") > 0);
        get.releaseConnection();

    }

    @Test
    public void testIngestAndSearchFile() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-15");
        this.postEntity(ie1);

        IntellectualEntity ie2 = TestUtil.createTestEntity("entity-16");
        this.postEntity(ie2);

        /* search via SRU */
        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/sru/files?version=1&operation=searchRetrieve&query=*");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String xml = EntityUtils.toString(resp.getEntity(), "UTF-8");
        assertTrue(0 < xml.length());
        assertTrue(xml
                .indexOf("<scape:identifier type=\"String\"><scape:value>file-1</scape:value></scape:identifier>") > 0);
        get.releaseConnection();

        /* search via SRU for exetension png */
        get =
                new HttpGet(SCAPE_URL +
                        "/sru/files?version=1&operation=searchRetrieve&query=png");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        xml = EntityUtils.toString(resp.getEntity(), "UTF-8");
        assertTrue(0 < xml.length());
        assertTrue(xml
                .indexOf("<scape:identifier type=\"String\"><scape:value>file-1</scape:value></scape:identifier>") > 0);
        get.releaseConnection();
    }

    @Test
    public void testIngestAndUpdateIntellectualEntity() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-17");
        this.postEntity(ie1);

        org.purl.dc.elements._1.ObjectFactory dcFac =
                new org.purl.dc.elements._1.ObjectFactory();
        ElementContainer cnt = dcFac.createElementContainer();
        SimpleLiteral lit_title = new SimpleLiteral();
        lit_title.getContent().add("Object Updated");
        cnt.getAny().add(dcFac.createTitle(lit_title));

        IntellectualEntity ie2 =
                new IntellectualEntity.Builder(ie1).descriptive(cnt).build();

        /* update the current object */
        HttpPut put = new HttpPut(SCAPE_URL + "/entity/entity-17");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(ie2, sink);
        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* check that the new version is returned */
        HttpGet get = new HttpGet(SCAPE_URL + "/entity/entity-17");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        IntellectualEntity fetched =
                this.marshaller.deserialize(IntellectualEntity.class, resp
                        .getEntity().getContent());
        get.releaseConnection();
        assertNotNull(fetched.getDescriptive());
        assertEquals(ElementContainer.class, fetched.getDescriptive()
                .getClass());
        ElementContainer dc = (ElementContainer) fetched.getDescriptive();
        assertEquals("Object Updated", dc.getAny().get(0).getValue()
                .getContent().get(0));

        /* check that the old version is returned when specifically asked for */
        get = new HttpGet(SCAPE_URL + "/entity/entity-17/1");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        fetched =
                this.marshaller.deserialize(IntellectualEntity.class, resp
                        .getEntity().getContent());
        get.releaseConnection();
        assertNotNull(fetched.getDescriptive());
        assertEquals(ElementContainer.class, fetched.getDescriptive()
                .getClass());
        dc = (ElementContainer) fetched.getDescriptive();
        assertEquals("Object 1", dc.getAny().get(0).getValue().getContent()
                .get(0));

        /* check that the new version is returned when specifically asked for */
        get = new HttpGet(SCAPE_URL + "/entity/entity-17/2");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        fetched =
                this.marshaller.deserialize(IntellectualEntity.class, resp
                        .getEntity().getContent());
        get.releaseConnection();
        assertNotNull(fetched.getDescriptive());
        assertEquals(ElementContainer.class, fetched.getDescriptive()
                .getClass());
        dc = (ElementContainer) fetched.getDescriptive();
        assertEquals("Object Updated", dc.getAny().get(0).getValue()
                .getContent().get(0));
    }

    @Test
    public void testIngestAndUpdateRepresentation() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-18");
        this.postEntity(ie1);

        Representation r =
                new Representation.Builder(ie1.getRepresentations().get(0))
                        .title("title update").build();

        HttpPut put =
                new HttpPut(SCAPE_URL + "/representation/entity-18/" +
                        r.getIdentifier().getValue());
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(r, sink);
        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the representation and check that the title has been updated */
        HttpGet get =
                new HttpGet(SCAPE_URL + "/representation/entity-18/" +
                        r.getIdentifier().getValue());
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        Representation fetched =
                this.marshaller.deserialize(Representation.class, resp
                        .getEntity().getContent());
        assertEquals(r.getIdentifier().getValue(), fetched.getIdentifier()
                .getValue());
        assertEquals("title update", fetched.getTitle());
        get.releaseConnection();

    }

    @Test
    public void testIngestAndUpdateEntityMetadata() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-19");
        this.postEntity(ie1);

        org.purl.dc.elements._1.ObjectFactory dcFac =
                new org.purl.dc.elements._1.ObjectFactory();
        ElementContainer cnt = dcFac.createElementContainer();
        SimpleLiteral lit_title = new SimpleLiteral();
        lit_title.getContent().add("DC metadata updated");
        cnt.getAny().add(dcFac.createTitle(lit_title));

        HttpPut put =
                new HttpPut(SCAPE_URL + "/metadata/entity-19/DESCRIPTIVE");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(cnt, sink);

        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the entity and check that the title has been updated */
        HttpGet get =
                new HttpGet(SCAPE_URL + "/metadata/entity-19/DESCRIPTIVE");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        ElementContainer fetched =
                (ElementContainer) this.marshaller.deserialize(resp.getEntity()
                        .getContent());
        assertEquals("DC metadata updated", fetched.getAny().get(0).getValue()
                .getContent().get(0));
        get.releaseConnection();

    }

    @Test
    public void testIngestAndUpdateRepresentationMetadata() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-20");
        this.postEntity(ie1);

        org.purl.dc.elements._1.ObjectFactory dcFac =
                new org.purl.dc.elements._1.ObjectFactory();
        ElementContainer cnt = dcFac.createElementContainer();
        SimpleLiteral lit_title = new SimpleLiteral();
        lit_title.getContent().add("SOURCE metadata updated");
        cnt.getAny().add(dcFac.createTitle(lit_title));

        HttpPut put =
                new HttpPut(SCAPE_URL +
                        "/metadata/entity-20/representation-1/SOURCE");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(cnt, sink);

        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the entity and check that the title has been updated */
        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/metadata/entity-20/representation-1/SOURCE");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        ElementContainer fetched =
                (ElementContainer) this.marshaller.deserialize(resp.getEntity()
                        .getContent());
        assertEquals("SOURCE metadata updated", fetched.getAny().get(0)
                .getValue().getContent().get(0));
        get.releaseConnection();

    }

    @Test
    public void testIngestAndUpdateFileMetadata() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-21");
        this.postEntity(ie1);

        HttpPut put =
                new HttpPut(SCAPE_URL +
                        "/metadata/entity-21/representation-1/file-1/TECHNICAL");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(TestUtil.createFITSRecord(), sink);

        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the entity and check that the title has been updated */
        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/metadata/entity-21/representation-1/file-1/TECHNICAL");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        Object fetched =
                this.marshaller.deserialize(resp.getEntity().getContent());
        assertEquals(Fits.class, fetched.getClass());
        get.releaseConnection();

    }

    @Test
    public void testIngestAndUpdateBistreamMetadata() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-22");
        this.postEntity(ie1);

        HttpPut put =
                new HttpPut(SCAPE_URL +
                        "/metadata/entity-22/representation-1/file-1/bitstream-1/TECHNICAL");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(TestUtil.createMIXRecord(), sink);

        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the entity and check that the title has been updated */
        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/metadata/entity-22/representation-1/file-1/bitstream-1/TECHNICAL");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        Object fetched =
                this.marshaller.deserialize(resp.getEntity().getContent());
        assertEquals(Mix.class, fetched.getClass());
        get.releaseConnection();

    }

    @Test
    public void testIngestAndFetchVersionList() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-23");
        this.postEntity(ie1);

        HttpPut put =
                new HttpPut(SCAPE_URL +
                        "/metadata/entity-23/representation-1/file-1/bitstream-1/TECHNICAL");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(TestUtil.createMIXRecord(), sink);

        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the entity and check that the title has been updated */
        HttpGet get = new HttpGet(SCAPE_URL + "/entity-version-list/entity-23");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        VersionList fetched =
                (VersionList) this.marshaller.deserialize(resp.getEntity()
                        .getContent());
        assertEquals(2, fetched.getVersionIdentifiers().size());
        get.releaseConnection();

    }

    @Test
    public void testIngestAndUpdateRepresentationAndFetchOldVersion()
            throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-24");
        this.postEntity(ie1);

        Representation r =
                new Representation.Builder(ie1.getRepresentations().get(0))
                        .title("title update").build();

        HttpPut put =
                new HttpPut(SCAPE_URL + "/representation/entity-24/" +
                        r.getIdentifier().getValue());
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(r, sink);
        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the representation and check that the title has been updated */
        HttpGet get =
                new HttpGet(SCAPE_URL + "/representation/entity-24/" +
                        r.getIdentifier().getValue() + "/1");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        Representation fetched =
                this.marshaller.deserialize(Representation.class, resp
                        .getEntity().getContent());
        assertEquals(r.getIdentifier().getValue(), fetched.getIdentifier()
                .getValue());
        assertEquals("Text representation", fetched.getTitle());
        get.releaseConnection();

    }

    @Test
    public void testIngestAndUpdateFileAndFetchOldVersion() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-25");
        this.postEntity(ie1);

        File f =
                new File.Builder(ie1.getRepresentations().get(0).getFiles()
                        .get(0)).uri(
                        URI.create(TestUtil.class.getClassLoader().getResource(
                                "scape_logo.png").toString())).filename(
                        "wikipedia.png").mimetype("image/png").build();

        Representation r =
                new Representation.Builder(ie1.getRepresentations().get(0))
                        .title("title update").files(Arrays.asList(f)).build();

        HttpPut put =
                new HttpPut(SCAPE_URL + "/representation/entity-25/" +
                        r.getIdentifier().getValue());
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(r, sink);
        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the file */
        HttpGet get =
                new HttpGet(SCAPE_URL + "/file/entity-25/" +
                        r.getIdentifier().getValue() + "/" +
                        f.getIdentifier().getValue() + "/1");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        get.releaseConnection();

    }

    @Test
    public void testIngestAndUpdateBitstreamAndFetchOldVersion()
            throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-26");
        this.postEntity(ie1);

        HttpPut put =
                new HttpPut(SCAPE_URL +
                        "/metadata/entity-26/representation-1/file-1/bitstream-1/TECHNICAL");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(TestUtil.createMIXRecord(), sink);

        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink
                .toByteArray()), sink.size(), ContentType.TEXT_XML));
        HttpResponse resp = this.client.execute(put);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        put.releaseConnection();

        /* fetch the entity and check that the title has been updated */
        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/bitstream/entity-26/representation-1/file-1/bitstream-1/1");
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        BitStream fetched =
                (BitStream) this.marshaller.deserialize(resp.getEntity()
                        .getContent());
        assertEquals(Fits.class, fetched.getTechnical().getClass());
        get.releaseConnection();

    }

    @Test
    public void testIngestAndSearchEntity() throws Exception {
        IntellectualEntity ie1 = TestUtil.createTestEntity("entity-11");
        this.postEntity(ie1);

        IntellectualEntity ie2 = TestUtil.createTestEntity("entity-12");
        this.postEntity(ie2);

        /* search via SRU */
        HttpGet get =
                new HttpGet(SCAPE_URL +
                        "/sru/entities?version=1&operation=searchRetrieve&query=*");
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String xml = EntityUtils.toString(resp.getEntity(), "UTF-8");
        System.out.println(xml);
        assertTrue(0 < xml.length());
        get.releaseConnection();

    }
}


text:
using System.IO;
using System.Threading.Tasks;
using Util.Exceptions;
using Util.Files.Paths;
using Util.Helpers;

namespace Util.Files {
    /// <summary>
    /// 本地文件存储服务
    /// </summary>
    public class DefaultFileStore : IFileStore {
        /// <summary>
        /// 路径生成器
        /// </summary>
        private readonly IPathGenerator _generator;

        /// <summary>
        /// 初始化本地文件存储服务
        /// </summary>
        /// <param name="pathGenerator">路径生成器</param>
        public DefaultFileStore( IPathGenerator pathGenerator ) {
            _generator = pathGenerator;
        }

        /// <summary>
        /// 保存文件,返回完整文件路径 w
        /// </summary>
        public async Task<string> SaveAsync() {
            var fileControl = Web.GetFile();
            var path = _generator.Generate( fileControl.FileName );
            var physicalPath = Common.GetWebRootPath( path );
            var directory = Path.GetDirectoryName( physicalPath );
            if( string.IsNullOrEmpty( directory ) )
                throw new Warning( "上传失败" );
            if( Directory.Exists( directory ) == false )
                Directory.CreateDirectory( directory );
            using( var stream = new FileStream( physicalPath, FileMode.Create ) ) {
                await fileControl.CopyToAsync( stream );
            }
            return path;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;
using Xunit;

namespace System.Time.Tests
{
    public class TimeOfDayFormattingTests
    {
        public TimeOfDayFormattingTests()
        {
            CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
            CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
        }

        [Fact]
        public void ToLongTimeString()
        {
            var time = new TimeOfDay(10, 49, 12, Meridiem.PM);
            var s = time.ToLongTimeString();
            Assert.Equal("22:49:12", s);
        }

        [Fact]
        public void ToLongTimeStringInvariant()
        {
            var time = new TimeOfDay(10, 49, 12, Meridiem.PM);
            var s = time.ToLongTimeStringInvariant();
            Assert.Equal("22:49:12", s);
        }

        [Fact]
        public void ToShortTimeString()
        {
            var time = new TimeOfDay(22, 49);
            var s = time.ToShortTimeString();
            Assert.Equal("22:49", s);
        }

        [Fact]
        public void ToShortTimeStringInvariant()
        {
            var time = new TimeOfDay(22, 49);
            var s = time.ToShortTimeStringInvariant();
            Assert.Equal("22:49", s);
        }

        [Fact]
        public void ToStringWithStandardTimeFormat()
        {
            var time = new TimeOfDay(23, 59, 59);
            var s = time.ToString("t");
            Assert.Equal("23:59", s);
        }

        [Fact]
        public void ToStringWithNullTimeFormat()
        {
            var time = new TimeOfDay(23, 59, 59);
            var s = time.ToString((string) null);
            Assert.Equal("23:59:59", s);
        }

        [Fact]
        public void ToStringWithEmptyTimeFormat()
        {
            var time = new TimeOfDay(23, 59, 59);
            var s = time.ToString("");
            Assert.Equal("23:59:59", s);
        }

        [Fact]
        public void ToStringWithCustomTimeFormat()
        {
            var time = new TimeOfDay(23, 59, 59);
            var s = time.ToString("HH:mm:ss");
            Assert.Equal("23:59:59", s);
        }

        [Fact]
        public void ToStringWithISOTimeFormat_O()
        {
            var time = new TimeOfDay(23, 59, 59);
            var s = time.ToString("O");
            Assert.Equal("23:59:59.0000000", s);
        }

        [Fact]
        public void ToStringWithISOTimeFormat_o()
        {
            var time = new TimeOfDay(23, 59, 59);
            var s = time.ToString("o");
            Assert.Equal("23:59:59.0000000", s);
        }

        [Fact]
        public void ToStringWithISOTimeFormat_s()
        {
            var time = new TimeOfDay(23, 59, 59);
            var s = time.ToString("s");
            Assert.Equal("23:59:59", s);
        }

        [Fact]
        public void ToStringWithCustomDateTimeFormat()
        {
            Assert.Throws<FormatException>(() => new TimeOfDay(23, 59, 59).ToString("yyyy-MM-dd HH:mm:ss"));
        }

        [Fact]
        public void ToStringWithStandardDateFormat()
        {
            Assert.Throws<FormatException>(() => new TimeOfDay(23, 59, 59).ToString("d"));
        }

        [Fact]
        public void ToStringWithCustomDateFormat()
        {
            Assert.Throws<FormatException>(() => new TimeOfDay(23, 59, 59).ToString("dd MMM yyyy"));
        }
    }
}


text:
local log = require "util.logger".init("auth_sql");
local new_sasl = require "util.sasl".new;
local nodeprep = require "util.encodings".stringprep.nodeprep;
local saslprep = require "util.encodings".stringprep.saslprep;
local DBI = require "DBI"
local md5 = require "util.hashes".md5;
local uuid_gen = require "util.uuid".generate;

local connection;
local params = module:get_option("sql");
local table_prefix = module:get_option_string("wordpress_table_prefix", "wp_");

local resolve_relative_path = require "core.configmanager".resolve_relative_path;

local function test_connection()
	if not connection then return nil; end
	if connection:ping() then
		return true;
	else
		module:log("debug", "Database connection closed");
		connection = nil;
	end
end
local function connect()
	if not test_connection() then
		prosody.unlock_globals();
		local dbh, err = DBI.Connect(
			params.driver, params.database,
			params.username, params.password,
			params.host, params.port
		);
		prosody.lock_globals();
		if not dbh then
			module:log("debug", "Database connection failed: %s", tostring(err));
			return nil, err;
		end
		module:log("debug", "Successfully connected to database");
		dbh:autocommit(true); -- don't run in transaction
		connection = dbh;
		return connection;
	end
end

do -- process options to get a db connection
	params = params or { driver = "SQLite3" };

	if params.driver == "SQLite3" then
		params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
	end

	assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");

	assert(connect());
end

local function getsql(sql, ...)
	if params.driver == "PostgreSQL" then
		sql = sql:gsub("`", "\"");
	end
	if not test_connection() then connect(); end
	-- do prepared statement stuff
	local stmt, err = connection:prepare(sql);
	if not stmt and not test_connection() then error("connection failed"); end
	if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
	-- run query
	local ok, err = stmt:execute(...);
	if not ok and not test_connection() then error("connection failed"); end
	if not ok then return nil, err; end

	return stmt;
end
local function setsql(sql, ...)
	local stmt, err = getsql(sql, ...);
	if not stmt then return stmt, err; end
	return stmt:affected();
end

local function get_password(username)
	local stmt, err = getsql("SELECT `user_pass` FROM `"..table_prefix.."users` WHERE `user_login`=?", username);
	if stmt then
		for row in stmt:rows(true) do
			return row.user_pass;
		end
	end
end

local itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
local function hashEncode64(input, count)
	local output = "";
	local i, value = 0, 0;

	while true do
		value = input:byte(i+1)
		i = i+1;
		local idx = value % 0x40 + 1;
		output = output .. itoa64:sub(idx, idx);

		if i < count then
			value = value + input:byte(i+1) * 256;
		end
		local _ = value % (2^6);
		local idx = ((value - _) / (2^6)) % 0x40 + 1
		output = output .. itoa64:sub(idx, idx);

		if i >= count then break; end
		i = i+1;

		if i < count then
			value = value + input:byte(i+1) * 256 * 256;
		end
		local _ = value % (2^12);
		local idx = ((value - _) / (2^12)) % 0x40 + 1
		output = output .. itoa64:sub(idx, idx);

		if i >= count then break; end
		i = i+1;

		local _ = value % (2^18);
		local idx = ((value - _) / (2^18)) % 0x40 + 1
		output = output .. itoa64:sub(idx, idx);

		if not(i < count) then break; end
	end
	return output;
end
local function hashCryptPrivate(password, genSalt)
	local output = "*";
	if not genSalt:match("^%$P%$") then return output; end

	local count_log2 = itoa64:find(genSalt:sub(4,4)) - 1;
	if count_log2 < 7 or count_log2 > 30 then return output; end

	local count = 2 ^ count_log2;
	local salt = genSalt:sub(5, 12);

	if #salt ~= 8 then return output; end

	local hash = md5(salt..password);

	while true do
		hash = md5(hash..password);
		if not(count > 1) then break; end
		count = count-1;
	end

	output = genSalt:sub(1, 12);
	output = output .. hashEncode64(hash, 16);

	return output;
end
local function hashGensaltPrivate(input)
	local iteration_count_log2 = 6;
	local output = "$P$";
	local idx = math.min(iteration_count_log2 + 5, 30) + 1;
	output = output .. itoa64:sub(idx, idx);
	output = output .. hashEncode64(input, 6);
	return output;
end
local function wordpressCheckHash(password, hash)
	if #hash == 32 then return hash == md5(password, true); end
	return #hash == 34 and hashCryptPrivate(password, hash) == hash;
end
local function wordpressCreateHash(password)
	local random = uuid_gen():sub(-6);
	local salt = hashGensaltPrivate(random);
	local hash = hashCryptPrivate(password, salt);
	if #hash == 34 then return hash; end
	return md5(password, true);
end

provider = {};

function provider.test_password(username, password)
	local hash = get_password(username);
	return hash and wordpressCheckHash(password, hash);
end
function provider.user_exists(username)
	module:log("debug", "test user %s existence", username);
	return get_password(username) and true;
end

function provider.get_password(username)
	return nil, "Getting password is not supported.";
end
function provider.set_password(username, password)
	local hash = wordpressCreateHash(password);
	local stmt, err = setsql("UPDATE `"..table_prefix.."users` SET `user_pass`=? WHERE `user_login`=?", hash, username);
	return stmt and true, err;
end
function provider.create_user(username, password)
	return nil, "Account creation/modification not supported.";
end

local escapes = {
	[" "] = "\\20";
	['"'] = "\\22";
	["&"] = "\\26";
	["'"] = "\\27";
	["/"] = "\\2f";
	[":"] = "\\3a";
	["<"] = "\\3c";
	[">"] = "\\3e";
	["@"] = "\\40";
	["\\"] = "\\5c";
};
local unescapes = {};
for k,v in pairs(escapes) do unescapes[v] = k; end
local function jid_escape(s) return s and (s:gsub(".", escapes)); end
local function jid_unescape(s) return s and (s:gsub("\\%x%x", unescapes)); end

function provider.get_sasl_handler()
	local sasl = {};
	function sasl:clean_clone() return provider.get_sasl_handler(); end
	function sasl:mechanisms() return { PLAIN = true; }; end
	function sasl:select(mechanism)
		if not self.selected and mechanism == "PLAIN" then
			self.selected = mechanism;
			return true;
		end
	end
	function sasl:process(message)
		if not message then return "failure", "malformed-request"; end
		local authorization, authentication, password = message:match("^([^%z]*)%z([^%z]+)%z([^%z]+)");
		if not authorization then return "failure", "malformed-request"; end
		authentication = saslprep(authentication);
		password = saslprep(password);
		if (not password) or (password == "") or (not authentication) or (authentication == "") then
			return "failure", "malformed-request", "Invalid username or password.";
		end
		local function test(authentication)
			local prepped = nodeprep(authentication);
			local normalized = jid_unescape(prepped);
			return normalized and provider.test_password(normalized, password) and prepped;
		end
		local username = test(authentication) or test(jid_escape(authentication));
		if username then
			self.username = username;
			return "success";
		end
		return "failure", "not-authorized", "Unable to authorize you with the authentication credentials you've sent.";
	end
	return sasl;
end

module:provides("auth", provider);


text:
using System.Collections.Generic;
using System.Linq;

namespace ExpressMapper.Tests.Model.Models
{
    public class TestItem
    {
        public TestCollection[] Array { get; set; }
        public ICollection<TestCollection> Collection { get; set; }
        public IList<TestCollection> List { get; set; }
        public IEnumerable<TestCollection> Enumerable { get; set; }
        public IQueryable<TestCollection> Queryable { get; set; }
    }
}


text:
<?php

/*
 * This file is part of the Lime test framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 * (c) Bernhard Schussek <bernhard.schussek@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Tests that a value is unlike another.
 *
 * @package    Lime
 * @author     Bernhard Schussek <bernhard.schussek@symfony-project.com>
 * @version    SVN: $Id: LimeConstraintUnlike.php 23701 2009-11-08 21:23:40Z bschussek $
 */
class LimeConstraintUnlike extends LimeConstraint
{
  /**
   * (non-PHPdoc)
   * @see constraint/LimeConstraintInterface#evaluate($value)
   */
  public function evaluate($value)
  {
    try
    {
      LimeTester::create($value)->unlike(LimeTester::create($this->expected));
    }
    catch (LimeAssertionFailedException $e)
    {
      throw new LimeConstraintException(sprintf("         %s\nmatches %s", $e->getActual(), $e->getExpected()));
    }
  }
}


text:
struct StmtVisitor;
struct Stmt;

using StmtVisitorPtr = std::shared_ptr<StmtVisitor>;
using StmtPtr = std::shared_ptr<Stmt>;

struct Stmt {
  virtual void accept(const StmtVisitorPtr& visitor) = 0;
};

class ExprStmt : public Stmt, public Visitable<ExprStmt> {
public:
  ExprPtr expr_;
public:
  ExprStmt(const ExprPtr& expr);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class PrintStmt : public Stmt, public Visitable<PrintStmt> {
public:
  ExprPtr expr_;
public:
  PrintStmt(const ExprPtr& expr);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class VarStmt : public Stmt, public Visitable<VarStmt> {
public:
  Token name_;
  ExprPtr expr_;
public:
  VarStmt(const Token& name, const ExprPtr& expr);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class BlockStmt : public Stmt, public Visitable<BlockStmt> {
public:
  std::vector<StmtPtr> stmts_;
public:
  BlockStmt(const std::vector<StmtPtr>& stmts);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class IfStmt : public Stmt, public Visitable<IfStmt> {
public:
  ExprPtr cond_;
  StmtPtr then_branch_;
  StmtPtr else_branch_;
public:
  IfStmt(const ExprPtr& cond,
      const StmtPtr& then_branch, const StmtPtr& else_branch);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class WhileStmt : public Stmt, public Visitable<WhileStmt> {
public:
  ExprPtr cond_;
  StmtPtr body_;
public:
  WhileStmt(const ExprPtr& cond, const StmtPtr& body);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class FunctionStmt : public Stmt, public Visitable<FunctionStmt> {
  using FunctionPtr = std::shared_ptr<Function>;
public:
  Token name_;
  FunctionPtr function_;
public:
  FunctionStmt(const Token& name, const FunctionPtr& function);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class ReturnStmt : public Stmt, public Visitable<ReturnStmt> {
public:
  Token keyword_;
  ExprPtr value_;
public:
  ReturnStmt(const Token& keyword, const ExprPtr& value);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

class ClassStmt : public Stmt, public Visitable<ClassStmt> {
  using FunctionStmtPtr = std::shared_ptr<FunctionStmt>;
public:
  Token name_;
  ExprPtr super_class_;
  std::vector<FunctionStmtPtr> methods_;
public:
  ClassStmt(const Token& name,
      const ExprPtr& super_class, const std::vector<FunctionStmtPtr>& methods);
  virtual void accept(const StmtVisitorPtr& visitor) override;
};

struct StmtVisitor {
  using ExprStmtPtr = std::shared_ptr<ExprStmt>;
  using PrintStmtPtr = std::shared_ptr<PrintStmt>;
  using VarStmtPtr = std::shared_ptr<VarStmt>;
  using BlockStmtPtr = std::shared_ptr<BlockStmt>;
  using IfStmtPtr = std::shared_ptr<IfStmt>;
  using WhileStmtPtr = std::shared_ptr<WhileStmt>;
  using FunctionStmtPtr = std::shared_ptr<FunctionStmt>;
  using ReturnStmtPtr = std::shared_ptr<ReturnStmt>;
  using ClassStmtPtr = std::shared_ptr<ClassStmt>;

  virtual void visit_expr_stmt(const ExprStmtPtr& stmt) = 0;
  virtual void visit_print_stmt(const PrintStmtPtr& stmt) = 0;
  virtual void visit_var_stmt(const VarStmtPtr& stmt) = 0;
  virtual void visit_block_stmt(const BlockStmtPtr& stmt) = 0;
  virtual void visit_if_stmt(const IfStmtPtr& stmt) = 0;
  virtual void visit_while_stmt(const WhileStmtPtr& stmt) = 0;
  virtual void visit_function_stmt(const FunctionStmtPtr& stmt) = 0;
  virtual void visit_return_stmt(const ReturnStmtPtr& stmt) = 0;
  virtual void visit_class_stmt(const ClassStmtPtr& stmt) = 0;
};


text:
require 'spec_helper'

describe "Example" do
  describe "namespace" do
    it { should == "namespace" }

    it do
      should == "namespace"
    end

    it "should create some (should another)" do
      1.should == 1
    end

    it "should do something" do
      1.should == 1
    end

    it 'should do something' do
      italian = "hi"
      italian.should == "hi"
    end

    it %{should do something} do
      "it".should == "it"
    end
  end
end


text:
/* config.h.  Generated automatically by configure.  */
/* config.h.in.  Generated automatically from configure.in by autoheader.  */

/* Define to empty if the keyword does not work.  */
/* #undef const */

/* Define to one of _getb67, GETB67, getb67 for Cray-2 and Cray-YMP systems.
   This function is required for alloca.c support on those systems.  */
/* #undef CRAY_STACKSEG_END */

/* Define to the type of elements in the array set by `getgroups'.
   Usually this is either `int' or `gid_t'.  */
/* #undef GETGROUPS_T */

/* Define if the `getloadavg' function needs to be run setuid or setgid.  */
/* #undef GETLOADAVG_PRIVILEGED */

/* Define if the `getpgrp' function takes no argument.  */
/* #undef GETPGRP_VOID */

/* Define if you don't have vprintf but do have _doprnt.  */
/* #undef HAVE_DOPRNT */

/* Define if you have the strftime function.  */
#define HAVE_STRFTIME 1

/* Define if you have <sys/wait.h> that is POSIX.1 compatible.  */
#define HAVE_SYS_WAIT_H 1

/* Define if you have the vprintf function.  */
#define HAVE_VPRINTF 1

/* Define as __inline if that's what the C compiler calls it.  */
/* #undef inline */

/* Define as the return type of signal handlers (int or void).  */
#define RETSIGTYPE void

/* Define to `unsigned' if <sys/types.h> doesn't define.  */
/* #undef size_t */

/* Define if you have the ANSI C header files.  */
#define STDC_HEADERS 1

/* Define if you can safely include both <sys/time.h> and <time.h>.  */
#define TIME_WITH_SYS_TIME 1

/* Define if your <sys/time.h> declares struct tm.  */
/* #undef TM_IN_SYS_TIME */

/* The number of bytes in a int.  */
#define SIZEOF_INT 4

/* The number of bytes in a long.  */
#define SIZEOF_LONG 4

/* The number of bytes in a short.  */
#define SIZEOF_SHORT 2

/* The number of bytes in a unsigned.  */
#define SIZEOF_UNSIGNED 4

/* The number of bytes in a unsigned long.  */
#define SIZEOF_UNSIGNED_LONG 4

/* The number of bytes in a unsigned short.  */
#define SIZEOF_UNSIGNED_SHORT 2

/* Define if you have the calloc function.  */
#define HAVE_CALLOC 1

/* Define if you have the chmod function.  */
//#define HAVE_CHMOD 1

/* Define if you have the cygwin_conv_to_full_win32_path function.  */
/* #undef HAVE_CYGWIN_CONV_TO_FULL_WIN32_PATH */

/* Define if you have the getpagesize function.  */
#define HAVE_GETPAGESIZE 1

/* Define if you have the getpid function.  */
#define HAVE_GETPID 1

/* Define if you have the gettimeofday function.  */
#define HAVE_GETTIMEOFDAY 1

/* Define if you have the memmove function.  */
#define HAVE_MEMMOVE 1

/* Define if you have the mkdir function.  */
#undef HAVE_MKDIR

/* Define if you have the nl_langinfo function.  */
#define HAVE_NL_LANGINFO 1

/* Define if you have the png_get_bit_depth function.  */
#define HAVE_PNG_GET_BIT_DEPTH 1

/* Define if you have the png_get_color_type function.  */
#define HAVE_PNG_GET_COLOR_TYPE 1

/* Define if you have the png_get_gAMA function.  */
#define HAVE_PNG_GET_GAMA 1

/* Define if you have the png_get_image_height function.  */
#define HAVE_PNG_GET_IMAGE_HEIGHT 1

/* Define if you have the png_get_image_width function.  */
#define HAVE_PNG_GET_IMAGE_WIDTH 1

/* Define if you have the png_get_sRGB function.  */
#define HAVE_PNG_GET_SRGB 1

/* Define if you have the png_get_valid function.  */
#define HAVE_PNG_GET_VALID 1

/* Define if you have the png_set_rgb_to_gray function.  */
#define HAVE_PNG_SET_RGB_TO_GRAY 1

/* Define if you have the png_set_strip_alpha function.  */
#define HAVE_PNG_SET_STRIP_ALPHA 1

/* Define if you have the popen function.  */
#undef HAVE_POPEN

/* Define if you have the raise function.  */
#undef HAVE_RAISE

/* Define if you have the resume_thread function.  */
/* #undef HAVE_RESUME_THREAD */

/* Define if you have the select function.  */
#define HAVE_SELECT 1

/* Define if you have the setlocale function.  */
#undef HAVE_SETLOCALE

/* Define if you have the setpgid function.  */
#undef HAVE_SETPGID

/* Define if you have the snprintf function.  */
#define HAVE_SNPRINTF 1

/* Define if you have the spawn_thread function.  */
/* #undef HAVE_SPAWN_THREAD */

/* Define if you have the strcspn function.  */
#define HAVE_STRCSPN 1

/* Define if you have the strerror function.  */
#define HAVE_STRERROR 1

/* Define if you have the strptime function.  */
#define HAVE_STRPTIME 1

/* Define if you have the strstr function.  */
#define HAVE_STRSTR 1

/* Define if you have the strtol function.  */
#define HAVE_STRTOL 1

/* Define if you have the strtoll function.  */
#define HAVE_STRTOLL 1

/* Define if you have the strtoq function.  */
#define HAVE_STRTOQ 1

/* Define if you have the strtoul function.  */
#define HAVE_STRTOUL 1

/* Define if you have the tempnam function.  */
#define HAVE_TEMPNAM 1

/* Define if you have the uname function.  */
#define HAVE_UNAME 1

/* Define if you have the <X11/X.h> header file.  */
/* #undef HAVE_X11_X_H */

/* Define if you have the <X11/Xlib.h> header file.  */
/* #undef HAVE_X11_XLIB_H */

/* Define if you have the <X11/Xlocale.h> header file.  */
/* #undef HAVE_X11_XLOCALE_H */

/* Define if you have the <X11/Xutil.h> header file.  */
/* #undef HAVE_X11_XUTIL_H */

/* Define if you have the <atheos/threads.h> header file.  */
/* #undef HAVE_ATHEOS_THREADS_H */

/* Define if you have the <bzlib.h> header file.  */
/* #undef HAVE_BZLIB_H */

/* Define if you have the <dirent.h> header file.  */
#define HAVE_DIRENT_H 1

/* Define if you have the <endian.h> header file.  */
#define HAVE_ENDIAN_H 1

/* Define if you have the <fcntl.h> header file.  */
#define HAVE_FCNTL_H 1

/* Define if you have the <gpm.h> header file.  */
/* #undef HAVE_GPM_H */

/* Define if you have the <gui/bitmap.h> header file.  */
/* #undef HAVE_GUI_BITMAP_H */

/* Define if you have the <gui/desktop.h> header file.  */
/* #undef HAVE_GUI_DESKTOP_H */

/* Define if you have the <gui/view.h> header file.  */
/* #undef HAVE_GUI_VIEW_H */

/* Define if you have the <gui/window.h> header file.  */
/* #undef HAVE_GUI_WINDOW_H */

/* Define if you have the <ieee.h> header file.  */
/* #undef HAVE_IEEE_H */

/* Define if you have the <io.h> header file.  */
/* #undef HAVE_IO_H */

/* Define if you have the <jpeglib.h> header file.  */
#define HAVE_JPEGLIB_H 1

/* Define if you have the <langinfo.h> header file.  */
#define HAVE_LANGINFO_H 1

/* Define if you have the <libpng/png.h> header file.  */
/* #undef HAVE_LIBPNG_PNG_H */

/* Define if you have the <limits.h> header file.  */
#define HAVE_LIMITS_H 1

/* Define if you have the <linux/fb.h> header file.  */
#undef HAVE_LINUX_FB_H

/* Define if you have the <linux/kd.h> header file.  */
#undef HAVE_LINUX_KD_H

/* Define if you have the <linux/vt.h> header file.  */
#undef HAVE_LINUX_VT_H

/* Define if you have the <math.h> header file.  */
#define HAVE_MATH_H 1

/* Define if you have the <ndir.h> header file.  */
/* #undef HAVE_NDIR_H */

/* Define if you have the <netinet/dhcp.h> header file.  */
/* #undef HAVE_NETINET_DHCP_H */

/* Define if you have the <netinet/in_system.h> header file.  */
/* #undef HAVE_NETINET_IN_SYSTEM_H */

/* Define if you have the <netinet/in_systm.h> header file.  */
#undef HAVE_NETINET_IN_SYSTM_H

/* Define if you have the <netinet/ip.h> header file.  */
#undef HAVE_NETINET_IP_H

/* Define if you have the <png.h> header file.  */
#define HAVE_PNG_H 1

/* Define if you have the <setjmp.h> header file.  */
#define HAVE_SETJMP_H 1

/* Define if you have the <sigaction.h> header file.  */
/* #undef HAVE_SIGACTION_H */

/* Define if you have the <sys/cygwin.h> header file.  */
/* #undef HAVE_SYS_CYGWIN_H */

/* Define if you have the <sys/dir.h> header file.  */
/* #undef HAVE_SYS_DIR_H */

/* Define if you have the <sys/fmutex.h> header file.  */
/* #undef HAVE_SYS_FMUTEX_H */

/* Define if you have the <sys/ioctl.h> header file.  */
#define HAVE_SYS_IOCTL_H 1

/* Define if you have the <sys/mman.h> header file.  */
#undef HAVE_SYS_MMAN_H

/* Define if you have the <sys/ndir.h> header file.  */
/* #undef HAVE_SYS_NDIR_H */

/* Define if you have the <sys/resource.h> header file.  */
#undef HAVE_SYS_RESOURCE_H

/* Define if you have the <sys/select.h> header file.  */
#define HAVE_SYS_SELECT_H 1

/* Define if you have the <sys/time.h> header file.  */
#define HAVE_SYS_TIME_H 1

/* Define if you have the <sys/un.h> header file.  */
#define HAVE_SYS_UN_H 1

/* Define if you have the <sys/utsname.h> header file.  */
#define HAVE_SYS_UTSNAME_H 1

/* Define if you have the <tiffio.h> header file.  */
#define HAVE_TIFFIO_H 1

/* Define if you have the <time.h> header file.  */
#define HAVE_TIME_H 1

/* Define if you have the <unistd.h> header file.  */
#define HAVE_UNISTD_H 1

/* Define if you have the <util/application.h> header file.  */
/* #undef HAVE_UTIL_APPLICATION_H */

/* Define if you have the <util/locker.h> header file.  */
/* #undef HAVE_UTIL_LOCKER_H */

/* Define if you have the <values.h> header file.  */
#define HAVE_VALUES_H 1

/* Define if you have the <zlib.h> header file.  */
/* #undef HAVE_ZLIB_H */

/* Define if you have the X11 library (-lX11).  */
/* #undef HAVE_LIBX11 */

/* Define if you have the atheos library (-latheos).  */
/* #undef HAVE_LIBATHEOS */

/* Define if you have the bz2 library (-lbz2).  */
/* #undef HAVE_LIBBZ2 */

/* Define if you have the dl library (-ldl).  */
#undef HAVE_LIBDL

/* Define if you have the gpm library (-lgpm).  */
/* #undef HAVE_LIBGPM */

/* Define if you have the jpeg library (-ljpeg).  */
#define HAVE_LIBJPEG 1

/* Define if you have the m library (-lm).  */
#define HAVE_LIBM 1

/* Define if you have the nsl library (-lnsl).  */
/* #undef HAVE_LIBNSL */

/* Define if you have the png library (-lpng).  */
#define HAVE_LIBPNG 1

/* Define if you have the socket library (-lsocket).  */
/* #undef HAVE_LIBSOCKET */

/* Define if you have the stdc++ library (-lstdc++).  */
/* #undef HAVE_LIBSTDC__ */

/* Define if you have the tiff library (-ltiff).  */
//#define HAVE_LIBTIFF 1

/* Define if you have the z library (-lz).  */
#define HAVE_LIBZ 1

/* Name of package */
#define PACKAGE "links"

/* Version number of package */
#define VERSION "2.1pre30"

/* Define to 1 if NLS is requested.  */
/* #undef ENABLE_NLS */

/* Define as 1 if you have catgets and don't want to use GNU gettext.  */
/* #undef HAVE_CATGETS */

/* Define as 1 if you have gettext and don't want to use GNU gettext.  */
/* #undef HAVE_GETTEXT */

/* Define if your locale.h file contains LC_MESSAGES.  */
/* #undef HAVE_LC_MESSAGES */

/* Define to 1 if you have the stpcpy function.  */
/* #undef HAVE_STPCPY */

/* */
#define HAVE_TYPEOF 1

/* */
#define HAVE_LONG_LONG 1

/* */
#define HAVE_SIGSETJMP 1

/* */
#undef HAVE_CHMOD

/* */
/* #undef HAVE_ALARM */

/* */
#define HAVE_CFMAKERAW 1

/* */
#define HAVE_GETHOSTBYADDR 1

/* */
/* #undef HAVE_DHCP_OPTION */

/* */
#define HAVE_HERROR 1

/* */
/* #undef HAVE_BEGINTHREAD */

/* */
/* #undef HAVE_MOUOPEN */

/* */
/* #undef HAVE_READ_KBD */

/* */
/* #undef HAVE_CLONE */

/* */
/* #undef HAVE_PTHREADS */

/* */
/* #undef HAVE_SSL */

/* */
/* #undef HAVE_ZLIB */

/* */
/* #undef HAVE_BZIP2 */

/* */
/* #undef X2 */

/* */
#define DEBUGLEVEL 2

/* */
/* #undef JS */

/* */
/* #undef HAVE_PCRE */

/* */
/* #undef HAVE_REGEX */

/* */
/* #undef CHCEME_FLEXI_LIBU */

/* By PerM's ideological comittee */
#define VERSION "2.1pre30"

/* */
#define G 1

/* */
/* #undef GRDRV_SVGALIB */

/* */
/* #undef GRDRV_FB */

/* */
/* #undef GRDRV_DIRECTFB */

/* */
/* #undef GRDRV_PMSHELL */

/* */
#ifndef GRDRV_X
#undef GRDRV_X
#define NCE_WINDOWS 1
#endif
/* */
/* #undef GRDRV_SDL */

/* */
/* #undef GRDRV_ATHEOS */

/* */
/* #undef DONT_INCLUDE_SETJMP */

/* Tiff by Brain */
//#define HAVE_TIFF 1

/* Jpeg by Clock */
#define HAVE_JPEG 1

/* */
/* #undef C_BIG_ENDIAN */

/* */
#define C_LITTLE_ENDIAN 1

/* */
#define RENAME_OVER_EXISTING_FILES 1

/* */
#define HAVE_SOCKLEN_T 1


text:
"""
byceps.services.orga.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from dataclasses import dataclass
from datetime import date
from typing import Optional

from ....util.datetime.calc import calculate_age, calculate_days_until
from ....util.datetime.monthday import MonthDay

@dataclass(frozen=True)
class Birthday:
    date_of_birth: date

    @property
    def age(self) -> Optional[int]:
        """Return the current age."""
        return calculate_age(self.date_of_birth, today())

    @property
    def days_until_next_birthday(self) -> Optional[int]:
        """Return the number of days until the next birthday."""
        return calculate_days_until(self.date_of_birth, today())

    @property
    def is_today(self) -> Optional[bool]:
        """Return `True` if the birthday is today."""
        return MonthDay.of(self.date_of_birth).matches(today())

def today() -> date:
    return date.today()


text:
import React, { Component } from 'react';
import { Link } from 'react-router';

export default class Footer extends Component {
  render() {
    return (

List item 1

List item 2

List item 3

List unstyled 1

List unstyled 2

List unstyled 3

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

            © 2017 Rice & Noodle

    );
  }
}


text:
Client library for AutomationManagement

## Installation and Usage
```bash
npm install --save @datafire/azure_automation_jobschedule
```
```js
let azure_automation_jobschedule = require('@datafire/azure_automation_jobschedule').create({
  access_token: "",
  refresh_token: "",
  client_id: "",
  client_secret: "",
  redirect_uri: ""
});

.then(data => {
  console.log(data);
});
```

## Description

## Actions

### JobSchedule_ListByAutomationAccount
Retrieve a list of job schedules.

```js
azure_automation_jobschedule.JobSchedule_ListByAutomationAccount({
  "resourceGroupName": "",
  "automationAccountName": "",
  "subscriptionId": "",
  "api-version": ""
}, context)
```

#### Input
* input `object`
  * resourceGroupName **required** `string`: Name of an Azure Resource group.
  * automationAccountName **required** `string`: The name of the automation account.
  * $filter `string`: The filter to apply on the operation.
  * subscriptionId **required** `string`: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
  * api-version **required** `string`: Client Api Version.

#### Output
* output [JobScheduleListResult](#jobschedulelistresult)

### JobSchedule_Delete
Delete the job schedule identified by job schedule name.

```js
azure_automation_jobschedule.JobSchedule_Delete({
  "resourceGroupName": "",
  "automationAccountName": "",
  "jobScheduleId": "",
  "subscriptionId": "",
  "api-version": ""
}, context)
```

#### Input
* input `object`
  * resourceGroupName **required** `string`: Name of an Azure Resource group.
  * automationAccountName **required** `string`: The name of the automation account.
  * jobScheduleId **required** `string`: The job schedule name.
  * subscriptionId **required** `string`: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
  * api-version **required** `string`: Client Api Version.

#### Output
*Output schema unknown*

### JobSchedule_Get
Retrieve the job schedule identified by job schedule name.

```js
azure_automation_jobschedule.JobSchedule_Get({
  "resourceGroupName": "",
  "automationAccountName": "",
  "jobScheduleId": "",
  "subscriptionId": "",
  "api-version": ""
}, context)
```

#### Input
* input `object`
  * resourceGroupName **required** `string`: Name of an Azure Resource group.
  * automationAccountName **required** `string`: The name of the automation account.
  * jobScheduleId **required** `string`: The job schedule name.
  * subscriptionId **required** `string`: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
  * api-version **required** `string`: Client Api Version.

#### Output
* output [JobSchedule](#jobschedule)

### JobSchedule_Create
Create a job schedule.

```js
azure_automation_jobschedule.JobSchedule_Create({
  "resourceGroupName": "",
  "automationAccountName": "",
  "jobScheduleId": "",
  "parameters": null,
  "subscriptionId": "",
  "api-version": ""
}, context)
```

#### Input
* input `object`
  * resourceGroupName **required** `string`: Name of an Azure Resource group.
  * automationAccountName **required** `string`: The name of the automation account.
  * jobScheduleId **required** `string`: The job schedule name.
  * parameters **required** [JobScheduleCreateParameters](#jobschedulecreateparameters)
  * subscriptionId **required** `string`: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
  * api-version **required** `string`: Client Api Version.

#### Output
* output [JobSchedule](#jobschedule)

## Definitions

### JobSchedule
* JobSchedule `object`: Definition of the job schedule.
  * id `string`: Gets the id of the resource.
  * name `string`: Gets the name of the variable.
  * properties [JobScheduleProperties](#jobscheduleproperties)
  * type `string`: Resource type

### JobScheduleCreateParameters
* JobScheduleCreateParameters `object`: The parameters supplied to the create job schedule operation.
  * properties **required** [JobScheduleCreateProperties](#jobschedulecreateproperties)

### JobScheduleCreateProperties
* JobScheduleCreateProperties `object`: The parameters supplied to the create job schedule operation.
  * parameters `object`: Gets or sets a list of job properties.
  * runOn `string`: Gets or sets the hybrid worker group that the scheduled job should run on.
  * runbook **required** [RunbookAssociationProperty](#runbookassociationproperty)
  * schedule **required** [ScheduleAssociationProperty](#scheduleassociationproperty)

### JobScheduleListResult
* JobScheduleListResult `object`: The response model for the list job schedule operation.
  * nextLink `string`: Gets or sets the next link.
  * value `array`: Gets or sets a list of job schedules.
    * items [JobSchedule](#jobschedule)

### JobScheduleProperties
* JobScheduleProperties `object`: Definition of job schedule parameters.
  * jobScheduleId `string`: Gets or sets the id of job schedule.
  * parameters `object`: Gets or sets the parameters of the job schedule.
  * runOn `string`: Gets or sets the hybrid worker group that the scheduled job should run on.
  * runbook [RunbookAssociationProperty](#runbookassociationproperty)
  * schedule [ScheduleAssociationProperty](#scheduleassociationproperty)

### RunbookAssociationProperty
* RunbookAssociationProperty `object`: The runbook property associated with the entity.
  * name `string`: Gets or sets the name of the runbook.

### ScheduleAssociationProperty
* ScheduleAssociationProperty `object`: The schedule property associated with the entity.
  * name `string`: Gets or sets the name of the Schedule.


text:
// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2011 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

sc_require('models/record');

/** @class

  A RecordAttribute describes a single attribute on a record.  It is used to
  generate computed properties on records that can automatically convert data
  types and verify data.

  When defining an attribute on an SC.Record, you can configure it this way:

      title: SC.Record.attr(String, {
        defaultValue: 'Untitled',
        isRequired: YES|NO
      })

  In addition to having predefined transform types, there is also a way to
  set a computed relationship on an attribute. A typical example of this would
  be if you have record with a parentGuid attribute, but are not able to
  determine which record type to map to before looking at the guid (or any
  other attributes). To set up such a computed property, you can attach a
  function in the attribute definition of the SC.Record subclass:

      relatedToComputed: SC.Record.toOne(function() {
        return (this.readAttribute('relatedToComputed').indexOf("foo")==0) ? MyApp.Foo : MyApp.Bar;
      })

  Notice that we are not using .get() to avoid another transform which would
  trigger an infinite loop.

  You usually will not work with RecordAttribute objects directly, though you
  may extend the class in any way that you like to create a custom attribute.

  A number of default RecordAttribute types are defined on the SC.Record.

  @extends SC.Object
  @see SC.Record
  @see SC.ManyAttribute
  @see SC.SingleAttribute
  @since SproutCore 1.0
*/
SC.RecordAttribute = SC.Object.extend(
  /** @scope SC.RecordAttribute.prototype */ {
  /**
    Walk like a duck.

    @type Boolean
    @default YES
  */
  isRecordAttribute: YES,

  /**
    The default value.  If attribute is `null` or `undefined`, this default
    value will be substituted instead.  Note that `defaultValue`s are not
    converted, so the value should be in the output type expected by the
    attribute.

    If you use a `defaultValue` function, the arguments given to it are the
    record instance and the key.

    @type Object|function
    @default null
  */
  defaultValue: null,

  /**
    The attribute type.  Must be either an object class or a property path
    naming a class.  The built in handler allows all native types to pass
    through, converts records to ids and dates to UTF strings.

    If you use the `attr()` helper method to create a RecordAttribute instance,
    it will set this property to the first parameter you pass.

    @type Object|String
    @default String
  */
  type: String,

  /**
    The underlying attribute key name this attribute should manage.  If this
    property is left empty, then the key will be whatever property name this
    attribute assigned to on the record.  If you need to provide some kind
    of alternate mapping, this provides you a way to override it.

    @type String
    @default null
  */
  key: null,

  /**
    If `YES`, then the attribute is required and will fail validation unless
    the property is set to a non-null or undefined value.

    @type Boolean
    @default NO
  */
  isRequired: NO,

  /**
    If `NO` then attempts to edit the attribute will be ignored.

    @type Boolean
    @default YES
  */
  isEditable: YES,

  /**
    If set when using the Date format, expect the ISO8601 date format.
    This is the default.

    @type Boolean
    @default YES
  */
  useIsoDate: YES,

  /**
    Can only be used for toOne or toMany relationship attributes. If YES,
    this flag will ensure that any related objects will also be marked
    dirty when this record dirtied.

    Useful when you might have multiple related objects that you want to
    consider in an 'aggregated' state. For instance, by changing a child
    object (image) you might also want to automatically mark the parent
    (album) dirty as well.

    @type Boolean
    @default NO
  */
  aggregate: NO,

  /**
    Can only be used for toOne or toMany relationship attributes. If YES,
    this flag will lazily create the related record that was pushed in
    from the data source (via pushRetrieve) if the related record does
    not exist yet.

    Useful when you have a record used as a join table. Assumptions then
    can be made that the record exists at all times (even if it doesn't).
    For instance, if you have a contact that is a member of groups,
    a group will be created automatically when a contact pushes a new
    group.

    Note that you will have to take care of destroying the created record
    once all relationships are removed from it.

    @property {Boolean}
    @default NO
   */
  lazilyInstantiate: NO,

  // ..........................................................
  // HELPER PROPERTIES
  //

  /**
    Returns the type, resolved to a class.  If the type property is a regular
    class, returns the type unchanged.  Otherwise attempts to lookup the
    type as a property path.

    @property
    @type Object
    @default String
  */
  typeClass: function() {
    var ret = this.get('type');
    if (SC.typeOf(ret) === SC.T_STRING) ret = SC.requiredObjectForPropertyPath(ret);
    return ret ;
  }.property('type').cacheable(),

  /**
    Finds the transform handler. Attempts to find a transform that you
    registered using registerTransform for this attribute's type, otherwise
    defaults to using the default transform for String.

    @property
    @type Transform
  */
  transform: function() {
    var klass      = this.get('typeClass') || String,
        transforms = SC.RecordAttribute.transforms,
        ret ;

    // walk up class hierarchy looking for a transform handler
    while(klass && !(ret = transforms[SC.guidFor(klass)])) {
      // check if super has create property to detect SC.Object's
      if(klass.superclass.hasOwnProperty('create')) klass = klass.superclass ;
      // otherwise return the function transform handler
      else klass = SC.T_FUNCTION ;
    }

    return ret ;
  }.property('typeClass').cacheable(),

  // ..........................................................
  // LOW-LEVEL METHODS
  //

  /**
    Converts the passed value into the core attribute value.  This will apply
    any format transforms.  You can install standard transforms by adding to
    the `SC.RecordAttribute.transforms` hash.  See
    SC.RecordAttribute.registerTransform() for more.

    @param {SC.Record} record The record instance
    @param {String} key The key used to access this attribute on the record
    @param {Object} value The property value before being transformed
    @returns {Object} The transformed value
  */
  toType: function(record, key, value) {
    var transform = this.get('transform'),
        type      = this.get('typeClass'),
        children;

    if (transform && transform.to) {
      value = transform.to(value, this, type, record, key) ;

      // if the transform needs to do something when its children change, we need to set up an observer for it
      if(!SC.none(value) && (children = transform.observesChildren)) {
        var i, len = children.length,
        // store the record, transform, and key so the observer knows where it was called from
        context = {
          record: record,
          key: key
        };

        for(i = 0; i < len; i++) value.addObserver(children[i], this, this._SCRA_childObserver, context);
      }
    }

    return value ;
  },

  /**
    @private

    Shared observer used by any attribute whose transform creates a seperate
    object that needs to write back to the datahash when it changes. For
    example, when enumerable content changes on a `SC.Set` attribute, it
    writes back automatically instead of forcing you to call `.set` manually.

    This functionality can be used by setting an array named
    observesChildren on your transform containing the names of keys to
    observe. When one of them triggers it will call childDidChange on your
    transform with the same arguments as to and from.

    @param {Object} obj The transformed value that is being observed
    @param {String} key The key used to access this attribute on the record
    @param {Object} prev Previous value (not used)
    @param {Object} context Hash of extra context information
  */
  _SCRA_childObserver: function(obj, key, prev, context) {
    // write the new value back to the record
    this.call(context.record, context.key, obj);

    // mark the attribute as dirty
    context.record.notifyPropertyChange(context.key);
  },

  /**
    Converts the passed value from the core attribute value.  This will apply
    any format transforms.  You can install standard transforms by adding to
    the `SC.RecordAttribute.transforms` hash.  See
    `SC.RecordAttribute.registerTransform()` for more.

    @param {SC.Record} record The record instance
    @param {String} key The key used to access this attribute on the record
    @param {Object} value The transformed value
    @returns {Object} The value converted back to attribute format
  */
  fromType: function(record, key, value) {
    var transform = this.get('transform'),
        type      = this.get('typeClass');

    if (transform && transform.from) {
      value = transform.from(value, this, type, record, key);
    }
    return value;
  },

  /**
    The core handler. Called when `get()` is called on the
    parent record, since `SC.RecordAttribute` uses `isProperty` to masquerade
    as a computed property. Get expects a property be a function, thus we
    need to implement call.

    @param {SC.Record} record The record instance
    @param {String} key The key used to access this attribute on the record
    @param {Object} value The property value if called as a setter
    @returns {Object} property value
  */
  call: function(record, key, value) {
    var attrKey = this.get('key') || key, nvalue;

    if ((value !== undefined) && this.get('isEditable')) {
      // careful: don't overwrite value here.  we want the return value to
      // cache.
      nvalue = this.fromType(record, key, value) ; // convert to attribute.
      record.writeAttribute(attrKey, nvalue);
    }

    value = record.readAttribute(attrKey);
    if (SC.none(value) && (value = this.get('defaultValue'))) {
       if (typeof value === SC.T_FUNCTION) {
        value = value(record, key, this);
      }
    }

    value = this.toType(record, key, value);

    return value ;
  },

  /**
    Apply needs to implemented for sc_super to work.

    @see SC.RecordAttribute#call
  */
  apply: function(target, args) {
    return this.call.apply(target, args);
  },

  // ..........................................................
  // INTERNAL SUPPORT
  //

  /** @private - Make this look like a property so that `get()` will call it. */
  isProperty: YES,

  /** @private - Make this look cacheable */
  isCacheable: YES,

  /** @private - needed for KVO `property()` support */
  dependentKeys: [],

  /** @private */
  init: function() {
    sc_super();
    // setup some internal properties needed for KVO - faking 'cacheable'
    this.cacheKey = "__cache__recattr__" + SC.guidFor(this) ;
    this.lastSetValueKey = "__lastValue__recattr__" + SC.guidFor(this) ;
  }
}) ;

// ..........................................................
// CLASS METHODS
//

SC.RecordAttribute.mixin(
  /** @scope SC.RecordAttribute.prototype */{
  /**
    The default method used to create a record attribute instance.  Unlike
    `create()`, takes an `attributeType` as the first parameter which will be
    set on the attribute itself.  You can pass a string naming a class or a
    class itself.

    @static
    @param {Object|String} attributeType the assumed attribute type
    @param {Hash} opts optional additional config options
    @returns {SC.RecordAttribute} new instance
  */
  attr: function(attributeType, opts) {
    if (!opts) opts = {} ;
    if (!opts.type) opts.type = attributeType || String ;
    return this.create(opts);
  },

  /** @private
    Hash of registered transforms by class guid.
  */
  transforms: {},

  /**
    Call to register a transform handler for a specific type of object.  The
    object you pass can be of any type as long as it responds to the following
    methods

     - `to(value, attr, klass, record, key)` converts the passed value
       (which will be of the class expected by the attribute) into the
       underlying attribute value
     - `from(value, attr, klass, record, key)` converts the underlying
       attribute value into a value of the class

    You can also provide an array of keys to observer on the return value.
    When any of these change, your from method will be called to write the
    changed object back to the record. For example:

        {
          to: function(value, attr, type, record, key) {
            if(value) return value.toSet();
            else return SC.Set.create();
          },

          from: function(value, attr, type, record, key) {
            return value.toArray();
          },

          observesChildren: ['[]']
        }

    @static
    @param {Object} klass the type of object you convert
    @param {Object} transform the transform object
    @returns {SC.RecordAttribute} receiver
  */
  registerTransform: function(klass, transform) {
    SC.RecordAttribute.transforms[SC.guidFor(klass)] = transform;
  }
});

// ..........................................................
// STANDARD ATTRIBUTE TRANSFORMS
//

// Object, String, Number just pass through.

/** @private - generic converter for Boolean records */
SC.RecordAttribute.registerTransform(Boolean, {
  /** @private - convert an arbitrary object value to a boolean */
  to: function(obj) {
    return SC.none(obj) ? null : !!obj;
  }
});

/** @private - generic converter for Numbers */
SC.RecordAttribute.registerTransform(Number, {
  /** @private - convert an arbitrary object value to a Number */
  to: function(obj) {
    return SC.none(obj) ? null : Number(obj) ;
  }
});

/** @private - generic converter for Strings */
SC.RecordAttribute.registerTransform(String, {
  /** @private -
    convert an arbitrary object value to a String
    allow null through as that will be checked separately
  */
  to: function(obj) {
    if (!(typeof obj === SC.T_STRING) && !SC.none(obj) && obj.toString) {
      obj = obj.toString();
    }
    return obj;
  }
});

/** @private - generic converter for Array */
SC.RecordAttribute.registerTransform(Array, {
  /** @private - check if obj is an array
  */
  to: function(obj) {
    if (!SC.isArray(obj) && !SC.none(obj)) {
      obj = [];
    }
    return obj;
  },

  observesChildren: ['[]']
});

/** @private - generic converter for Object */
SC.RecordAttribute.registerTransform(Object, {
  /** @private - check if obj is an object */
  to: function(obj) {
    if (!(typeof obj === 'object') && !SC.none(obj)) {
      obj = {};
    }
    return obj;
  }
});

/** @private - generic converter for SC.Record-type records */
SC.RecordAttribute.registerTransform(SC.Record, {

  /** @private - convert a record id to a record instance */
  to: function(id, attr, recordType, parentRecord) {
    var store = parentRecord.get('store');
    if (SC.none(id) || (id==="")) return null;
    else return store.find(recordType, id);
  },

  /** @private - convert a record instance to a record id */
  from: function(record) { return record ? record.get('id') : null; }
});

/** @private - generic converter for transforming computed record attributes */
SC.RecordAttribute.registerTransform(SC.T_FUNCTION, {

  /** @private - convert a record id to a record instance */
  to: function(id, attr, recordType, parentRecord) {
    recordType = recordType.apply(parentRecord);
    var store = parentRecord.get('store');
    return store.find(recordType, id);
  },

  /** @private - convert a record instance to a record id */
  from: function(record) { return record.get('id'); }
});

/** @private - generic converter for Date records */
SC.RecordAttribute.registerTransform(Date, {

  /** @private - convert a string to a Date */
  to: function(str, attr) {

    // If a null or undefined value is passed, don't
    // do any normalization.
    if (SC.none(str)) { return str; }

    var ret ;
    str = str.toString() || '';

    if (attr.get('useIsoDate')) {
      var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
             "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" +
             "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?",
          d      = str.match(new RegExp(regexp)),
          offset = 0,
          date   = new Date(d[1], 0, 1),
          time ;

      if (d[3]) { date.setMonth(d[3] - 1); }
      if (d[5]) { date.setDate(d[5]); }
      if (d[7]) { date.setHours(d[7]); }
      if (d[8]) { date.setMinutes(d[8]); }
      if (d[10]) { date.setSeconds(d[10]); }
      if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
      if (d[14]) {
         offset = (Number(d[16]) * 60) + Number(d[17]);
         offset *= ((d[15] === '-') ? 1 : -1);
      }

      offset -= date.getTimezoneOffset();
      time = (Number(date) + (offset * 60 * 1000));

      ret = new Date();
      ret.setTime(Number(time));
    } else ret = new Date(Date.parse(str));
    return ret ;
  },

  _dates: {},

  /** @private - pad with leading zeroes */
  _zeropad: function(num) {
    return ((num<0) ? '-' : '') + ((num<10) ? '0' : '') + Math.abs(num);
  },

  /** @private - convert a date to a string */
  from: function(date) {

    if (SC.none(date)) { return null; }

    var ret = this._dates[date.getTime()];
    if (ret) return ret ;

    // figure timezone
    var zp = this._zeropad,
        tz = 0-date.getTimezoneOffset()/60;

    tz = (tz === 0) ? 'Z' : '%@:00'.fmt(zp(tz));

    this._dates[date.getTime()] = ret = "%@-%@-%@T%@:%@:%@%@".fmt(
      zp(date.getFullYear()),
      zp(date.getMonth()+1),
      zp(date.getDate()),
      zp(date.getHours()),
      zp(date.getMinutes()),
      zp(date.getSeconds()),
      tz) ;

    return ret ;
  }
});

if (SC.DateTime && !SC.RecordAttribute.transforms[SC.guidFor(SC.DateTime)]) {
  /**
    Registers a transform to allow `SC.DateTime` to be used as a record
    attribute, ie `SC.Record.attr(SC.DateTime);`

    Because `SC.RecordAttribute` is in the datastore framework and
    `SC.DateTime` in the foundation framework, and we don't know which
    framework is being loaded first, this chunck of code is duplicated in
    both frameworks.

    IF YOU EDIT THIS CODE MAKE SURE YOU COPY YOUR CHANGES to
    `record_attribute.js.`
  */

  SC.RecordAttribute.registerTransform(SC.DateTime, {

    /** @private
      Convert a String to a DateTime
    */
    to: function(str, attr) {
      if(attr.get('useUnixTime')) {
        if(SC.typeOf(str) === SC.T_STRING) { str = parseInt(str); }
        if(isNaN(str) || SC.typeOf(str) !== SC.T_NUMBER) { str = 0; }
        return SC.DateTime.create({ milliseconds: str*1000, timezone: 0 });
      }
      if (SC.none(str) || SC.instanceOf(str, SC.DateTime)) return str;
      if (SC.none(str) || SC.instanceOf(str, Date)) return SC.DateTime.create(str.getTime());
      var format = attr.get('format');
      return SC.DateTime.parse(str, format ? format : SC.DateTime.recordFormat);
    },

    /** @private
      Convert a DateTime to a String
    */
    from: function(dt, attr) {
      if (SC.none(dt)) return dt;
      if (attr.get('useUnixTime')) {
        return dt.get('milliseconds')/1000;
      }
      var format = attr.get('format');
      return dt.toFormattedString(format ? format : SC.DateTime.recordFormat);
    }
  });

}

/**
  Parses a coreset represented as an array.
 */
SC.RecordAttribute.registerTransform(SC.Set, {
  to: function(value, attr, type, record, key) {
    return SC.Set.create(value);
  },

  from: function(value, attr, type, record, key) {
    return value.toArray();
  },

  observesChildren: ['[]']
});


text:
using System;
using System.Collections.Generic;
namespace Lex
{
	public class Spec
	{
		public const int NUM_PSEUDO = 2;
		public const int NONE = 0;
		public const int START = 1;
		public const int END = 2;
		private readonly Dictionary<string, int> states = new Dictionary<string, int>();
		public string InitialState = "YYINITIAL";
		public Dictionary<string, string> macros = new Dictionary<string, string>();
		public Nfa nfa_start;
		public List<Nfa> nfa_states = new List<Nfa>();
		public List<Nfa>[] state_rules;
		public int[] state_dtrans;
		public List<Dfa> dfa_states = new List<Dfa>();
		public Dictionary<BitSet, Dfa> dfa_sets = new Dictionary<BitSet, Dfa>();
		public List<Accept> accept_list;
		public int[] anchor_array;
		public List<DTrans> dtrans_list = new List<DTrans>();
		public int dtrans_ncols = 128;
		public int[] row_map;
		public int[] col_map;
		public char BOL;
		public char EOF;
		public char[] ccls_map;
		public Tokens current_token = Tokens.EOS;
		public char current_token_value;
		public string class_name;
		public bool in_quote;
		public bool in_ccl;
		public bool verbose;
		public bool integer_type;
		public bool yyeof;
		public bool CountChars;
		public bool CountLines;
		public bool CountColumns;
		public bool cup_compatible;
		public string ClassAttributes = "public";
		public bool IgnoreCase;
		public int Version = 2;
		public List<string> InitCode = new List<string>();
		public List<string> CtorCode = new List<string>();
		public List<string> ClassCode = new List<string>();
		public List<string> EofCode = new List<string>();
		public string EofTokenName;
		public string ErrorTokenName;
		public string LexerName = "Yylex";
		public string ImplementsName;
		public string FunctionName = "yylex";
		public string TokenTypeName = "Yytoken";
		public string Namespace = "YyNameSpace";
		public string SemanticValueType;
		public string CharMapMethod;
		public int VariantCount = 1;
		private int unmarked_dfa;
		public Dictionary<string, int> States
		{
			get
			{
				return this.states;
			}
		}
		public void InitUnmarkedDFA()
		{
			this.unmarked_dfa = 0;
		}
		public void AddInitialState()
		{
			if (this.states.Count == 0)
			{
				this.states.Add(this.InitialState, 0);
			}
		}
		public void AddState(string name)
		{
			if (this.states.Count == 0)
			{
				this.InitialState = name;
			}
			this.states.Add(name, this.states.Count);
		}
		public Dfa GetNextUnmarkedDFA()
		{
			while (this.unmarked_dfa < this.dfa_states.Count)
			{
				Dfa dfa = this.dfa_states[this.unmarked_dfa];
				if (!dfa.IsMarked())
				{
					return dfa;
				}
				this.unmarked_dfa++;
			}
			return null;
		}
	}
}


text:
using UnityEngine;
using System.Collections;

public class FallingBomb : MonoBehaviour
{
	public AudioClip dropSound;

	private bool groundOn = false;
	private float scaler;
	private Vector3 position;
	private float newAlpha;
	private bool soundOn = false;

	private GameController gameControl;

	// Use this for initialization
	void Start ()
	{
		GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("GameController");
		gameControl = gameControllerObject.GetComponent <GameController>();

		// let's sync our default object position in our buffer
		position = transform.position;

		position.y = 3000;
		position.x = Random.Range(-2600, 2600);
		position.z = 2500;

		scaler = 20.0f;
		newAlpha = 1.0f;
	}

	// Update is called once per frame
	void Update ()
	{
		// don't draw if at max explosion size...
		if (newAlpha > 0.1f) renderer.enabled = true;
		else renderer.enabled = false;

		if ((int)gameControl.gameTime > 20)
		{
			// scale size of object
			transform.localScale = new Vector3(scaler, scaler, scaler);

			if (groundOn)
			{
				position.z -= gameControl.gameSpeed;
				scaler+=2.0f;
				scaler = Mathf.Clamp(scaler, 20.0f, 200.0f);
				transform.position = new Vector3(position.x, 20.0f, position.z);
				newAlpha = Mathf.Lerp(1.0f, 0.0f, Mathf.InverseLerp (20.0f, 200.0f, scaler));

				if (soundOn)
				{
					audio.PlayOneShot(dropSound);
					soundOn = false;
				}
			}
			else
			{
				Physics.gravity = new Vector3(0.0f,-600.0f,0.0f);
				transform.position = new Vector3(position.x, transform.position.y, position.z);
			}

			if (transform.position.y < 20.0f)
			{
				groundOn = true;
				soundOn = true;
			}

			if (transform.position.z < -4000.0f)
			{
				groundOn = false;
				scaler = 20.0f;
				position.y = 3000;
				position.x = Random.Range(-2600, 2600);
				position.z = 2500;
				newAlpha = 1.0f;

				transform.position = position;
			}

			// color alpha change
			renderer.material.color = new Color(renderer.material.color.r, renderer.material.color.g, renderer.material.color.b, newAlpha);
		}
		else
		{
			transform.position = new Vector3(position.x, 3000.0f, position.z);
		}
	}

	void OnTriggerEnter(Collider collisions)
	{
		if (newAlpha > 0.1f)
		{
			if(collisions.gameObject.tag == "Player")
			{
				if (gameObject.name == "cloneBomb") Destroy(gameObject);
				gameControl.killScreen = true;
			}
		}
	}
}


text:
package types

//Credentials user credentials and client credentials
type Credentials struct {
	UserCredentials
	ClientCredentials
}

//UserCredentials the users credentials
type UserCredentials struct {
	UserName    string
	AccessToken string
}

//ClientCredentials The clients credetials  the users credentials
type ClientCredentials struct {
	ClientID     string
	ClientSecret string
}

//Mode The possible client running action
type Mode uint8

const (
	//PRODUCTION production mode says its not in debug mode
	PRODUCTION Mode = iota
	//DEBUG mode says that the client is in debug mode
	DEBUG
)

// Error is a struct for platform error
type Error struct {
	Code     int    `json:"code"`
	HTTPCode int    `json:"status"`
	Message  string `json:"message"`
}

//Action Has the set of actions possible
type Action uint8

const (
	//CREATE create resource request
	CREATE Action = 0X01
	//BULKREAD get request on a resource
	//READ is by default bulk
	BULKREAD Action = 0X02
	//READ flag on action
	READ Action = 0x04
	//UPDATE update request on a resource
	UPDATE Action = 0X08
	//DELETE delete request on a resource
	DELETE Action = 0X10
)

//String implements the fmt.Stringer interface
func (a Action) String() (action string) {
	switch a {
	case CREATE:
		action = "CREATE"
	case BULKREAD:
		action = "READ"
	case READ:
		action = "READ"
	case UPDATE:
		action = "UPDATE"
	case DELETE:
		action = "DELETE"
	default:
		action = "INVALIDMETHOD"
	}
	return
}


text:
@interface PATypeAheadView : NSView {

}

@end