text:
package org.dcm4chex.archive.ejb.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * @author Gunter Zeilinger
 *
 */
public abstract class BaseCmd {
    protected static final Logger log = Logger.getLogger(BaseCmd.class);
    protected DataSource ds;
    protected Connection con;
    protected Statement stmt;
    protected int prevLevel = 0;

    protected BaseCmd(String dsJndiName, int transactionIsolationLevel, String sql)
			throws SQLException {
        try {
            Context jndiCtx = new InitialContext();
            try {
                ds = (DataSource) jndiCtx.lookup(dsJndiName);
            } finally {
                try {
                    jndiCtx.close();
                } catch (NamingException ignore) {
                }
            }
        } catch (NamingException ne) {
            throw new RuntimeException(
                    "Failed to access Data Source: " + dsJndiName, ne);
        }
        try {
            con = ds.getConnection();
            prevLevel = con.getTransactionIsolation();
            if (transactionIsolationLevel > 0)
                con.setTransactionIsolation(transactionIsolationLevel);
			if (sql != null) {
		        log.debug("SQL: " + sql);
	            stmt = con.prepareStatement(sql);
			} else {
				stmt = con.createStatement();
			}
        } catch (SQLException e) {
            close();
            throw e;
        }
    }

    public void close() {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ignore) {}
            stmt = null;
        }
        if (con != null) {
            try {
                con.setTransactionIsolation(prevLevel);
            } catch (SQLException ignore) {}
            try {
                con.close();
            } catch (SQLException ignore) {}
            con = null;
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Kew Bull. 1952:373. 1952

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
//========================================================================
//Copyright 2007-2009 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//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 com.dyuproject.protostuff.parser;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import junit.framework.TestCase;

import com.dyuproject.protostuff.parser.Field.Modifier;

/**
 * Various tests for the proto parser.
 *
 * @author David Yu
 * @created Dec 18, 2009
 */
public class ProtoParserTest extends TestCase
{

    static URL getResource(String path) throws IOException
    {
        return Thread.currentThread().getContextClassLoader().getResource(path);
    }

    static File getFile(String path)
    {
        return new File(new File("src/test/resources"), path);
    }

    public void testSimple() throws Exception
    {
        File f = getFile("TestModel.proto");
        assertTrue(f.exists());

        Proto proto = new Proto(f);
        ProtoUtil.loadFrom(f, proto);
        assertEquals(proto.getPackageName(), "simple");
        assertEquals(proto.getJavaPackageName(), "com.example.simple");
        assertTrue(proto.getEnumGroups().size() == 0);
        assertTrue(proto.getMessages().size() == 3);

        Message foo = proto.getMessage("Foo");
        Message bar = proto.getMessage("Bar");
        Message baz = proto.getMessage("Baz");
        assertNotNull(foo);
        assertNotNull(bar);
        assertNotNull(baz);

        assertTrue(foo.getNestedEnumGroups().size() == 1);
        EnumGroup enumSample = foo.getNestedEnumGroup("EnumSample");
        assertNotNull(enumSample);
        assertTrue(enumSample.getValues().size() == 5);
        assertEquals("TYPE0", enumSample.getValue(0).getName());
        assertEquals("TYPE1", enumSample.getValue(1).getName());
        assertEquals("TYPE2", enumSample.getValue(2).getName());
        assertEquals("TYPE3", enumSample.getValue(3).getName());
        assertEquals("TYPE4", enumSample.getValue(4).getName());

        assertTrue(foo.getFields().size() == 9);
        Field.Int32 foo_some_int = (Field.Int32)foo.getField("some_int");
        Field.String foo_some_string = (Field.String)foo.getField("some_string");
        MessageField foo_bar = (MessageField)foo.getField("bar");
        EnumField foo_some_enum = (EnumField)foo.getField("some_enum");
        Field.Bytes foo_some_bytes = (Field.Bytes)foo.getField("some_bytes");
        Field.Bool foo_some_boolean = (Field.Bool)foo.getField("some_boolean");
        Field.Float foo_some_float = (Field.Float)foo.getField("some_float");
        Field.Double foo_some_double = (Field.Double)foo.getField("some_double");
        Field.Int64 foo_some_long = (Field.Int64)foo.getField("some_long");

        assertTrue(foo_some_int !=null && foo_some_int.modifier == Modifier.REPEATED);
        assertTrue(foo_some_string !=null && foo_some_string.modifier == Modifier.REPEATED);
        assertTrue(foo_bar !=null && foo_bar.modifier == Modifier.REPEATED);
        assertTrue(foo_some_enum !=null && foo_some_enum.modifier == Modifier.REPEATED);
        assertTrue(foo_some_bytes !=null && foo_some_bytes.modifier == Modifier.REPEATED);
        assertTrue(foo_some_boolean !=null && foo_some_boolean.modifier == Modifier.REPEATED);
        assertTrue(foo_some_float !=null && foo_some_float.modifier == Modifier.REPEATED);
        assertTrue(foo_some_double !=null && foo_some_double.modifier == Modifier.REPEATED);
        assertTrue(foo_some_long !=null && foo_some_long.modifier == Modifier.REPEATED);

        Field.Int32 bar_some_int = (Field.Int32)bar.getField("some_int");
        Field.String bar_some_string = (Field.String)bar.getField("some_string");
        MessageField bar_baz = (MessageField)bar.getField("baz");
        EnumField bar_some_enum = (EnumField)bar.getField("some_enum");
        Field.Bytes bar_some_bytes = (Field.Bytes)bar.getField("some_bytes");
        Field.Bool bar_some_boolean = (Field.Bool)bar.getField("some_boolean");
        Field.Float bar_some_float = (Field.Float)bar.getField("some_float");
        Field.Double bar_some_double = (Field.Double)bar.getField("some_double");
        Field.Int64 bar_some_long = (Field.Int64)bar.getField("some_long");

        assertTrue(bar_some_int !=null && bar_some_int.modifier == Modifier.OPTIONAL);
        assertTrue(bar_some_string !=null && bar_some_string.modifier == Modifier.OPTIONAL);
        assertTrue(bar_baz !=null && bar_baz.modifier == Modifier.OPTIONAL);
        assertTrue(bar_some_enum !=null && bar_some_enum.modifier == Modifier.OPTIONAL);
        assertTrue(bar_some_bytes !=null && bar_some_bytes.modifier == Modifier.OPTIONAL);
        assertTrue(bar_some_boolean !=null && bar_some_boolean.modifier == Modifier.OPTIONAL);
        assertTrue(bar_some_float !=null && bar_some_float.modifier == Modifier.OPTIONAL);
        assertTrue(bar_some_double !=null && bar_some_double.modifier == Modifier.OPTIONAL);
        assertTrue(bar_some_long !=null && bar_some_long.modifier == Modifier.OPTIONAL);

        Field.Int64 baz_id = (Field.Int64)baz.getField("id");
        Field.String baz_name = (Field.String)baz.getField("name");
        Field.Int64 baz_timestamp = (Field.Int64)baz.getField("timestamp");
        Field.Bytes baz_data = (Field.Bytes)baz.getField("data");

        assertTrue(baz_id !=null && baz_id.modifier == Modifier.REQUIRED);
        assertTrue(baz_name !=null && baz_name.modifier == Modifier.OPTIONAL);
        assertTrue(baz_timestamp !=null && baz_timestamp.modifier == Modifier.OPTIONAL);
        assertTrue(baz_data !=null && baz_data.modifier == Modifier.OPTIONAL);

        assertEquals(bar_some_int.defaultValue, Integer.valueOf(127));
        assertEquals(new String(bar_some_string.defaultValue.getBytes(TextFormat.ISO_8859_1), "UTF-8"), "\u1234");
        assertEquals(bar_some_float.defaultValue, Float.valueOf(127.0f));
        assertEquals(bar_some_double.defaultValue, Double.valueOf(45.123));
        byte[] data = baz_data.getDefaultValue();
        assertTrue(data!=null && data.length == 2);
        assertTrue((data[0] & 0xFF) == 0xFA);
        assertTrue((data[1] & 0xFF)== 0xCE);
    }

    public void testImport() throws Exception
    {
        File f = getFile("unittest.proto");
        assertTrue(f.exists());

        Proto proto = new Proto(f);
        ProtoUtil.loadFrom(f, proto);

        Proto iProto = proto.getImportedProto(getFile("google/protobuf/unittest_import.proto"));
        assertNotNull(iProto);
        assertEquals("protobuf_unittest_import", iProto.getPackageName());
        assertEquals("com.google.protobuf.test", iProto.getJavaPackageName());
        assertTrue(iProto.getMessages().size() == 1);
        assertTrue(iProto.getEnumGroups().size() == 1);

        EnumGroup importEnum = iProto.getEnumGroup("ImportEnum");
        assertNotNull(importEnum);
        assertTrue(importEnum.values.size() == 3);
        assertTrue(importEnum.getValue("IMPORT_FOO").number == 7);
        assertTrue(importEnum.getValue("IMPORT_BAR").number == 8);
        assertTrue(importEnum.getValue("IMPORT_BAZ").number == 9);

        Message importMessage = iProto.getMessage("ImportMessage");
        assertNotNull(importMessage);

        assertTrue(importMessage.getFields().size() == 1);
        Field.Int32 import_message_d = (Field.Int32)importMessage.getField("d");
        assertTrue(import_message_d != null);
        assertTrue(import_message_d.modifier == Modifier.OPTIONAL);
        assertTrue(import_message_d.number == 1);
        assertTrue(import_message_d.defaultValue == null);

        // unittest.proto

        assertEquals("protobuf_unittest", proto.getPackageName());
        assertEquals(proto.getJavaPackageName(), proto.getPackageName());

        assertTrue(proto.getEnumGroups().size() == 3);

        EnumGroup foreignEnum = proto.getEnumGroup("ForeignEnum");
        assertNotNull(foreignEnum);
        assertTrue(foreignEnum.getValues().size() == 3);

        EnumGroup testEnumWithDupValue = proto.getEnumGroup("TestEnumWithDupValue");
        assertNotNull(testEnumWithDupValue);
        assertTrue(testEnumWithDupValue.getValues().size() == 5);
        assertTrue(testEnumWithDupValue.getSortedValues().get(0).name.equals("FOO1"));
        assertTrue(testEnumWithDupValue.getSortedValues().get(0).number == 1);
        assertTrue(testEnumWithDupValue.getSortedValues().get(1).name.equals("FOO2"));
        assertTrue(testEnumWithDupValue.getSortedValues().get(1).number == 1);
        assertTrue(testEnumWithDupValue.getSortedValues().get(2).name.equals("BAR1"));
        assertTrue(testEnumWithDupValue.getSortedValues().get(2).number == 2);
        assertTrue(testEnumWithDupValue.getSortedValues().get(3).name.equals("BAR2"));
        assertTrue(testEnumWithDupValue.getSortedValues().get(3).number == 2);
        assertTrue(testEnumWithDupValue.getSortedValues().get(4).name.equals("BAZ"));
        assertTrue(testEnumWithDupValue.getSortedValues().get(4).number == 3);

        EnumGroup testSparseEnum = proto.getEnumGroup("TestSparseEnum");
        assertNotNull(testSparseEnum);
        assertTrue(testSparseEnum.getValues().size() == 7);
        assertTrue(testSparseEnum.getSortedValues().get(0).name.equals("SPARSE_E"));
        assertTrue(testSparseEnum.getSortedValues().get(0).number == -53452);
        assertTrue(testSparseEnum.getSortedValues().get(1).name.equals("SPARSE_D"));
        assertTrue(testSparseEnum.getSortedValues().get(1).number == -15);
        assertTrue(testSparseEnum.getSortedValues().get(2).name.equals("SPARSE_F"));
        assertTrue(testSparseEnum.getSortedValues().get(2).number == 0);
        assertTrue(testSparseEnum.getSortedValues().get(3).name.equals("SPARSE_G"));
        assertTrue(testSparseEnum.getSortedValues().get(3).number == 2);
        assertTrue(testSparseEnum.getSortedValues().get(4).name.equals("SPARSE_A"));
        assertTrue(testSparseEnum.getSortedValues().get(4).number == 123);
        assertTrue(testSparseEnum.getSortedValues().get(5).name.equals("SPARSE_B"));
        assertTrue(testSparseEnum.getSortedValues().get(5).number == 62374);
        assertTrue(testSparseEnum.getSortedValues().get(6).name.equals("SPARSE_C"));
        assertTrue(testSparseEnum.getSortedValues().get(6).number == 12589234);

        Message testAllTypes = proto.getMessage("TestAllTypes");
        assertNotNull(testAllTypes);
        assertTrue(testAllTypes.getNestedMessages().size() == 1);
        assertTrue(testAllTypes.getNestedEnumGroups().size() == 1);

        Field<?> defaultStringPiece = testAllTypes.getField("default_string_piece");
        Field<?> defaultCord = testAllTypes.getField("default_cord");

        assertNotNull(defaultStringPiece);
        assertEquals("STRING_PIECE", defaultStringPiece.getOption("ctype"));
        assertEquals("abc", defaultStringPiece.getOption("default"));
        assertEquals("abc", defaultStringPiece.defaultValue);

        assertNotNull(defaultCord);
        assertEquals("CORD", defaultCord.getOption("ctype"));
        assertEquals("123", defaultCord.getOption("default"));
        assertEquals("123", defaultCord.defaultValue);

        Message nestedMessage = testAllTypes.getNestedMessage("NestedMessage");
        assertNotNull(nestedMessage);
        EnumGroup nestedEnum = testAllTypes.getNestedEnumGroup("NestedEnum");
        assertNotNull(nestedEnum);

        Message foreignMessage = proto.getMessage("ForeignMessage");
        assertNotNull(foreignMessage);

        EnumField optional_nested_enum = testAllTypes.getField("optional_nested_enum",
                EnumField.class);
        assertNotNull(optional_nested_enum);
        assertTrue(nestedEnum == optional_nested_enum.getEnumGroup());

        EnumField optional_foreign_enum = testAllTypes.getField("optional_foreign_enum",
                EnumField.class);
        assertNotNull(optional_foreign_enum);
        assertTrue(foreignEnum == optional_foreign_enum.getEnumGroup());

        EnumField optional_import_enum = testAllTypes.getField("optional_import_enum",
                EnumField.class);
        assertNotNull(optional_import_enum);
        assertTrue(importEnum == optional_import_enum.getEnumGroup());

        MessageField optional_nested_message = testAllTypes.getField("optional_nested_message",
                MessageField.class);
        assertNotNull(optional_nested_message);
        assertTrue(nestedMessage == optional_nested_message.getMessage());

        MessageField optional_foreign_message = testAllTypes.getField("optional_foreign_message",
                MessageField.class);
        assertNotNull(optional_foreign_message);
        assertTrue(foreignMessage == optional_foreign_message.getMessage());

        MessageField optional_import_message = testAllTypes.getField("optional_import_message",
                MessageField.class);
        assertNotNull(optional_import_message);
        assertTrue(importMessage == optional_import_message.getMessage());

        Message testRequiredForeign = proto.getMessage("TestRequiredForeign");
        assertNotNull(testRequiredForeign);
        assertTrue(testRequiredForeign.getFields().size() == 3);

        MessageField test_required_foreign_optional_message = testRequiredForeign.getField("optional_message",
                MessageField.class);
        assertNotNull(test_required_foreign_optional_message);
        assertTrue(test_required_foreign_optional_message.modifier == Modifier.OPTIONAL);

        MessageField test_required_foreign_repeated_message = testRequiredForeign.getField("repeated_message",
                MessageField.class);
        assertNotNull(test_required_foreign_repeated_message);
        assertTrue(test_required_foreign_repeated_message.modifier == Modifier.REPEATED);

        Field.Int32 dummy = testRequiredForeign.getField("dummy", Field.Int32.class);
        assertNotNull(dummy);
        assertTrue(dummy.modifier == Modifier.OPTIONAL && dummy.number == 3);

        Message testForeignNested = proto.getMessage("TestForeignNested");
        assertNotNull(testForeignNested);
        MessageField foreign_nested = testForeignNested.getField("foreign_nested",
                MessageField.class);
        assertNotNull(foreign_nested);
        assertTrue(nestedMessage == foreign_nested.getMessage());

        Message testEmptyMessage = proto.getMessage("TestEmptyMessage");
        assertNotNull(testEmptyMessage);
        assertTrue(testEmptyMessage.getFields().size() == 0);
        assertTrue(testEmptyMessage.getNestedEnumGroups().size() == 0);
        assertTrue(testEmptyMessage.getNestedMessages().size() == 0);

        Message testReallyLargeTagNumber = proto.getMessage("TestReallyLargeTagNumber");
        assertNotNull(testReallyLargeTagNumber);

        Field.Int32 a = testReallyLargeTagNumber.getField("a", Field.Int32.class);
        assertNotNull(a);
        assertTrue(a.number == 1);
        Field.Int32 bb = testReallyLargeTagNumber.getField("bb", Field.Int32.class);
        assertNotNull(bb);
        assertTrue(bb.number == 268435455);

        Message testRecursiveMessage = proto.getMessage("TestRecursiveMessage");
        assertNotNull(testRecursiveMessage);

        MessageField testRecursiveMessage_a = testRecursiveMessage.getField("a",
                MessageField.class);
        assertTrue(testRecursiveMessage == testRecursiveMessage_a.getMessage());

        Message testMutualRecursionA = proto.getMessage("TestMutualRecursionA");
        assertNotNull(testMutualRecursionA);
        Message testMutualRecursionB = proto.getMessage("TestMutualRecursionB");
        assertNotNull(testMutualRecursionB);

        MessageField testMutualRecursionA_bb = testMutualRecursionA.getField("bb",
                MessageField.class);
        assertNotNull(testMutualRecursionA_bb);
        MessageField testMutualRecursionB_a = testMutualRecursionB.getField("a",
                MessageField.class);
        assertNotNull(testMutualRecursionB_a);

        assertTrue(testMutualRecursionA == testMutualRecursionB_a.getMessage());
        assertTrue(testMutualRecursionB == testMutualRecursionA_bb.getMessage());

        Message testNestedMessageHasBits = proto.getMessage("TestNestedMessageHasBits");
        assertNotNull(testNestedMessageHasBits);
        Message tnmhb_nestedMessage = testNestedMessageHasBits.getNestedMessage("NestedMessage");
        assertNotNull(tnmhb_nestedMessage);

        MessageField tnmhb_optional_nested_message = testNestedMessageHasBits.getField("optional_nested_message",
                MessageField.class);
        assertNotNull(tnmhb_optional_nested_message);
        assertTrue(tnmhb_nestedMessage == tnmhb_optional_nested_message.getMessage());

        MessageField nestedmessage_repeated_foreignmessage = tnmhb_nestedMessage.getField("nestedmessage_repeated_foreignmessage",
                MessageField.class);
        assertNotNull(nestedmessage_repeated_foreignmessage);
        assertTrue(foreignMessage == nestedmessage_repeated_foreignmessage.getMessage());

        Message testFieldOrderings = proto.getMessage("TestFieldOrderings");
        assertNotNull(testFieldOrderings);
        assertTrue(testFieldOrderings.getFields().size() == 3);
        assertEquals(testFieldOrderings.sortedFields.get(0).name, "my_int");
        assertEquals(testFieldOrderings.sortedFields.get(1).name, "my_string");
        assertEquals(testFieldOrderings.sortedFields.get(2).name, "my_float");

        Message testExtremeDefaultValues = proto.getMessage("TestExtremeDefaultValues");
        assertNotNull(testExtremeDefaultValues);

        Field.UInt32 large_uint32 = testExtremeDefaultValues.getField("large_uint32",
                Field.UInt32.class);
        assertNotNull(large_uint32);
        assertTrue((large_uint32.getDefaultValue().intValue() & 0xFFFFFFFF) == 0xFFFFFFFF);

        Field.UInt64 large_uint64 = testExtremeDefaultValues.getField("large_uint64",
                Field.UInt64.class);
        assertNotNull(large_uint64);
        assertTrue(-1 == large_uint64.getDefaultValue().longValue());

        Field.Int32 small_int32 = testExtremeDefaultValues.getField("small_int32",
                Field.Int32.class);
        assertNotNull(small_int32);
        assertTrue(small_int32.getDefaultValue().intValue() == -0x7FFFFFFF);

        Field.Int64 small_int64 = testExtremeDefaultValues.getField("small_int64",
                Field.Int64.class);
        assertNotNull(small_int64);
        assertTrue(-Long.MAX_VALUE == small_int64.getDefaultValue().longValue());

        Message testAllExtensions = proto.getMessage("TestAllExtensions");
        assertNotNull(proto.getExtensions());
        assertTrue(proto.getExtensions().size() > 0);
        Extension extension = proto.getExtensions().iterator().next();
        assertEquals(testAllExtensions, extension.extendedMessage);
        assertNotNull(extension.getFields());
        assertTrue(extension.getFields().size() > 0);

        Message testNestedExtension = proto.getMessage("TestNestedExtension");
        assertNotNull(testNestedExtension.getNestedExtensions());
        assertEquals(1, testNestedExtension.getNestedExtensions().size());
        extension = testNestedExtension.getNestedExtensions().iterator().next();
        assertTrue(extension.isNested());

        Message testMultipleExtensionRanges = proto.getMessage("TestMultipleExtensionRanges");
        assertNotNull(testMultipleExtensionRanges);
        assertTrue(3 == testMultipleExtensionRanges.extensionRanges.size());
        int[] first = testMultipleExtensionRanges.extensionRanges.get(0);
        int[] second = testMultipleExtensionRanges.extensionRanges.get(1);
        int[] third = testMultipleExtensionRanges.extensionRanges.get(2);

        assertTrue(first[0] == first[1] && first[0] == 42);
        assertTrue(second[0] == 4143 && second[1] == 4243);
        assertTrue(third[0] == 65536 && third[1] == 536870911);
    }

    public void testEnumWithTrailingSemicolon() throws Exception
    {
        File f = getFile("enum_with_semicolon.proto");
        assertTrue(f.exists());

        Proto proto = new Proto(f);
        ProtoUtil.loadFrom(f, proto);
        assertEquals(proto.getPackageName(), "rpc");
    }

    public void testDescriptorProto() throws Exception
    {
        File f = getFile("descriptor.proto");
        assertTrue(f.exists());

        Proto proto = new Proto(f);
        ProtoUtil.loadFrom(f, proto);
        assertEquals(proto.getPackageName(), "google.protobuf");
    }

    /*public static void main(String[] args) throws Exception
    {
        File f = getFile("unittest.proto");
        assertTrue(f.exists());

        Proto proto = new Proto(f);
        ProtoUtil.loadFrom(f, proto);
        System.err.println(Float.parseFloat("6.13e5"));
        byte[] b = "123".getBytes();
        for(int i=0; i<b.length; i++)
            System.err.println(b[i]);

    }*/

}


text:
package com.huawei.openview.devops.domain.admin;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import lombok.Data;

/**
 * Created by zhang on 10/24/16.
 */
@Data
@DatabaseTable(tableName = "app_blueprint")
public class AppBlueprint {
	public static final String APP_ID = "app_id";
	public static final String BLUEPRINT_TYPE_YAML = "YAML";

	@JsonIgnore
	@DatabaseField(generatedId = true)
	private Long id;

	@DatabaseField
	@JsonIgnore
	private Long app_id;

	@DatabaseField(canBeNull = false, defaultValue = BLUEPRINT_TYPE_YAML)
	private String original_type;

	@DatabaseField(canBeNull = false)
	private String original_content;

	@DatabaseField
	private String edited_content;

	@DatabaseField
	private String entry_point;

}


text:
common = require("./HostCommon");

// forward exports
exports = module.exports = common;
exports.atomicTool = exports.artifactsRoot + "Build/AtomicTool/AtomicTool";


text:
package org.apache.catalina.valves;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;

public class TestStuckThreadDetectionValve extends TomcatBaseTest {
    private StandardContext context;
    private Tomcat tomcat;

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        tomcat = getTomcatInstance();
        File docBase = new File(System.getProperty("java.io.tmpdir"));
        context = (StandardContext) tomcat.addContext("",
                docBase.getAbsolutePath());
    }

    @Test
    public void testDetection() throws Exception {
        // second, we test the actual effect of the flag on the startup
        StuckingServlet stuckingServlet = new StuckingServlet(8000L);
        Wrapper servlet = Tomcat.addServlet(context, "myservlet",
                stuckingServlet);
        servlet.addMapping("/myservlet");

        StuckThreadDetectionValve valve = new StuckThreadDetectionValve();
        valve.setThreshold(2);
        context.addValve(valve);
        context.setBackgroundProcessorDelay(1);
        tomcat.start();

        Assert.assertEquals(0, valve.getStuckThreadIds().length);

        final ByteChunk result = new ByteChunk();
        Thread asyncThread = new Thread() {
            @Override
            public void run() {
                try {
                    getUrl("http://localhost:" + getPort() + "/myservlet",
                            result, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        };
        asyncThread.start();
        try {
            Thread.sleep(500L);
            Assert.assertEquals(0, valve.getStuckThreadIds().length);

            Thread.sleep(5000L);
            Assert.assertEquals(1, valve.getStuckThreadIds().length);
        } finally {
            asyncThread.join(20000);
            // check that we did not reach the join timeout
            Assert.assertFalse(asyncThread.isAlive());
        }
        Assert.assertFalse(stuckingServlet.wasInterrupted);
        Assert.assertTrue(result.toString().startsWith("OK"));
    }

    @Test
    public void testInterruption() throws Exception {
        // second, we test the actual effect of the flag on the startup
        StuckingServlet stuckingServlet = new StuckingServlet(
                TimeUnit.SECONDS.toMillis(20L));
        Wrapper servlet = Tomcat.addServlet(context, "myservlet",
                stuckingServlet);
        servlet.addMapping("/myservlet");

        StuckThreadDetectionValve valve = new StuckThreadDetectionValve();
        valve.setThreshold(2);
        valve.setInterruptThreadThreshold(5);
        context.addValve(valve);
        context.setBackgroundProcessorDelay(1);
        tomcat.start();

        Assert.assertEquals(0, valve.getStuckThreadIds().length);

        final ByteChunk result = new ByteChunk();
        Thread asyncThread = new Thread() {
            @Override
            public void run() {
                try {
                    getUrl("http://localhost:" + getPort() + "/myservlet",
                            result, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        };
        asyncThread.start();
        try {
            Thread.sleep(4000L);
            Assert.assertEquals(1, valve.getStuckThreadIds().length);

        } finally {
            asyncThread.join(20000);
            // check that we did not reach the join timeout
            Assert.assertFalse(asyncThread.isAlive());
        }
        Assert.assertTrue(stuckingServlet.wasInterrupted);
        Assert.assertEquals(0, valve.getStuckThreadIds().length);
        Assert.assertTrue(result.toString().startsWith("OK"));
    }

    private class StuckingServlet extends HttpServlet {

        private static final long serialVersionUID = 1L;
        private final long delay;
        boolean wasInterrupted = false;

        StuckingServlet(long delay) {
            this.delay = delay;
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                wasInterrupted = true;
            }
            resp.setContentType("text/plain");
            resp.getWriter().println("OK");
        }

    }
}


text:
import * as Immutable from "immutable";
import { CellFormatter, ClickHandler, FormatOptions } from "./FormatOptions";

export interface NumFormatOptionsProps {
  type: string;
  commas: boolean;
  decimalPlaces: number | undefined;
  exponential: boolean;
}

const defaultNumFormatOptionsProps: NumFormatOptionsProps = {
  type: "NumFormatOptions",
  commas: true,
  decimalPlaces: 2,
  exponential: false,
};

export class NumFormatOptions
  extends Immutable.Record(defaultNumFormatOptionsProps)
  implements NumFormatOptionsProps, FormatOptions
{
  public readonly type!: string;
  public readonly commas!: boolean;
  public readonly decimalPlaces!: number | undefined;
  public readonly exponential!: boolean;

  getFormatter(): CellFormatter {
    const fmtOpts = {
      minimumFractionDigits: this.decimalPlaces,
      maximumFractionDigits: this.decimalPlaces,
      useGrouping: this.commas,
    };

    const ff = (val?: any): string | undefined | null => {
      if (val == null) {
        return null;
      }

      let ret;

      if (this.exponential) {
        if (this.decimalPlaces) {
          ret = val.toExponential(this.decimalPlaces);
        } else {
          ret = val.toExponential();
        }
      } else {
        ret = val.toLocaleString(undefined, fmtOpts);
      }

      return ret;
    };

    return ff;
  }

  getClassName(): string | null {
    return "data-cell-numeric";
  }

  getClickHandler(): ClickHandler | null {
    return null;
  }
}


text:
        <button type="button" class="close pull-right" data-dismiss="modal" aria-label="Close">×</button>

Sorry.  Your request failed.

If this problem persists, please submit a trouble ticket.


text:
/**
 *
 */
package com.withinet.opaas.controller.impl;

import java.io.File;
import java.io.IOException;

import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.withinet.opaas.controller.FileController;
import com.withinet.opaas.controller.common.FileControllerException;
import com.withinet.opaas.controller.system.FileLocationGenerator;
/**
 * @author Folarin
 *
 */
@Controller
public class FileControllerImpl implements FileController {

	@Autowired
	private FileLocationGenerator fileMan;

	/* (non-Javadoc)
	 * @see com.withinet.opaas.controller.FileController#getUsedSpace(java.lang.Long)
	 */
	@Override
	public String getUsedSpace(Long uid) throws FileControllerException {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.withinet.opaas.controller.FileController#flushUserDirectory(java.lang.Long)
	 */
	@Override
	public boolean flushUserDirectory(Long uid) throws FileControllerException{
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see com.withinet.opaas.controller.FileController#flushProjectDirectory(java.lang.Long)
	 */
	@Override
	public boolean flushProjectDirectory(Long pid) throws FileControllerException {
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see com.withinet.opaas.controller.FileController#uploadFile(java.lang.Long, org.apache.wicket.markup.html.form.upload.FileUpload, java.lang.String)
	 */
	@Override
	public File uploadTempFile(Long uid, FileUpload upload) throws FileControllerException{
		// If project creation succeeds, check for file upload
		File thisFile = new File((fileMan.getConcurrentTempDirectory (uid)).getAbsolutePath() + "/"
				+ upload.getClientFileName());
		try {
			if (!thisFile.createNewFile())
				throw new FileControllerException ("File upload failed");
			else {
				upload.writeTo(thisFile);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new FileControllerException ("File upload failed");
		}
		return thisFile;
	}

	@Override
	public File uploadToDestFile(Long uid, FileUpload upload, String dest) throws FileControllerException {
		// If project creation succeeds, check for file upload
		File thisFile = new File(dest + "/"
				+ upload.getClientFileName());
		try {
			if (!thisFile.createNewFile())
				throw new FileControllerException ("File upload failed");
			else {
				upload.writeTo(thisFile);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new FileControllerException ("File upload failed");
		}
		return thisFile;
	}

}


text:
/*
 * Generated by asn1c-0.9.23 (http://lionet.info/asn1c)
 * From ASN.1 module "CDR"
 * 	found in "../cdr.asn1"
 * 	`asn1c -fskeletons-copy -fnative-types`
 */

#include "RecordingEntity.h"

int
RecordingEntity_constraint(asn_TYPE_descriptor_t *td, const void *sptr,
			asn_app_constraint_failed_f *ctfailcb, void *app_key) {
	const AddressString_t *st = (const AddressString_t *)sptr;
	size_t size;

	if(!sptr) {
		_ASN_CTFAIL(app_key, td, sptr,
			"%s: value not given (%s:%d)",
			td->name, __FILE__, __LINE__);
		return -1;
	}

	size = st->size;

	if((size >= 1 && size <= 20)) {
		/* Constraint check succeeded */
		return 0;
	} else {
		_ASN_CTFAIL(app_key, td, sptr,
			"%s: constraint failed (%s:%d)",
			td->name, __FILE__, __LINE__);
		return -1;
	}
}

/*
 * This type is implemented using AddressString,
 * so here we adjust the DEF accordingly.
 */
static void
RecordingEntity_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) {
	td->free_struct    = asn_DEF_AddressString.free_struct;
	td->print_struct   = asn_DEF_AddressString.print_struct;
	td->ber_decoder    = asn_DEF_AddressString.ber_decoder;
	td->der_encoder    = asn_DEF_AddressString.der_encoder;
	td->xer_decoder    = asn_DEF_AddressString.xer_decoder;
	td->xer_encoder    = asn_DEF_AddressString.xer_encoder;
	td->uper_decoder   = asn_DEF_AddressString.uper_decoder;
	td->uper_encoder   = asn_DEF_AddressString.uper_encoder;
	if(!td->per_constraints)
		td->per_constraints = asn_DEF_AddressString.per_constraints;
	td->elements       = asn_DEF_AddressString.elements;
	td->elements_count = asn_DEF_AddressString.elements_count;
	td->specifics      = asn_DEF_AddressString.specifics;
}

void
RecordingEntity_free(asn_TYPE_descriptor_t *td,
		void *struct_ptr, int contents_only) {
	RecordingEntity_1_inherit_TYPE_descriptor(td);
	td->free_struct(td, struct_ptr, contents_only);
}

int
RecordingEntity_print(asn_TYPE_descriptor_t *td, const void *struct_ptr,
		int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
	RecordingEntity_1_inherit_TYPE_descriptor(td);
	return td->print_struct(td, struct_ptr, ilevel, cb, app_key);
}

asn_dec_rval_t
RecordingEntity_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
		void **structure, const void *bufptr, size_t size, int tag_mode) {
	RecordingEntity_1_inherit_TYPE_descriptor(td);
	return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode);
}

asn_enc_rval_t
RecordingEntity_encode_der(asn_TYPE_descriptor_t *td,
		void *structure, int tag_mode, ber_tlv_tag_t tag,
		asn_app_consume_bytes_f *cb, void *app_key) {
	RecordingEntity_1_inherit_TYPE_descriptor(td);
	return td->der_encoder(td, structure, tag_mode, tag, cb, app_key);
}

asn_dec_rval_t
RecordingEntity_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
		void **structure, const char *opt_mname, const void *bufptr, size_t size) {
	RecordingEntity_1_inherit_TYPE_descriptor(td);
	return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size);
}

asn_enc_rval_t
RecordingEntity_encode_xer(asn_TYPE_descriptor_t *td, void *structure,
		int ilevel, enum xer_encoder_flags_e flags,
		asn_app_consume_bytes_f *cb, void *app_key) {
	RecordingEntity_1_inherit_TYPE_descriptor(td);
	return td->xer_encoder(td, structure, ilevel, flags, cb, app_key);
}

static ber_tlv_tag_t asn_DEF_RecordingEntity_tags_1[] = {
	(ASN_TAG_CLASS_UNIVERSAL | (4 << 2))
};
asn_TYPE_descriptor_t asn_DEF_RecordingEntity = {
	"RecordingEntity",
	"RecordingEntity",
	RecordingEntity_free,
	RecordingEntity_print,
	RecordingEntity_constraint,
	RecordingEntity_decode_ber,
	RecordingEntity_encode_der,
	RecordingEntity_decode_xer,
	RecordingEntity_encode_xer,
	0, 0,	/* No PER support, use "-gen-PER" to enable */
	0,	/* Use generic outmost tag fetcher */
	asn_DEF_RecordingEntity_tags_1,
	sizeof(asn_DEF_RecordingEntity_tags_1)
		/sizeof(asn_DEF_RecordingEntity_tags_1[0]), /* 1 */
	asn_DEF_RecordingEntity_tags_1,	/* Same as above */
	sizeof(asn_DEF_RecordingEntity_tags_1)
		/sizeof(asn_DEF_RecordingEntity_tags_1[0]), /* 1 */
	0,	/* No PER visible constraints */
	0, 0,	/* No members */
	0	/* No specifics */
};


text: curl http://downloads.4ksamples.com/downloads/Elysium_trailer_1-4K-HDTN\(4ksamples.com\).mp4 > video.mp4


text:
from __future__ import (unicode_literals, absolute_import,
                        division, print_function)
import logging

from django.core.management.base import BaseCommand
from django.db import connections

logger = logging.getLogger(__name__)

class Command(BaseCommand):

    def handle(self, database="default", *args, **options):

        cursor = connections[database].cursor()

        # harmonize to MyISAM first
        cursor.execute(
            "ALTER TABLE snisi_core_snisiprojectparticipation "
            "DROP FOREIGN KEY entity_id_refs_slug_27d6217c;")
        cursor.execute(
            "ALTER TABLE snisi_core_snisiprojectparticipation "
            "DROP FOREIGN KEY project_id_refs_slug_96acf6bc;")
        cursor.execute(
            "ALTER TABLE snisi_core_snisiproject "
            "DROP FOREIGN KEY operational_contact_id_refs_username_d1f73aeb;")
        cursor.execute(
            "ALTER TABLE snisi_core_snisiproject "
            "DROP FOREIGN KEY technical_contact_id_refs_username_d1f73aeb;")
        cursor.execute(
            "ALTER TABLE snisi_core_snisiproject ENGINE=MyISAM;")
        cursor.execute(
            "ALTER TABLE snisi_core_snisiprojectparticipation ENGINE=MyISAM;")

        # now convert all to InnoDB
        cursor.execute("SHOW TABLE STATUS;")

        for row in cursor.fetchall():
            if row[1] != "InnoDB":
                logger.info("Converting {}".format(row[0]))
                result = cursor.execute("ALTER TABLE {} ENGINE=INNODB"
                                        .format(row[0]))
                logger.info(result)


text:
package com.zentral.sembilar.resp.command;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import com.zentral.sembilar.resp.RespException;
import com.zentral.sembilar.resp.RespSerializer;

public interface ListCommand extends Command {

	public int rpush(String key, String value) throws IOException, RespException;
	public int rpush(String key, List<String> values) throws IOException, RespException;
	public <T extends Serializable> int rpush(String key, RespSerializer<T> serializer, T value) throws IOException, RespException;
	public <T extends Serializable> int rpush(String key, RespSerializer<T> serializer, List<T> values) throws IOException, RespException;
	public List<String> lrange(String key, int start, int stop) throws IOException, RespException;
	public List<String> lrange(String key) throws IOException, RespException;
	public int llen(String key) throws IOException, RespException;
}


text:
<?php

namespace Oro\Bundle\EntityExtendBundle\Migrations\Schema;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\EntityExtendBundle\Migrations\Schema\v1_0\RenameExtendTablesAndColumns;
use Oro\Bundle\EntityExtendBundle\Migrations\Schema\v1_1\OroEntityExtendBundle as OroEntityExtendBundle11;
use Oro\Bundle\MigrationBundle\Migration\Installation;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroEntityExtendBundleInstaller extends RenameExtendTablesAndColumns implements Installation
{
    /**
     * {@inheritdoc}
     */
    public function getMigrationVersion()
    {
        return 'v1_5';
    }

    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        // rename should not be performed during a fresh installation
        if ($this->container->hasParameter('installed') && $this->container->getParameter('installed')) {
            parent::up($schema, $queries);
        }

        OroEntityExtendBundle11::oroEnumValueTransTable($schema);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Interface org.apache.commons.math3.stat.descriptive.StatisticalMultivariateSummary (Commons Math 3.1.1 API)
</TITLE>

<META NAME="date" CONTENT="2013-01-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.apache.commons.math3.stat.descriptive.StatisticalMultivariateSummary

Packages that use StatisticalMultivariateSummary

org.apache.commons.math3.stat.descriptive
Generic univariate summary statistic objects.

Uses of StatisticalMultivariateSummary in org.apache.commons.math3.stat.descriptive

Classes in org.apache.commons.math3.stat.descriptive that implement StatisticalMultivariateSummary

 class
MultivariateSummaryStatistics

          Computes summary statistics for a stream of n-tuples added using the
 addValue method.

 class
SynchronizedMultivariateSummaryStatistics

          Implementation of
 MultivariateSummaryStatistics that
 is safe to use in a multithreaded environment.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2003-2013 The Apache Software Foundation. All Rights Reserved.


text:
package org.zhbit.excel.language;

/**
 * 语言国际化工具.
 * 用户可以自己实现国际化接口
 * @author Hyberbin
 */
public class LanguageUtils {

    private static ILanguage language = new SimpleLanguage();

    /**
     * @param key
     * @param args the command line arguments
     * @return
     */
    public static String translate(String key, Object... args) {
        return language.translate(key, args);
    }

    public static void setLanguage(ILanguage lang) {
        language = lang;
    }

}


text:
using namespace std;
#include "partition_string.h"

int CreateSpan::execute(const int & t, partStr_context & c ) const
{
    // Get input string
    string in;
    c.input.get(t, in);

    if (! in.empty()) {
        // construct span
        char ch = in[0];
        int len = 0;
        unsigned int i = 0;
        unsigned int j = 0;
        while (i < in.length()) {
            if (in[i] == ch) {
                i++;
                len++;
            } else {
                c.span.put(j, in.substr(j, len));
                c.spanTags.put(j);
                ch = in[i];
                len = 0;
                j = i;
            }
            // Put the last span
        }
        c.span.put(j, in.substr(j, len));
        c.spanTags.put(j);
    }

    return CnC::CNC_Success;
}

int ProcessSpan::execute(const int & t, partStr_context & c ) const
{
    // Get the span
    string span;
    c.span.get(t, span);
    // Test for odd length
    if ((span.length())%2 != 0) {  // odd length
        c.results.put(t, span);
    }
    return CnC::CNC_Success;
}

int main(int argc, char* argv[])
{
    // Create an instance of the context class which defines the graph
    partStr_context c;

    // Use an arbitrary value (e.g. 0) as the single tag value for
    // <singletonTag> and [input].
    const int singleton = 0;
    const string in_string = "aaaffqqqmmmmmmm";
    c.input.put(singleton, in_string);
    c.singletonTag.put(singleton);

    // Wait for all steps to finish
    c.wait();

    // Execution of the graph has finished.
    // Print the result instances.
    cout << "Input string: " << in_string << endl << endl
        << "The subparts with odd length:" << endl;

    CnC::item_collection<int, string>::const_iterator cii;
    for (cii = c.results.begin(); cii != c.results.end(); cii++) {
        string result = *(cii->second);
        cout << result << endl;
    }
}


text:
package com.linxiao.framework.common;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.linxiao.framework.net.ApiResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * a wrapper for gson, handled most problems that could cause fatal exception
 * <p>
 * using gson to cast some non standard json string, like defined int but got a double,
 * or you want get a force cast a jsonobject to string, using standard gson may cause exceptions
 * like 'expected something but was another...'.
 *
 * this wrapper is using to handle such situations like this,
 * you can use it to do some force cast and do not need to worry about the crash,
 * such like force cast to String, {@link JSONObject} and {@link JSONArray}
 *
 * if you want to add more deserialize rules based on this gson template,
 * you can use {@link #getBuilder()} method and add your custom deserializer
 * or just edit this class if your rules are acting on the whole project
 *
 * Gson包装工具,添加了处理常见崩溃情况的反序列化规则,也支持反序列化为{@link JSONObject}和{@link JSONArray}。
 * 如需添加自定义规则,请使用{@link #getBuilder()}方法获取Builder对象并自行添加,或者直接修改此class
 * </p>
 *
 * @author linxiao
 * @since 2018/1/11.
 */
public final class GsonParser {

    private static final String TAG = GsonParser.class.getSimpleName();

    private static Gson gson;

    /**
     * get GsonBuilder that contains default deserialize rules
     *
     * @return instance of GsonBuilder
     */
    public static GsonBuilder getBuilder() {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(int.class, new IntegerDeserializer())
        .registerTypeAdapter(Integer.class, new IntegerDeserializer())
        .registerTypeAdapter(String.class, new StringDeserializer())
        .registerTypeAdapter(JSONObject.class, new JSONObjectDeserializer())
        .registerTypeAdapter(JSONArray.class, new JSONArrayDeserializer())
        .registerTypeAdapter(ApiResponse.class, new ApiResponse.GsonDeserializer());
        return builder;
    }

    /**
     * get default gson instance
     * @return instance of Gson
     */
    public static Gson getParser() {
        if (gson == null) {
            gson = getBuilder().create();
        }
        return gson;
    }

    /**
     * cast json string to defined type
     * 将传入json string反序列化为声明类型对象
     *
     * @param json 需要反序列化的json string
     * @param clazz 需要反序列化的对象类型class
     * @param <T> 需要反序列化的对象类型声明
     * @return 反序列化类型的对象,如果失败则返回null
     */
    public static <T> T fromJSONObject(String json, Class<T> clazz) {
        try {
            return getParser().fromJson(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * cast {@link JSONObject} to defined type
     * 将传入{@link JSONObject}对象反序列化为声明类型对象
     *
     * @param json 需要反序列化的{@link JSONObject}对象
     * @param clazz 需要反序列化的对象类型class
     * @param <T> 需要反序列化的对象类型声明
     * @return 反序列化类型的对象,如果失败则返回null
     */
    public static <T> T fromJSONObject(JSONObject json, Class<T> clazz) {
        if (json == null) {
            return null;
        }
        try {
            return getParser().fromJson(json.toString(), clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * cast {@link JSONArray} string to the list of defined type
     * 将传入{@link JSONArray}字符串反序列化为声明类型对象
     *
     * @param jsonArrayStr 需要反序列化的{@link JSONObject}字符串
     * @param clazz 需要反序列化的对象类型class
     * @param <T> 需要反序列化的对象类型声明
     * @return 反序列化类型的对象,如果失败则返回null
     */
    public static <T> List<T> fromJSONArray(String jsonArrayStr, Class<T> clazz) {
        List<T> retList = new ArrayList<>();
        if (TextUtils.isEmpty(jsonArrayStr)) {
            return retList;
        }
        try {
            JsonArray arr = JsonParser.parseString(jsonArrayStr).getAsJsonArray();
            for (JsonElement jsonElement : arr) {
                retList.add(getParser().fromJson(jsonElement, clazz));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return retList;
        }
        return retList;
    }

    /**
     * cast {@link JSONArray} object to the list of defined type
     * 将传入{@link JSONArray}对象反序列化为声明类型对象
     *
     * @param jsonArray 需要反序列化的{@link JSONObject}对象
     * @param clazz 需要反序列化的对象类型class
     * @param <T> 需要反序列化的对象类型声明
     * @return 反序列化类型的对象,如果失败则返回null
     */
    public static <T> List<T>  fromJSONArray(JSONArray jsonArray, Class<T> clazz) {
        return fromJSONArray(String.valueOf(jsonArray), clazz);
    }

    /**
     * cast defined type to {@link JSONObject}
     * 将传入类型对象序列化为{@link JSONObject}对象
     *
     * @param data 需要序列化的对象
     * @param <T> 需要序列化的对象类型声明
     * @return {@link JSONObject}对象,如果序列化失败则返回null
     */
    public static <T> JSONObject toJSONObject(T data) {
        try {
            String jsonText = getParser().toJson(data);
            return new JSONObject(jsonText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * cast defined type to {@link JSONArray}
     * 将传入类型对象序列化为{@link JSONArray}对象
     *
     * @param data 需要序列化的对象列表
     * @param <T> 需要序列化的对象类型声明
     * @return {@link JSONArray}对象,如果序列化失败则返回null
     */
    public static <T> JSONArray toJSONArray(List<T> data) {

        try {
            String jsonText = getParser().toJson(data);
            return new JSONArray(jsonText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Rules for the situation that defined as integer but get float,
     * force cast to integer
     */
    static class IntegerDeserializer implements JsonDeserializer<Integer> {

        @Override
        public Integer deserialize(JsonElement json, Type typeOfT,
                                   JsonDeserializationContext context) throws JsonParseException {
            try {
                return json.getAsInt();
            }
            catch (Exception e) {
                try {
                    return (int) json.getAsDouble();
                } catch (Exception e1) {
                    throw new JsonParseException(e.getMessage());
                }
            }
        }
    }

    /**
     * if defined string, force cast to string whatever it got
     */
    static class StringDeserializer implements JsonDeserializer<String> {

        @Override
        public String deserialize(JsonElement json, Type typeOfT,
                                  JsonDeserializationContext context) throws JsonParseException {
            try {
                return json.getAsString();
            }
            catch (Exception e) {
                return json.toString();
            }
        }
    }

    /**
     * method to auto deserialize data as {@link JSONObject}
     */
    static class JSONObjectDeserializer implements JsonDeserializer<JSONObject> {

        @Override
        public JSONObject deserialize(JsonElement json, Type typeOfT,
                                      JsonDeserializationContext context) throws JsonParseException {
            try {
                return new JSONObject(json.toString());
            } catch (JSONException e) {
                Log.w(TAG, "err, string = " + json.toString());
            }
            return null;
        }
    }

    /**
     * method to auto deserialize data as {@link JSONArray}
     */
    static class JSONArrayDeserializer implements JsonDeserializer<JSONArray> {

        @Override
        public JSONArray deserialize(JsonElement json, Type typeOfT,
                                     JsonDeserializationContext context) throws JsonParseException {
            try {
                return new JSONArray(json.toString());
            } catch (JSONException e) {
                Log.w(TAG, "err, string = " + json.toString());
            }
            return null;
        }
    }

}


text:
"""
setup.py for rieapie

"""
__author__ = "Ali-Akber Saifee"
__email__ = "ali@indydevs.org"
__copyright__ = "Copyright 2013, Ali-Akber Saifee"

from setuptools import setup, find_packages
import os
import sys
import rieapie
this_dir = os.path.abspath(os.path.dirname(__file__))
REQUIREMENTS = filter(None, open(os.path.join(this_dir, 'requirements.txt')).read().splitlines())
extra = {}
if sys.version_info >= (3, ):
    extra['use_2to3'] = True

setup(
    name='rieapie',
    author=__author__,
    author_email=__email__,
    license=open('LICENSE.txt').read(),
    url="http://github.com/alisaifee/rieapie",
    zip_safe=False,
    version=rieapie.version,
    classifiers=[k for k in open('CLASSIFIERS').read().split('\n') if k],
    include_package_data=True,
    install_requires=REQUIREMENTS,
    description='Easy REST api wrapper',
    long_description=open('README.rst').read(),
    packages=find_packages(),
    **extra
)


text:
<?xml version="1.0"?>
<x:doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:x="http://xsdtesting" xsi:schemaLocation="http://xsdtesting attLb003.xsd">
	<x:elem ca1="123"/>
</x:doc>


text:
package com.github.dozermapper.core.metadata;

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

import com.github.dozermapper.core.classmap.ClassMap;
import com.github.dozermapper.core.classmap.MappingDirection;
import com.github.dozermapper.core.fieldmap.FieldMap;

/**
 * Internal use only.
 */
public final class DozerClassMappingMetadata implements ClassMappingMetadata {

    private final ClassMap classMap;

    public DozerClassMappingMetadata(ClassMap classMap) {
        this.classMap = classMap;
    }

    public String getSourceClassName() {
        return classMap.getSrcClassName();
    }

    public String getDestinationClassName() {
        return classMap.getDestClassName();
    }

    public Class<?> getSourceClass() {
        return classMap.getSrcClassToMap();
    }

    public Class<?> getDestinationClass() {
        return classMap.getDestClassToMap();
    }

    public boolean isStopOnErrors() {
        return classMap.isStopOnErrors();
    }

    public boolean isTrimStrings() {
        return classMap.isTrimStrings();
    }

    public boolean isWildcard() {
        return classMap.isWildcard();
    }

    public boolean isSourceMapNull() {
        return classMap.isSrcMapNull();
    }

    public boolean isDestinationMapNull() {
        return classMap.isDestMapNull();
    }

    public boolean isSourceMapEmptyString() {
        return classMap.isSrcMapEmptyString();
    }

    public boolean isDestinationMapEmptyString() {
        return classMap.isDestMapEmptyString();
    }

    public String getDateFormat() {
        return classMap.getDateFormat();
    }

    public MappingDirection getMappingDirection() {
        return classMap.getType();
    }

    public String getMapId() {
        return classMap.getMapId();
    }

    public List<FieldMappingMetadata> getFieldMappings() {
        List<FieldMappingMetadata> fieldMapCats = new ArrayList<>();
        for (FieldMap fieldMap : classMap.getFieldMaps()) {
            fieldMapCats.add(new DozerFieldMappingMetadata(fieldMap));
        }

        return fieldMapCats;
    }

    public FieldMappingMetadata getFieldMappingBySource(String sourceFieldName) {
        FieldMap fieldMap = classMap.getFieldMapUsingSrc(sourceFieldName);
        if (fieldMap == null) {
            throw new MetadataLookupException("Field mapping " + sourceFieldName + " not found for class " + classMap.getSrcClassName());
        }

        return new DozerFieldMappingMetadata(fieldMap);
    }

    public FieldMappingMetadata getFieldMappingByDestination(String destinationFieldName) {
        FieldMap fieldMap = classMap.getFieldMapUsingDest(destinationFieldName);
        if (fieldMap == null) {
            throw new MetadataLookupException("Field mapping " + destinationFieldName + " not found for class " + classMap.getDestClassName());
        }

        return new DozerFieldMappingMetadata(fieldMap);
    }

}


text:
#include "xenia/gpu/trace_reader.h"

#include "xenia/base/mapped_memory.h"
#include "xenia/gpu/packet_disassembler.h"
#include "xenia/gpu/trace_protocol.h"
#include "xenia/memory.h"

#include "third_party/zlib/zlib.h"

namespace xe {
namespace gpu {

bool TraceReader::Open(const std::wstring& path) {
  Close();

  mmap_ = MappedMemory::Open(path, MappedMemory::Mode::kRead);
  if (!mmap_) {
    return false;
  }

  trace_data_ = reinterpret_cast<const uint8_t*>(mmap_->data());
  trace_size_ = mmap_->size();

  ParseTrace();

  return true;
}

void TraceReader::Close() {
  mmap_.reset();
  trace_data_ = nullptr;
  trace_size_ = 0;
}

void TraceReader::ParseTrace() {
  auto trace_ptr = trace_data_;
  Frame current_frame;
  current_frame.start_ptr = trace_ptr;
  const PacketStartCommand* packet_start = nullptr;
  const uint8_t* packet_start_ptr = nullptr;
  const uint8_t* last_ptr = trace_ptr;
  bool pending_break = false;
  while (trace_ptr < trace_data_ + trace_size_) {
    ++current_frame.command_count;
    auto type = static_cast<TraceCommandType>(xe::load<uint32_t>(trace_ptr));
    switch (type) {
      case TraceCommandType::kPrimaryBufferStart: {
        auto cmd =
            reinterpret_cast<const PrimaryBufferStartCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd) + cmd->count * 4;
        break;
      }
      case TraceCommandType::kPrimaryBufferEnd: {
        auto cmd = reinterpret_cast<const PrimaryBufferEndCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd);
        break;
      }
      case TraceCommandType::kIndirectBufferStart: {
        auto cmd =
            reinterpret_cast<const IndirectBufferStartCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd) + cmd->count * 4;
        break;
      }
      case TraceCommandType::kIndirectBufferEnd: {
        auto cmd = reinterpret_cast<const IndirectBufferEndCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd);
        break;
      }
      case TraceCommandType::kPacketStart: {
        auto cmd = reinterpret_cast<const PacketStartCommand*>(trace_ptr);
        packet_start_ptr = trace_ptr;
        packet_start = cmd;
        trace_ptr += sizeof(*cmd) + cmd->count * 4;
        break;
      }
      case TraceCommandType::kPacketEnd: {
        auto cmd = reinterpret_cast<const PacketEndCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd);
        if (!packet_start_ptr) {
          continue;
        }
        auto packet_category = PacketDisassembler::GetPacketCategory(
            packet_start_ptr + sizeof(*packet_start));
        switch (packet_category) {
          case PacketCategory::kDraw: {
            Frame::Command command;
            command.type = Frame::Command::Type::kDraw;
            command.head_ptr = packet_start_ptr;
            command.start_ptr = last_ptr;
            command.end_ptr = trace_ptr;
            current_frame.commands.push_back(std::move(command));
            last_ptr = trace_ptr;
            break;
          }
          case PacketCategory::kSwap: {
            //
            break;
          }
        }
        if (pending_break) {
          current_frame.end_ptr = trace_ptr;
          frames_.push_back(std::move(current_frame));
          current_frame.start_ptr = trace_ptr;
          current_frame.end_ptr = nullptr;
          current_frame.command_count = 0;
          pending_break = false;
        }
        break;
      }
      case TraceCommandType::kMemoryRead: {
        auto cmd = reinterpret_cast<const MemoryReadCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd) + cmd->length;
        break;
      }
      case TraceCommandType::kMemoryWrite: {
        auto cmd = reinterpret_cast<const MemoryWriteCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd) + cmd->length;
        break;
      }
      case TraceCommandType::kEvent: {
        auto cmd = reinterpret_cast<const EventCommand*>(trace_ptr);
        trace_ptr += sizeof(*cmd);
        switch (cmd->event_type) {
          case EventType::kSwap: {
            pending_break = true;
            break;
          }
        }
        break;
      }
      default:
        // Broken trace file?
        assert_unhandled_case(type);
        break;
    }
  }
  if (pending_break || current_frame.command_count) {
    current_frame.end_ptr = trace_ptr;
    frames_.push_back(std::move(current_frame));
  }
}

bool TraceReader::DecompressMemory(const uint8_t* src, size_t src_size,
                                   uint8_t* dest, size_t dest_size) {
  uLongf dest_len = uint32_t(dest_size);
  int ret = uncompress(dest, &dest_len, src, uint32_t(src_size));
  assert_true(ret >= 0);
  return ret >= 0;
}

}  // namespace gpu
}  // namespace xe


text:
from io import BytesIO

import requests
from astropy.io.votable import parse
from glue.core.data_factories import astropy_tabular_data

def query_vizier(query_text):

    # Do the search using VizieR
    r = requests.post("http://vizier.u-strasbg.fr/viz-bin/votable",
                      {'-words': query_text.split(), '-meta.all': 1})

    # We now loop over the results and construct a list of dictionaries, where
    # each dictionary contains information about one set of tables.
    votablefile = parse(BytesIO(r.content))
    result = []
    for resource in votablefile.resources:
        catalog_set = {}
        catalog_set['description'] = resource.description
        catalog_set['tables'] = []
        for table in resource.tables:
            catalog = {}
            catalog['description'] = table.description
            catalog['nrows'] = str(table.nrows)
            catalog['name'] = str(table.name)
            catalog_set['tables'].append(catalog)
        result.append(catalog_set)

    return result

def fetch_vizier_catalog(catalog_name):
    r = requests.post("http://vizier.u-strasbg.fr/viz-bin/votable",
                      {'-source': catalog_name})
    table = astropy_tabular_data(BytesIO(r.content), format='votable')
    table.label = catalog_name
    return table


text:
require "#{File.dirname(__FILE__)}/../abstract_unit"

Bunny = Struct.new(:Bunny, :id)

class Author
  attr_reader :id
  def save; @id = 1 end
  def new_record?; @id.nil? end
  def name
    @id.nil? ? 'new author' : "author ##{@id}"
  end
end

class Article
  attr_reader :id
  attr_reader :author_id
  def save; @id = 1; @author_id = 1 end
  def new_record?; @id.nil? end
  def name
    @id.nil? ? 'new article' : "article ##{@id}"
  end
end

class Author::Nested < Author; end

module BaseTest
  def self.included(base)
    base.send :attr_accessor, :template_format
  end

  include ActionView::Helpers::JavaScriptHelper
  include ActionView::Helpers::PrototypeHelper
  include ActionView::Helpers::ScriptaculousHelper

  include ActionView::Helpers::UrlHelper
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::FormTagHelper
  include ActionView::Helpers::FormHelper
  include ActionView::Helpers::CaptureHelper
  include ActionView::Helpers::RecordIdentificationHelper
  include ActionController::PolymorphicRoutes

  def setup
    @template = nil
    @controller = Class.new do
      def url_for(options)
        if options.is_a?(String)
          options
        else
          url =  "http://www.example.com/"
          url << options[:action].to_s if options and options[:action]
          url << "?a=#{options[:a]}" if options && options[:a]
          url << "&b=#{options[:b]}" if options && options[:a] && options[:b]
          url
        end
      end
    end.new
  end

protected
  def create_generator
    block = Proc.new { |*args| yield *args if block_given? }
    JavaScriptGenerator.new self, &block
  end
end

class PrototypeHelperTest < Test::Unit::TestCase
  include BaseTest

  def setup
    @record = @author = Author.new
    @article = Article.new
    super
  end

  def test_link_to_remote
    assert_dom_equal %(Remote outauthor),
      link_to_remote("Remote outauthor", { :url => { :action => "whatnot"  }}, { :class => "fine"  })
    assert_dom_equal %(Remote outauthor),
      link_to_remote("Remote outauthor", :complete => "alert(request.reponseText)", :url => { :action => "whatnot"  })
    assert_dom_equal %(Remote outauthor),
      link_to_remote("Remote outauthor", :success => "alert(request.reponseText)", :url => { :action => "whatnot"  })
    assert_dom_equal %(Remote outauthor),
      link_to_remote("Remote outauthor", :failure => "alert(request.reponseText)", :url => { :action => "whatnot"  })
    assert_dom_equal %(Remote outauthor),
      link_to_remote("Remote outauthor", :failure => "alert(request.reponseText)", :url => { :action => "whatnot", :a => '10', :b => '20' })
  end

  def test_link_to_remote_html_options
    assert_dom_equal %(Remote outauthor),
      link_to_remote("Remote outauthor", { :url => { :action => "whatnot"  }, :html => { :class => "fine" } })
  end

  def test_periodically_call_remote
    assert_dom_equal %(),
      periodically_call_remote(:update => "schremser_bier", :url => { :action => "mehr_bier" })
  end

  def test_periodically_call_remote_with_frequency
    assert_dom_equal(
      "",
      periodically_call_remote(:frequency => 2)
    )
  end

  def test_form_remote_tag
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">),
      form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  })
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater({success:'glass_of_beer'}, 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">),
      form_remote_tag(:update => { :success => "glass_of_beer" }, :url => { :action => :fast  })
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater({failure:'glass_of_water'}, 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">),
      form_remote_tag(:update => { :failure => "glass_of_water" }, :url => { :action => :fast  })
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater({success:'glass_of_beer',failure:'glass_of_water'}, 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">),
      form_remote_tag(:update => { :success => 'glass_of_beer', :failure => "glass_of_water" }, :url => { :action => :fast  })
  end

  def test_form_remote_tag_with_method
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">
<input name='_method' type='hidden' value='put' />
),
      form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }, :html => { :method => :put })
  end

  def test_form_remote_tag_with_block
    _erbout = ''
    form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }) { _erbout.concat "Hello world!" }
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">Hello world!</form>), _erbout
  end

  def test_remote_form_for_with_record_identification_with_new_record
    _erbout = ''
    remote_form_for(@record, {:html => { :id => 'create-author' }}) {}

    expected = %(<form action='#{authors_path}' onsubmit="new Ajax.Request('#{authors_path}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='new_author' id='create-author' method='post'></form>)
    assert_dom_equal expected, _erbout
  end

  def test_remote_form_for_with_record_identification_without_html_options
    _erbout = ''
    remote_form_for(@record) {}

    expected = %(<form action='#{authors_path}' onsubmit="new Ajax.Request('#{authors_path}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='new_author' method='post' id='new_author'></form>)
    assert_dom_equal expected, _erbout
  end

  def test_remote_form_for_with_record_identification_with_existing_record
    @record.save
    _erbout = ''
    remote_form_for(@record) {}

    expected = %(<form action='#{author_path(@record)}' id='edit_author_1' method='post' onsubmit="new Ajax.Request('#{author_path(@record)}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='edit_author'>
<input name='_method' type='hidden' value='put' />
</form>)
    assert_dom_equal expected, _erbout
  end

  def test_remote_form_for_with_new_object_in_list
    _erbout = ''
    remote_form_for([@author, @article]) {}

    expected = %(<form action='#{author_articles_path(@author)}' onsubmit="new Ajax.Request('#{author_articles_path(@author)}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='new_article' method='post' id='new_article'></form>)
    assert_dom_equal expected, _erbout
  end

  def test_remote_form_for_with_existing_object_in_list
    @author.save
    @article.save
    _erbout = ''
    remote_form_for([@author, @article]) {}

    expected = %(<form action='#{author_article_path(@author, @article)}' id='edit_article_1' method='post' onsubmit="new Ajax.Request('#{author_article_path(@author, @article)}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='edit_article'>
<input name='_method' type='hidden' value='put' />
</form>)
    assert_dom_equal expected, _erbout
  end

  def test_on_callbacks
    callbacks = [:uninitialized, :loading, :loaded, :interactive, :complete, :success, :failure]
    callbacks.each do |callback|
      assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, on#{callback.to_s.capitalize}:function(request){monkeys();}, parameters:Form.serialize(this)}); return false;">),
        form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }, callback=>"monkeys();")
      assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater({success:'glass_of_beer'}, 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, on#{callback.to_s.capitalize}:function(request){monkeys();}, parameters:Form.serialize(this)}); return false;">),
        form_remote_tag(:update => { :success => "glass_of_beer" }, :url => { :action => :fast  }, callback=>"monkeys();")
      assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater({failure:'glass_of_beer'}, 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, on#{callback.to_s.capitalize}:function(request){monkeys();}, parameters:Form.serialize(this)}); return false;">),
        form_remote_tag(:update => { :failure => "glass_of_beer" }, :url => { :action => :fast  }, callback=>"monkeys();")
      assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater({success:'glass_of_beer',failure:'glass_of_water'}, 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, on#{callback.to_s.capitalize}:function(request){monkeys();}, parameters:Form.serialize(this)}); return false;">),
        form_remote_tag(:update => { :success => "glass_of_beer", :failure => "glass_of_water" }, :url => { :action => :fast  }, callback=>"monkeys();")
    end

    #HTTP status codes 200 up to 599 have callbacks
    #these should work
    100.upto(599) do |callback|
      assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, on#{callback.to_s.capitalize}:function(request){monkeys();}, parameters:Form.serialize(this)}); return false;">),
        form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }, callback=>"monkeys();")
    end

    #test 200 and 404
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, on200:function(request){monkeys();}, on404:function(request){bananas();}, parameters:Form.serialize(this)}); return false;">),
      form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }, 200=>"monkeys();", 404=>"bananas();")

    #these shouldn't
    1.upto(99) do |callback|
      assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">),
        form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }, callback=>"monkeys();")
    end
    600.upto(999) do |callback|
      assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">),
        form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }, callback=>"monkeys();")
    end

    #test ultimate combo
    assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, on200:function(request){monkeys();}, on404:function(request){bananas();}, onComplete:function(request){c();}, onFailure:function(request){f();}, onLoading:function(request){c1()}, onSuccess:function(request){s()}, parameters:Form.serialize(this)}); return false;\">),
      form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast  }, :loading => "c1()", :success => "s()", :failure => "f();", :complete => "c();", 200=>"monkeys();", 404=>"bananas();")

  end

  def test_submit_to_remote
    assert_dom_equal %(<input name=\"More beer!\" onclick=\"new Ajax.Updater('empty_bottle', 'http://www.example.com/', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)}); return false;\" type=\"button\" value=\"1000000\" />),
      submit_to_remote("More beer!", 1_000_000, :update => "empty_bottle")
  end

  def test_observe_field
    assert_dom_equal %(),
      observe_field("glass", :frequency => 5.minutes, :url => { :action => "reorder_if_empty" })
  end

  def test_observe_field_using_with_option
    expected = %()
    assert_dom_equal expected, observe_field("glass", :frequency => 5.minutes, :url => { :action => "check_value" }, :with => 'id')
    assert_dom_equal expected, observe_field("glass", :frequency => 5.minutes, :url => { :action => "check_value" }, :with => "'id=' + value")
  end

  def test_observe_field_using_json_in_with_option
    expected = %()
    assert_dom_equal expected, observe_field("glass", :frequency => 5.minutes, :url => { :action => "check_value" }, :with => "{'id':value}")
  end

  def test_observe_field_using_function_for_callback
    assert_dom_equal %(),
      observe_field("glass", :frequency => 5.minutes, :function => "alert('Element changed')")
  end

  def test_observe_form
    assert_dom_equal %(),
      observe_form("cart", :frequency => 2, :url => { :action => "cart_changed" })
  end

  def test_observe_form_using_function_for_callback
    assert_dom_equal %(),
      observe_form("cart", :frequency => 2, :function => "alert('Form changed')")
  end

  def test_observe_field_without_frequency
    assert_dom_equal %(),
      observe_field("glass")
  end

  def test_update_page
    block = Proc.new { |page| page.replace_html('foo', 'bar') }
    assert_equal create_generator(&block).to_s, update_page(&block)
  end

  def test_update_page_tag
    block = Proc.new { |page| page.replace_html('foo', 'bar') }
    assert_equal javascript_tag(create_generator(&block).to_s), update_page_tag(&block)
  end

  def test_update_page_tag_with_html_options
    block = Proc.new { |page| page.replace_html('foo', 'bar') }
    assert_equal javascript_tag(create_generator(&block).to_s, {:defer => 'true'}), update_page_tag({:defer => 'true'}, &block)
  end

  protected
    def author_path(record)
      "/authors/#{record.id}"
    end

    def authors_path
      "/authors"
    end

    def author_articles_path(author)
      "/authors/#{author.id}/articles"
    end

    def author_article_path(author, article)
      "/authors/#{author.id}/articles/#{article.id}"
    end
end

class JavaScriptGeneratorTest < Test::Unit::TestCase
  include BaseTest

  def setup
    super
    @generator = create_generator
  end

  def test_insert_html_with_string
    assert_equal 'new Insertion.Top("element", "\\074p\\076This is a test\\074/p\\076");',
      @generator.insert_html(:top, 'element', '
This is a test
')
    assert_equal 'new Insertion.Bottom("element", "\\074p\076This is a test\\074/p\076");',
      @generator.insert_html(:bottom, 'element', '
This is a test
')
    assert_equal 'new Insertion.Before("element", "\\074p\076This is a test\\074/p\076");',
      @generator.insert_html(:before, 'element', '
This is a test
')
    assert_equal 'new Insertion.After("element", "\\074p\076This is a test\\074/p\076");',
      @generator.insert_html(:after, 'element', '
This is a test
')
  end

  def test_replace_html_with_string
    assert_equal 'Element.update("element", "\\074p\\076This is a test\\074/p\\076");',
      @generator.replace_html('element', '
This is a test
')
  end

  def test_replace_element_with_string
    assert_equal 'Element.replace("element", "\\074div id=\"element\"\\076\\074p\\076This is a test\\074/p\\076\\074/div\\076");',
      @generator.replace('element', '

This is a test

')
  end

  def test_remove
    assert_equal 'Element.remove("foo");',
      @generator.remove('foo')
    assert_equal '["foo", "bar", "baz"].each(Element.remove);',
      @generator.remove('foo', 'bar', 'baz')
  end

  def test_show
    assert_equal 'Element.show("foo");',
      @generator.show('foo')
    assert_equal '["foo", "bar", "baz"].each(Element.show);',
      @generator.show('foo', 'bar', 'baz')
  end

  def test_hide
    assert_equal 'Element.hide("foo");',
      @generator.hide('foo')
    assert_equal '["foo", "bar", "baz"].each(Element.hide);',
      @generator.hide('foo', 'bar', 'baz')
  end

  def test_toggle
    assert_equal 'Element.toggle("foo");',
      @generator.toggle('foo')
    assert_equal '["foo", "bar", "baz"].each(Element.toggle);',
      @generator.toggle('foo', 'bar', 'baz')
  end

  def test_alert
    assert_equal 'alert("hello");', @generator.alert('hello')
  end

  def test_redirect_to
    assert_equal 'window.location.href = "http://www.example.com/welcome";',
      @generator.redirect_to(:action => 'welcome')
  end

  def test_delay
    @generator.delay(20) do
      @generator.hide('foo')
    end

    assert_equal "setTimeout(function() {\n;\nElement.hide(\"foo\");\n}, 20000);", @generator.to_s
  end

  def test_to_s
    @generator.insert_html(:top, 'element', '
This is a test
')
    @generator.insert_html(:bottom, 'element', '
This is a test
')
    @generator.remove('foo', 'bar')
    @generator.replace_html('baz', '
This is a test
')

    assert_equal <<-EOS.chomp, @generator.to_s
new Insertion.Top("element", "\\074p\\076This is a test\\074/p\\076");
new Insertion.Bottom("element", "\\074p\\076This is a test\\074/p\\076");
["foo", "bar"].each(Element.remove);
Element.update("baz", "\\074p\\076This is a test\\074/p\\076");
    EOS
  end

  def test_element_access
    assert_equal %($("hello");), @generator['hello']
  end

  def test_element_access_on_records
    assert_equal %($("bunny_5");),   @generator[Bunny.new(:id => 5)]
    assert_equal %($("new_bunny");), @generator[Bunny.new]
  end

  def test_element_proxy_one_deep
    @generator['hello'].hide
    assert_equal %($("hello").hide();), @generator.to_s
  end

  def test_element_proxy_variable_access
    @generator['hello']['style']
    assert_equal %($("hello").style;), @generator.to_s
  end

  def test_element_proxy_variable_access_with_assignment
    @generator['hello']['style']['color'] = 'red'
    assert_equal %($("hello").style.color = "red";), @generator.to_s
  end

  def test_element_proxy_assignment
    @generator['hello'].width = 400
    assert_equal %($("hello").width = 400;), @generator.to_s
  end

  def test_element_proxy_two_deep
    @generator['hello'].hide("first").clean_whitespace
    assert_equal %($("hello").hide("first").cleanWhitespace();), @generator.to_s
  end

  def test_select_access
    assert_equal %($$("div.hello");), @generator.select('div.hello')
  end

  def test_select_proxy_one_deep
    @generator.select('p.welcome b').first.hide
    assert_equal %($$("p.welcome b").first().hide();), @generator.to_s
  end

  def test_visual_effect
    assert_equal %(new Effect.Puff("blah",{});),
      @generator.visual_effect(:puff,'blah')
  end

  def test_visual_effect_toggle
    assert_equal %(Effect.toggle("blah",'appear',{});),
      @generator.visual_effect(:toggle_appear,'blah')
  end

  def test_sortable
    assert_equal %(Sortable.create("blah", {onUpdate:function(){new Ajax.Request('http://www.example.com/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("blah")})}});),
      @generator.sortable('blah', :url => { :action => "order" })
  end

  def test_draggable
    assert_equal %(new Draggable("blah", {});),
      @generator.draggable('blah')
  end

  def test_drop_receiving
    assert_equal %(Droppables.add("blah", {onDrop:function(element){new Ajax.Request('http://www.example.com/order', {asynchronous:true, evalScripts:true, parameters:'id=' + encodeURIComponent(element.id)})}});),
      @generator.drop_receiving('blah', :url => { :action => "order" })
  end

  def test_collection_first_and_last
    @generator.select('p.welcome b').first.hide()
    @generator.select('p.welcome b').last.show()
    assert_equal <<-EOS.strip, @generator.to_s
$$("p.welcome b").first().hide();
$$("p.welcome b").last().show();
      EOS
  end

  def test_collection_proxy_with_each
    @generator.select('p.welcome b').each do |value|
      value.remove_class_name 'selected'
    end
    @generator.select('p.welcome b').each do |value, index|
      @generator.visual_effect :highlight, value
    end
    assert_equal <<-EOS.strip, @generator.to_s
$$("p.welcome b").each(function(value, index) {
value.removeClassName("selected");
});
$$("p.welcome b").each(function(value, index) {
new Effect.Highlight(value,{});
});
      EOS
  end

  def test_collection_proxy_on_collect
    @generator.select('p').collect('a') { |para| para.show }
    @generator.select('p').collect { |para| para.hide }
    assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").collect(function(value, index) {
return value.show();
});
$$("p").collect(function(value, index) {
return value.hide();
});
    EOS
    @generator = create_generator
  end

  def test_collection_proxy_with_grep
    @generator.select('p').grep 'a', /^a/ do |value|
      @generator << '(value.className == "welcome")'
    end
    @generator.select('p').grep 'b', /b$/ do |value, index|
      @generator.call 'alert', value
      @generator << '(value.className == "welcome")'
    end

    assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").grep(/^a/, function(value, index) {
return (value.className == "welcome");
});
var b = $$("p").grep(/b$/, function(value, index) {
alert(value);
return (value.className == "welcome");
});
    EOS
  end

  def test_collection_proxy_with_inject
    @generator.select('p').inject 'a', [] do |memo, value|
      @generator << '(value.className == "welcome")'
    end
    @generator.select('p').inject 'b', nil do |memo, value, index|
      @generator.call 'alert', memo
      @generator << '(value.className == "welcome")'
    end

    assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").inject([], function(memo, value, index) {
return (value.className == "welcome");
});
var b = $$("p").inject(null, function(memo, value, index) {
alert(memo);
return (value.className == "welcome");
});
    EOS
  end

  def test_collection_proxy_with_pluck
    @generator.select('p').pluck('a', 'className')
    assert_equal %(var a = $$("p").pluck("className");), @generator.to_s
  end

  def test_collection_proxy_with_zip
    ActionView::Helpers::JavaScriptCollectionProxy.new(@generator, '[1, 2, 3]').zip('a', [4, 5, 6], [7, 8, 9])
    ActionView::Helpers::JavaScriptCollectionProxy.new(@generator, '[1, 2, 3]').zip('b', [4, 5, 6], [7, 8, 9]) do |array|
      @generator.call 'array.reverse'
    end

    assert_equal <<-EOS.strip, @generator.to_s
var a = [1, 2, 3].zip([4, 5, 6], [7, 8, 9]);
var b = [1, 2, 3].zip([4, 5, 6], [7, 8, 9], function(array) {
return array.reverse();
});
    EOS
  end

  def test_collection_proxy_with_find_all
    @generator.select('p').find_all 'a' do |value, index|
      @generator << '(value.className == "welcome")'
    end

    assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").findAll(function(value, index) {
return (value.className == "welcome");
});
    EOS
  end

  def test_collection_proxy_with_in_groups_of
    @generator.select('p').in_groups_of('a', 3)
    @generator.select('p').in_groups_of('a', 3, 'x')
    assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").inGroupsOf(3);
var a = $$("p").inGroupsOf(3, "x");
    EOS
  end

  def test_collection_proxy_with_each_slice
    @generator.select('p').each_slice('a', 3)
    @generator.select('p').each_slice('a', 3) do |group, index|
      group.reverse
    end

    assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").eachSlice(3);
var a = $$("p").eachSlice(3, function(value, index) {
return value.reverse();
});
    EOS
  end

  def test_debug_rjs
    ActionView::Base.debug_rjs = true
    @generator['welcome'].replace_html 'Welcome'
    assert_equal "try {\n$(\"welcome\").update(\"Welcome\");\n} catch (e) { alert('RJS error:\\n\\n' + e.toString()); alert('$(\\\"welcome\\\").update(\\\"Welcome\\\");'); throw e }", @generator.to_s
  ensure
    ActionView::Base.debug_rjs = false
  end

  def test_literal
    literal = @generator.literal("function() {}")
    assert_equal "function() {}", literal.to_json
    assert_equal "", @generator.to_s
  end

  def test_class_proxy
    @generator.form.focus('my_field')
    assert_equal "Form.focus(\"my_field\");", @generator.to_s
  end

  def test_call_with_block
    @generator.call(:before)
    @generator.call(:my_method) do |p|
      p[:one].show
      p[:two].hide
    end
    @generator.call(:in_between)
    @generator.call(:my_method_with_arguments, true, "hello") do |p|
      p[:three].visual_effect(:highlight)
    end
    assert_equal "before();\nmy_method(function() { $(\"one\").show();\n$(\"two\").hide(); });\nin_between();\nmy_method_with_arguments(true, \"hello\", function() { $(\"three\").visualEffect(\"highlight\"); });", @generator.to_s
  end

  def test_class_proxy_call_with_block
    @generator.my_object.my_method do |p|
      p[:one].show
      p[:two].hide
    end
    assert_equal "MyObject.myMethod(function() { $(\"one\").show();\n$(\"two\").hide(); });", @generator.to_s
  end
end


text:
<?php

namespace Cake\Upgrade\Shell\Task;

use Cake\Console\Shell;
use Cake\Error\Debugger;

/**
 * Provides features for modifying the contents of a file
 *
 */
trait ChangeTrait
{

    /**
     * Make tasks callable
     *
     * @return void
     */
    public function main()
    {
        if (!empty($this->params['dry-run'])) {
            $this->out('<warning>Dry-run mode enabled!</warning>', 1, Shell::QUIET);
        }

        $exclude = ['.git', '.svn', 'vendor', 'Vendor', 'webroot', 'tmp', 'logs'];
        if (empty($this->params['plugin']) && !empty($this->params['namespace']) && $this->params['namespace'] === 'App') {
            $exclude[] = 'plugins';
            $exclude[] = 'Plugin';
        }
        $files = $this->Stage->files($exclude);

        foreach ($files as $file) {
            $this->out(sprintf('<info>Processing %s</info>', Debugger::trimPath($file)));
            $this->process($file);
        }

        $this->Stage->commit();
    }

    /**
     * process
     *
     * @param string $path
     * @return void
     */
    public function process($path)
    {
        if (!$this->_shouldProcess($path)) {
            $this->out('<info>skipping</info>', 1, Shell::VERBOSE);
            return false;
        }

        $return = $this->_process($path);
        if ($return) {
            $this->out('<warning>updated</warning>', 1, Shell::VERBOSE);
        } else {
            $this->out('<info>no change</info>', 1, Shell::VERBOSE);
        }

        return $return;
    }

    /**
     * Default noop
     *
     * @param string $path
     * @return void
     */
    protected function _process($path)
    {
    }

    /**
     * _shouldProcess
     *
     * Default to PHP files only
     *
     * @param string $path
     * @return bool
     */
    protected function _shouldProcess($path)
    {
        return (substr($path, -4) === '.php');
    }

    /**
     * Update the contents of a file using an array of find and replace patterns
     *
     * @param string $contents The file contents to update
     * @param array $patterns The replacement patterns to run.
     * @return string
     */
    protected function _updateContents($contents, $patterns)
    {
        foreach ($patterns as $pattern) {
            $contents = preg_replace($pattern[1], $pattern[2], $contents);
        }
        return $contents;
    }
}


text:
using System;

internal class StartupHook
{
    public static void Initialize(int input)
    {
        // This hook should not be called because it takes a
        // parameter. Instead, the startup hook provider code should
        // throw an exception.
        Console.WriteLine("Hello from startup hook taking int! Input: " + input);
    }
}


text:
Ready to use docker-compose stack with php7 (php7-fpm), nginx and postgresql optimised for Symfony3 applications
(with ELK & Redis)

##Disclaimer
1. Nginx conf & docker-compose.yml assure your project is located in */var/www/* (if not make sure to change the .yml & .conf files)
2. Redis & ELK are optional

##Step by step configuration
###Step 1
make sure [docker](https://docs.docker.com/engine/installation/) and [docker-compose](https://docs.docker.com/compose/install/) are installed

###Step 2
1. Replace every occurence of **_{PROJECT_NAME}_** by the name of you project
2. Rename **_.conf/.site-conf/{PROJECT_NAME}.conf_** to the desired configuration name
3. Replace **_{PROJECT_URL}_** by the desired url of your project.
4. Edit **_DB_USER_**, **_DB_PASS_**, **_DB_NAME_** in **_.conf/.env/db.env_**

##Step 3
update your hosts file with the new url
```bash
sudo echo 127.0.0.1 {PROJECT_URL} www.{PROJECT_URL}  >> /etc/hosts
```

###Step 4
Pull docker images
```bash
docker pull redis:alpine && docker pull willdurand/elk && docker pull php:7-fpm && docker pull nginx:latest && docker pull postgres:latest
```

###Step 5
go to /var/www/project_name & run docker-compose
```bash
docker-compose up -d
```

###Step 6
enjoy ! go to www.project_url (make sure your have something in the directory /var/www/{PROJECT_NAME}/web)

###Step 7 (optional)
Add your ip of your host (seen from your php-fpm container) in _web/config.php_ and _web/app_dev.php_ (mine was 172.18.0.1)
```php
if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
    '127.0.0.1',
    '172.18.0.1', //ip to add
    '::1',
))) {
    header('HTTP/1.0 403 Forbidden');
    exit('This script is only accessible from localhost.');
}
```
If you don't know the ip to add :
```php
var_dump($_SERVER['REMOTE_ADDR']);
if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
```

###Useful commands
1. List all active containers
```bash
docker ps
```
2. List all the images available locally
```bash
docker images
```
3. Open bash in the given docker container (use docker ps to see docker id):
```bash
docker exec -it {docker_id} bash
```
4. Clear cache symfony :
```bash
docker exec -it $(docker ps -f name=php -q) php /var/www/{PROJECT_NAME}/bin/console cache:clear
```

4. Use psql in postgresql container :
```bash
docker exec -it $(docker ps -f name=postgre -q) psql -U postgres
```

##Todo
1. Test db container
2. Use php7-fpm docker images with recommended extensions and Xdebug

##Special thanks
User [Thomas Letellier](https://github.com/ltrtom) for help & support

User [Ronan Guilloux](https://github.com/ronanguilloux) for inspiration


text:
module QA
  module Scenario
    module Test
      module Instance
        class Airgapped < Template
          include Bootable
          include SharedAttributes
          def perform(address, *rspec_options)
            Runtime::Scenario.define(:runner_network, 'airgapped')

            super
          end
        end
      end
    end
  end
end


text:
class CreateTasukuTaskablesPollAnswers < ActiveRecord::Migration
  def change
    create_table :tasuku_taskables_poll_answers do |t|
      t.integer  :author_id
      t.string   :author_type
      t.datetime :created_at
      t.datetime :updated_at
    end
  end
end


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

Nested Elements

        Nested elements are moved into the 'expected' span.

Example

<div concordion:assertEquals="acronym">My <em>simple</em> example</div>

When marked as a failure, with actual value XYZ, it becomes:

<div concordion:assertEquals="acronym" class="failure">
  <del class="expected">My <em>simple</em> example</del>
  <ins class="actual">XYZ</ins>
</div>


text:
package org.openapitools.model;

import java.util.Objects;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.openapitools.model.CauseUserIdCause;
import javax.validation.constraints.*;
import io.swagger.annotations.*;

@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyServerCodegen", date = "2022-06-04T08:09:04.819692Z[Etc/UTC]")
public class CauseAction   {

  private String propertyClass;
  private List<CauseUserIdCause> causes = new ArrayList<>();

  /**
   **/

  @ApiModelProperty(value = "")
  @JsonProperty("_class")
  public String getPropertyClass() {
    return propertyClass;
  }
  public void setPropertyClass(String propertyClass) {
    this.propertyClass = propertyClass;
  }

  /**
   **/

  @ApiModelProperty(value = "")
  @JsonProperty("causes")
  public List<CauseUserIdCause> getCauses() {
    return causes;
  }
  public void setCauses(List<CauseUserIdCause> causes) {
    this.causes = causes;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CauseAction causeAction = (CauseAction) o;
    return Objects.equals(propertyClass, causeAction.propertyClass) &&
        Objects.equals(causes, causeAction.causes);
  }

  @Override
  public int hashCode() {
    return Objects.hash(propertyClass, causes);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class CauseAction {\n");

    sb.append("    propertyClass: ").append(toIndentedString(propertyClass)).append("\n");
    sb.append("    causes: ").append(toIndentedString(causes)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name clientApp.controller:PrincipalEditCtrl
 * @description
 * # PrincipalEditCtrl
 * Controller of the clientApp
 */
angular.module('Admiralty').controller('PrincipalEditCtrl', function ($scope, $routeParams, Principal, $location) {
	$scope.editPrincipal = true;
	$scope.principal = {};
	Principal.one($routeParams.id).get().then(function(principal) {
		$scope.principal = principal;
		$scope.savePrincipal = function() {
			$scope.principal.save().then(function() {
				$location.path('/principal/' + $routeParams.id);
			});
		};
	});
	$scope.back = function() {
		$location.path('/principal/' + $scope.principal._id);
	};
});