text:
<project name="run-tools file" basedir="." default="runClient">
	<property name="service.url" value="https://catissuesvc.wustl.edu:443/wsrf/services/cagrid/Catissue_cacore" />
	<!--<property name="service.url" value="https://sbhost07-vm05.semanticbits.com:9443/wsrf/services/cagrid/Catissue_cacore" />-->
     <property name="decodegen.dir" value="${basedir}/../DECodeGen" />

    <condition property="isUnix" value="true"><or><os family="unix" /><os family="mac" /></or></condition>
    <condition property="isWindows" value="true"><os family="windows" /></condition>

    <path id="cp">
        <fileset dir="${basedir}/ext/dependencies/default/jars"><include name="*.jar"/></fileset>
        <fileset dir="${basedir}/de_codegen"><include name="*.jar" /></fileset>
    </path>

    <taskdef resource="net/sf/antcontrib/antcontrib.properties">
        <classpath>
            <pathelement location="${basedir}/lib/ant-contrib.jar"/>
        </classpath>
    </taskdef>

	<target name="runClient" depends="checkContribTasksDefined, defineContribTasks,checkGlobus, defineClasspaths" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}" />
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
            <arg value="-url" />
            <arg value="${service.url}" />
        </java>
    </target>

    <target name="runQuery1" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
        <property name="runclasspath" refid="run.classpath"/>
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="./cqls/Query205.xml"/>
        </java>
    </target>

      <target name="runCountQuery1" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths"
            description="Run the sample Client">
        <property name="runclasspath" refid="run.classpath"/>
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient"
              classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="./cqls/CountQuery1.xml"/>
        </java>
    </target>

     <target name="runCountQuery2" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths"
            description="Run the sample Client">
        <property name="runclasspath" refid="run.classpath"/>
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient"
              classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="./cqls/CountQuery2.xml"/>
        </java>
    </target>

    <target name="runQuery1_1" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query1.xml" />
  </java>
</target>

<target name="runQuery2" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query2.xml" />
  </java>
</target>
<target name="runQuery3" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query3.xml" />
  </java>
</target>

<target name="runQuery4" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query4.xml" />
  </java>
</target>

<target name="runQuery5" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query5.xml" />
  </java>
</target>

<target name="runQuery205" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query205.xml" />
  </java>
</target>

<target name="runQuery206" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query206.xml" />
  </java>
</target>

<target name="runQuery207" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query207.xml" />
  </java>
</target>

<target name="runQuery208" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
    <property name="runclasspath" refid="run.classpath"/>
	<echo message="Connecting to service: ${service.url}" />
    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
		<jvmarg value="-Dsun.lang.ClassLoader.allowArraySyntax=true"/>
        <arg value="-url" />
		<arg value="${service.url}" />
        <arg value="./cqls/Query208.xml" />
  </java>
</target>

	<target name="runQuery" depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run the sample Client">
	    <property name="runclasspath" refid="run.classpath"/>
		<echo message="Connecting to service: ${service.url}" />
		<echo message="${testFile}"/>
	    <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.Catissue_cacoreClient" classpathref="run.classpath" fork="yes">
	        <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}" />
	        <arg value="-url" />
		    <arg value="${service.url}" />
	        <arg value="${testFile}" />
	  </java>
	</target>

    <target name="runAllQueries"  depends="checkContribTasksDefined, defineContribTasks, checkGlobus, defineClasspaths" description="Run queries against each caTissue Object" >
        <foreach delimiter="," param="testFile" target="runQuery" inheritall="true">
        	<path id="base.path">
        	      <fileset dir="./cqls" casesensitive="no">
        	        <include name="**/*.xml"/>
        	      </fileset>
        	</path>
         </foreach>
    </target>

    <!--START   Writable API targets-->

    <target name="CreateChemotherapy" depends="init" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.WritableAPIClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="CreateChemotherapy"/>
        </java>
    </target>

    <target name="CreateParticipant" depends="init" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.WritableAPIClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="CreateParticipant"/>
        </java>
    </target>

    <target name="CreateParticipantAndCPR" depends="init" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.WritableAPIClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="CreateParticipantAndCPR"/>
        </java>
    </target>

    <target name="CreateSpecimen" depends="init" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.WritableAPIClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="CreateSpecimen"/>
            <arg value="${CPE}"/>
            <arg value="${CPR}"/>
            <arg value="${SC}"/>
            <arg value="${SCHAR}"/>
        </java>
    </target>

    <target name="CreateOrder" depends="init" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.WritableAPIClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="CreateOrder"/>
            <arg value="${SPC}"/>
        </java>
    </target>

    <target name="UpdateOrder" depends="init" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.WritableAPIClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="UpdateOrder"/>
            <arg value="${SPC}"/>
            <arg value="${DP}"/>
            <arg value="${O}"/>
            <arg value="${OI}"/>
        </java>
    </target>

    <target name="DistributeOrder" depends="init" description="Run the sample Client">
        <echo message="Connecting to service: ${service.url}"/>
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.client.WritableAPIClient" classpathref="run.classpath" fork="yes">
            <jvmarg value="-DGLOBUS_LOCATION=${ext.globus.dir}"/>
            <arg value="-url"/>
            <arg value="${service.url}"/>
            <arg value="DistributeOrder"/>
            <arg value="${SPC}"/>
            <arg value="${DP}"/>
            <arg value="${O}"/>
            <arg value="${OI}"/>
            <arg value="${DI}"/>
        </java>
    </target>

    <!--END     Writable API targets-->

    <target name="-mergeORMFiles">
        <echo message="Updating ORM files..." />
        <property name="tempFolder" value="./temp/ormTemp/" />
        <property name="ormFile" value="./lib/catissue_cacore-orm.jar" />
        <mkdir dir="${tempFolder}" />
        <unzip src="./lib/catissue_cacore-orm.jar" dest="${tempFolder}" />
        <copy todir="${tempFolder}" overwrite="true" verbose="false">
            <fileset dir="./de_codegen/hbms">
                <include name="**/*.*" />
            </fileset>
        </copy>
        <jar basedir="${tempFolder}" destfile="${ormFile}" />
        <echo message="Updating ORM files...DONE." />
    </target>

    <target name="-processBeans">
        <basename property="filename" file="${fullFileName}"/>
        <echo message="Processing bean file: ${filename} "/>
        <propertyregex property="schemaFile" input="${filename}" regexp="-beans" replace="-schema" />
        <propertyregex property="schemaFileFullName" input="${fullFileName}" regexp="-beans" replace="-schema" />
        <echo message="The schemafile is: ${schemaFile}" />
        <echo message="The schemafileFullName is: ${schemaFileFullName}" />
        <mkdir dir="./temp/beanTempOrm/${schemaFile}" />
        <unjar src="${fullFileName}" dest="./temp/beanTempBeans/${filename}" />
        <unjar src="${schemaFileFullName}" dest="./temp/beanTempOrm/${schemaFile}" />
        <available file="${schemaFileFullName}" property="file.exists" />
        <echo message="File Exists: ${file.exists}" />
        <property file="./temp/beanTempOrm/${schemaFile}/info.properties" />
        <echo message="Package is: ${packagename}" />
        <propertyregex property="filesLocation" input="${packagename}" regexp="\." replace="/" />
        <property name="fromLocation" value="./temp/beanTempBeans/${filename}/${filesLocation}" />
        <property name="toLocation" value="./temp/beanTemp/${filesLocation}" />
        <echo message="COPY beans FROM: ${fromLocation} TO ${toLocation}" />
        <copy todir="${toLocation}" overwrite="true" verbose="false">
            <fileset dir="${fromLocation}">
                <include name="**/*.*" />
            </fileset>
        </copy>
        <copy todir="./temp/beanTemp/edu/wustl/catissuecore/domain/deintegration/" overwrite="true" verbose="true">
            <fileset dir="./temp/beanTempBeans/${filename}/edu/wustl/catissuecore/domain/deintegration/">
                <include name="**/*.*" />
            </fileset>
        </copy>
    </target>

    <target name="-mergeBeanFiles">
        <echo message="Updating Bean files..." />
        <property name="beanFile" value="./lib/catissue_cacore-beans.jar" />

        <mkdir dir="./temp/beanTemp/" />
        <mkdir dir="./temp/beanTempBeans/" />
        <mkdir dir="./temp/beanTempOrm/" />

        <unzip src="${beanFile}" dest="./temp/beanTemp/" />

        <foreach target="-processBeans" param="fullFileName" inheritall="true">
            <fileset dir="./de_codegen/artifacts" casesensitive="yes">
                <include name="**/*-beans.jar"/>
            </fileset>
        </foreach>
        <jar basedir="./temp/beanTemp/" destfile="${beanFile}" />
        <echo message="Updating Bean files...DONE." />
    </target>

    <!-- START Service rebuild -->
    <target name="updateService" depends="all">

        <tstamp><format property="install.time" pattern="yyyy-MM-dd_HH-mm"/></tstamp>
        <mkdir dir="./logs" />
        <record name="./logs/updateService-${install.time}.log" action="start" />

    	<delete dir="./temp" failonerror="false"/>
    	<mkdir dir="./temp" />

        <antcall target="-mergeBeanFiles" />
        <antcall target="-mergeORMFiles" />

        <!-- DOZER MERGE -->
        <foreach target="-processDozer" param="fullFileName" inheritall="true">
            <fileset dir="./de_codegen/artifacts" casesensitive="yes">
                <include name="**/*-dozer-files.jar"/>
            </fileset>
        </foreach>

        <!-- Compile DECodeGen and prepare artifacts -->
        <ant inheritAll="false" inheritRefs="false" antfile="${decodegen.dir}/build.xml" target="all" dir="${decodegen.dir}">
            <property name="basedir" value="${decodegen.dir}"/>
        </ant>

        <!-- XMIs MERGE-->
        <antcall target="-fixArtifacts">
            <param name="dir" value="${basedir}/de_codegen/xmi" />
        </antcall>

        <ant inheritAll="false" inheritRefs="false" antfile="../DECodeGen/build.xml" target="-doMergeXMIs" dir="../DECodeGen/">
            <property name="xmiFolder" value="${basedir}/de_codegen/xmi" />
            <property name="outputXMLFile" value="${basedir}/de_codegen/xmi/mergeResult.xml" />
            <property name="outputFixedXMLFile" value="${basedir}/de_codegen/xmi/fixedDomainModel.xml" />
        </ant>

        <!-- OVERWRITE ./etc/catissue_cacore_domainModel.xml -->
        <copy file="${basedir}/de_codegen/xmi/fixedDomainModel.xml" tofile="${basedir}/etc/catissue_cacore_domainModel.xml" />

        <!--COPY BEANS-->
<!--
        <copy todir="${basedir}/lib">
            <fileset dir="${basedir}/de_codegen/artifacts/">
                <include name="*-beans.jar" />
            </fileset>
        </copy>
-->

        <!-- MERGE CASTOR MAPPINGS -->
        <foreach target="-doMergeCastorMappingXMLs" param="fullJarFileName" inheritall="true">
            <fileset dir="./de_codegen/artifacts" casesensitive="yes">
                <include name="*-schema.jar"/>
            </fileset>
        </foreach>

        <echo message="DEBUG: Creating XSD Storage... :)" />
        <mkdir dir="./temp/XSDStorage" />

        <!-- Copy all main XSDs to a Storage -->
        <foreach target="-synchronizeXSDs" param="fullJarFileName" inheritall="false">
            <fileset dir="./de_codegen/artifacts" casesensitive="yes">
                <include name="*-schema.jar"/>
            </fileset>
        </foreach>

        <!-- replace "id" to "identifier "-->
        <echo message="DEBUG: Replacing 'id' to 'identifier'" />
        <replace dir="./temp/XSDStorage" includes="**/*.xsd" summary="true" token="xs:attribute name="id"" value="xs:attribute name="identifier"" />

        <!-- XSDs IMPORT -->
        <foreach target="-importXSDs" param="fullJarFileName" inheritall="false">
            <fileset dir="./de_codegen/artifacts" casesensitive="yes">
                <include name="*-schema.jar"/>
            </fileset>
        </foreach>

        <!-- CLEAN UP -->
        <delete>
            <fileset dir="./de_codegen/artifacts">
                <include name="*.jar" />
            </fileset>
            <fileset dir="./de_codegen/xmi">
                <exclude name="caTissueCore_v2.0.xmi" />
                <include name="*.xmi" />
                <include name="*.xml" />
            </fileset>
            <fileset dir="./temp">
                <include name="**/*" />
                <exclude name="imported_xsds.properties" />
            </fileset>
        </delete>

    </target>

	<target name="-fixArtifacts">
    	<echo>Fixing inconsistent XMIs and other artifacts...</echo>

        <!-- CASTOR -->
    	<replace dir="${dir}" includes="**/*" summary="true" token="ParticipantRecordEntry_Participant" value="ParticipantRecordEntryCollection"/>
		<replace dir="${dir}" includes="**/*" summary="true" token="SCGRecordEntry_SpecimenCollectionGroup" value="ScgRecordEntryCollection"/>
		<replace dir="${dir}" includes="**/*" summary="true" token="SpecimenRecordEntry_Specimen" value="SpecimenRecordEntryCollection"/>
		<replace dir="${dir}" includes="**/*" summary="true" token="name="SpecimenRecordEntryCollectionBaseSolidTissuePathologyAnnotation" value="name="SpecimenRecordEntry_SpecimenBaseSolidTissuePathologyAnnotation"/>

        <!-- DOZER -->
        <replace dir="${dir}" includes="**/*" summary="true" token="<a>SpecimenRecordEntryCollectionBaseSolidTissuePathologyAnnotation</a>" value="<a>SpecimenRecordEntry_SpecimenBaseSolidTissuePathologyAnnotation</a>"/>
        <replace dir="${dir}" includes="**/*" summary="true" token="<b>SpecimenRecordEntryCollectionBaseSolidTissuePathologyAnnotation.specimenRecordEntry</b>" value="<b>specimenRecordEntry_SpecimenBaseSolidTissuePathologyAnnotation.specimenRecordEntry</b>"/>

	</target>

<!--
    <target name="mergeCastor">
        <foreach target="-doMergeCastorMappingXMLs" param="fullJarFileName" inheritall="true">
            <fileset dir="./de_codegen/artifacts" casesensitive="yes">
                <include name="*-schema.jar"/>
            </fileset>
        </foreach>
    </target>
-->

    <target name="-doMergeCastorMappingXMLs">
        <basename property="jarfilename" file="${fullJarFileName}"/>
        <unjar src="${fullJarFileName}" dest="./temp/${jarfilename}" />

        <antcall target="-fixArtifacts">
            <param name="dir" value="./temp/${jarfilename}" />
        </antcall>

        <property name="fileOne" value="./temp/${jarfilename}/xml-mapping.xml" />
        <property name="fileTwo" value="./temp/${jarfilename}/unmarshaller-xml-mapping.xml" />

        <available file="${fileOne}" property="fileOne.exists" />
        <available file="${fileTwo}" property="fileTwo.exists" />

        <echo message="FILE1: ${fileOne}: ${fileOne.exists}" />
        <echo message="FILE2: ${fileTwo}: ${fileTwo.exists}" />

        <!--
            THE ORDER OF THE XML MAPPING FILES IS IMPORTANT, THAT's WHY ORIGINAL CASTOR FILE WILL GO FIRST
            SEE: edu.wustl.catissuecore.domain.util.CastorMappingMerger#doMerge
            SEE: https://bugzilla.wustl.edu/bugzilla/show_bug.cgi?id=22165
        -->
        <java failonerror="true" classname="edu.wustl.catissuecore.domain.util.CastorMappingMerger" fork="yes" dir="${basedir}">
            <classpath>
                <fileset dir="./build/lib/"><include name="*.jar" /></fileset>
                <fileset dir="./lib/"><include name="*.jar" /></fileset>
            </classpath>
            <arg value="./src/edu/wustl/catissuecore/domain/Catissue_cacore-xml-mapping.xml"/>
            <arg value="${fileOne}"/>
            <arg value="./src/edu/wustl/catissuecore/domain/Catissue_cacore-xml-mapping.xml"/>
        </java>

        <java failonerror="true" classname="edu.wustl.catissuecore.domain.util.CastorMappingMerger" fork="yes" dir="${basedir}">
            <classpath>
                <fileset dir="./build/lib/"><include name="*.jar" /></fileset>
                <fileset dir="./lib/"><include name="*.jar" /></fileset>
            </classpath>
            <arg value="./src/edu/wustl/catissuecore/domain/Catissue_cacore-unmarshaller-xml-mapping.xml"/>
            <arg value="${fileTwo}"/>
            <arg value="./src/edu/wustl/catissuecore/domain/Catissue_cacore-unmarshaller-xml-mapping.xml"/>
        </java>

    </target>

    <target name="-synchronizeXSDs">
        <basename property="jarfilename" file="${fullJarFileName}"/>
        <echo message="Sending new XSDs to the storage: ${jarfilename} "/>
        <unjar src="${fullJarFileName}" dest="./temp/${jarfilename}" />
        <property file="./temp/${jarfilename}/info.properties" />
        <echo message="DEBUG: Copy main XSD to Storage:" />
        <copy file="./temp/${jarfilename}/${packagename}.xsd" todir="./temp/XSDStorage" overwrite="true" verbose="true" />
    </target>

    <target name="-importXSDs">
        <basename property="jarfilename" file="${fullJarFileName}"/>
        <echo message="Processing XSD folder: ${jarfilename} "/>
        <unjar src="${fullJarFileName}" dest="./temp/${jarfilename}" />

       	<!-- Do various fixes to the schemas. -->
        <antcall target="-fixArtifacts">
            <param name="dir" value="./temp/${jarfilename}" />
        </antcall>

    	<java failonerror="true" classname="edu.wustl.catissuecore.domain.util.XSDConflictsResolver" fork="yes">
            <classpath>
                <fileset dir="build/lib/"><include name="*.jar" /></fileset>
                <fileset dir="lib/"><include name="*.jar" /></fileset>
            </classpath>
            <arg value="./temp/${jarfilename}"/>
    	</java>

        <property file="./temp/${jarfilename}/info.properties" />

        <!-- BEFORE RUNNING THE IMPORT we have to sync all DE XSDs with the storage and schema folder -->
        <foreach target="-bringSecondaryXSDsFromStorage" param="fullFileName" inheritall="true">
            <fileset dir="./temp/${jarfilename}" casesensitive="yes">
                <include name="gov.nih.nci.dynext*.xsd" />
                <exclude name="${packagename}.xsd" />
            </fileset>
        </foreach>

        <echo message="DEBUG: Importing main XSD: ${packagename}" />
        <foreach target="-importXSD" param="fullFileName" inheritall="true">
            <fileset dir="./temp/${jarfilename}" casesensitive="yes">
                <include name="gov.nih.nci.dynext*.xsd"/>
            </fileset>
        </foreach>

        <!--COPY Other files - DO NOT OVERWRITE -->
        <!--<copy overwrite="false" verbose="true">-->

    	<copy todir="./schema/Catissue_cacore" overwrite="true" verbose="true">
    		<fileset dir="./temp/${jarfilename}" casesensitive="yes">
            	<include name="SCGRecordEntry.xsd"/>
            	<include name="SpecimenRecordEntry.xsd"/>
            	<include name="ParticipantRecordEntry.xsd"/>
            	<include name="ActionApplicationRecordEntry.xsd"/>
			</fileset>
    	</copy>

    	<antcall target="all"/>

    </target>

    <target name="-bringSecondaryXSDsFromStorage">
        <basename property="filename" file="${fullFileName}" />
        <echo message="DEBUG: Storage or Schema Sync: ${filename}" />
        <if>
            <and><available file="./temp/XSDStorage/${filename}" property="fileIsInStorage" /></and>
            <then>
                <echo message="DEBUG: File found in Storage" />
                <dirname property="dir" file="${fullFileName}"/>
                <copy file="./temp/XSDStorage/${filename}" todir="${dir}" verbose="true" overwrite="true"/>
                <copy file="./temp/XSDStorage/${filename}" todir="./schema/Catissue_cacore/" verbose="true" overwrite="true"/>
            </then>
        </if>
        <if>
            <and><available file="./schema/Catissue_cacore/${filename}" property="fileIsInSchemaFolder" /></and>
            <then>
                <echo message="DEBUG: File found in Schema Folder" />
                <dirname property="dir" file="${fullFileName}"/>
                <copy file="./schema/Catissue_cacore/${filename}" todir="${dir}" verbose="true" overwrite="true"/>
                <copy file="./schema/Catissue_cacore/${filename}" todir="./schema/Catissue_cacore/" verbose="true" overwrite="true"/>
            </then>
        </if>
        <echo message="DONE." />
    </target>

    <target name="-importXSD">
        <basename property="filename" file="${fullFileName}"/>
    	<echo message="DEBUG: XSD Import analysis for ${filename} "/>

        <if>
            <and><available file="./temp/imported_xsds.properties"  /></and>
            <else>
                <touch file="./temp/imported_xsds.properties" verbose="true" />
            </else>
        </if>

        <property file="./temp/imported_xsds.properties" />
        <propertycopy name="FileImportedValue" from="${filename}" silent="true" />
        <echo message="DEBUG: Is file ${filename} already imported ? ${FileImportedValue}" />

        <if>
            <equals arg1="${FileImportedValue}" arg2="true" />
            <then>
                <echo message="DEBUG: It is imported. SKIPPING..." />
            </then>
            <else>
                <echo message="DEBUG: It is NOT imported. IMPORTING..." />
                <propertyfile file="./temp/imported_xsds.properties" comment="List of imported XSD files">
                    <entry key="${filename}" value="true" />
                </propertyfile>
                <antcall target="doImportXSD">
                    <param name="xsdFile" value="${fullFileName}" />
                </antcall>
            </else>
        </if>

    </target>

    <target name="-processDozer">
        <basename property="filename" file="${fullFileName}"/>
        <echo message="Processing: ${filename} "/>
        <mkdir dir="./temp/${filename}" />
        <unjar src="${fullFileName}" dest="./temp/${filename}" />

        <antcall target="-fixArtifacts">
            <param name="dir" value="./temp/${filename}" />
        </antcall>

        <java failonerror="true" classname="edu.wustl.catissuecore.domain.util.DozerMerger" fork="yes">
            <classpath>
                <fileset dir="build/lib/"><include name="*.jar" /></fileset>
                <fileset dir="lib/"><include name="*.jar" /></fileset>
            </classpath>
            <arg value="mappings"/>
            <arg value="./src/dozerBeanMapping.xml"/>
            <arg value="./temp/${filename}/DozerBeanMapping.xml"/>
            <arg value="./src/dozerBeanMapping.xml"/>
        </java>

        <java failonerror="true" classname="edu.wustl.catissuecore.domain.util.DozerMerger" fork="yes">
            <classpath>
                <fileset dir="build/lib/"><include name="*.jar" /></fileset>
                <fileset dir="lib/"><include name="*.jar" /></fileset>
            </classpath>
            <arg value="properties"/>
            <arg value="./temp/${filename}/genericCustomConverterParentRef.properties"/>
            <arg value="./src/edu/wustl/catissuecore/domain/genericCustomConverterParentRef.properties"/>
            <arg value="./src/edu/wustl/catissuecore/domain/genericCustomConverterParentRef.properties"/>
        </java>

        <java failonerror="true" classname="edu.wustl.catissuecore.domain.util.DozerMerger" fork="yes">
            <classpath>
                <fileset dir="build/lib/"><include name="*.jar" /></fileset>
                <fileset dir="lib/"><include name="*.jar" /></fileset>
            </classpath>
            <arg value="properties"/>
            <arg value="./temp/${filename}/genericCustomConverterSets.properties"/>
            <arg value="./src/edu/wustl/catissuecore/domain/genericCustomConverterSets.properties"/>
            <arg value="./src/edu/wustl/catissuecore/domain/genericCustomConverterSets.properties"/>
        </java>

    </target>

    <target name="doImportXSD">
        <property name="xsdFile" value="${decodegen.dir}/src/test/resources/withIdentifier/clinical_annotation.xsd"/>
        <echo message="Importing XSD: ${xsdFile}" />
        <antcall target="ex">
            <param name="xsdFile" value="${xsdFile}" />
        </antcall>
    </target>

    <target name="exUnix" unless="isWindows">
        <exec dir="../DECodeGen/" executable="chmod">
            <arg value="755"/>
            <arg value="./execute.sh"/>
        </exec>
        <exec dir="../DECodeGen/" executable="./execute.sh">
            <arg value="os"/>
            <arg value="Unix"/>
            <arg value="${xsdFile}"/>
        </exec>
    </target>

    <target name="ex" unless="isUnix" depends="exUnix">
        <exec dir="../DECodeGen/" executable="cmd">
            <arg value="/c"/>
            <arg value="execute.bat"/>
            <arg value="os"/>
            <arg value="Windows"/>
            <arg value="${xsdFile}"/>
        </exec>
    </target>

    <target name="-testJ">
        <ant inheritAll="false" inheritRefs="false" antfile="../DECodeGen/build.xml" target="-doMergeXMIs" dir="../DECodeGen/">
            <property name="xmiFolder" value="/temp/xmi/" />
            <property name="outputXMLFile" value="/temp/xmi/result.xml" />
            <property name="outputFixedXMLFile" value="/temp/xmi/ZZZ.xml" />
        </ant>
    </target>

    <!-- END -->
</project>

redpajama_set_name: RedPajamaGithub


text:
module TokyoMetro::Modules::ToFactory::Api::Convert::Patch::TrainTimetable::MusashiKosugiInNambokuLine

  def self.set_modules
    ::TokyoMetro::Api::TrainTimetable::Info.class_eval do
      prepend ::TokyoMetro::Modules::ToFactory::Api::Convert::Patch::TrainTimetable::MusashiKosugiInNambokuLine::Info
    end
  end

end


text:
==================
flask-s3-multipart
==================

This is a sample project to demonstrate how to upload directly to Amazon S3 via CORS using Flask making use of the multipart upload REST API.

The uploaded file will be chunked and sent to S3 concurrently. Every failed Ajax request will be retried until successful.

Using
=====

- Make sure the permission and CORS configuration of your S3 bucket are set properly.

- Fill in these values in app.py:

  * AWS_ACCESS_KEY_ID

  * AWS_SECRET_KEY

  * S3_BUCKET_NAME

- Run app.py as usual.

    python app.py

Sample CORS Configuration
=========================

Sample CORS configuration to enable CORS API::

    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
        <CORSRule>
            <AllowedOrigin>*</AllowedOrigin>
            <AllowedMethod>GET</AllowedMethod>
            <AllowedMethod>POST</AllowedMethod>
            <AllowedMethod>PUT</AllowedMethod>
            <MaxAgeSeconds>3000</MaxAgeSeconds>
            <ExposeHeader>ETag</ExposeHeader>
            <AllowedHeader>*</AllowedHeader>
            <AllowedHeader>Access-Control-Expose-Headers</AllowedHeader>
        </CORSRule>
    </CORSConfiguration>

Note the \* in the AllowedOrigin which means that any domain is allowed to use the CORS API.
Be sure to change it.

Sample Bucket Policy
====================

Sample bucket policy to enable everyone to download objects from the bucket::

    {
        "Version": "2008-10-17",
        "Id": "Policy1378976564974",
        "Statement": [
            {
                "Sid": "Stmt1378976561483",
                "Effect": "Allow",
                "Principal": {
                    "AWS": "*"
                },
                "Action": "s3:GetObject",
                "Resource": "arn:aws:s3:::your-bucket-name/\*"
            }
        ]
    }

Useful Docs
===========

`Amazon: Multipart Upload Overview <http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html>`_

`Amazon: API Support for Multipart Upload <http://docs.aws.amazon.com/AmazonS3/latest/dev/sdksupportformpu.html>`_

`Amazon: Signing and Authenticating REST Requests <http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html>`_

`Amazon: Enabling Cross-Origin Resource Sharing <http://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html>`_

Useful References
=================

`mule-uploader <https://github.com/cinely/mule-uploader>`_

`s3-multipart <https://github.com/maxgillett/s3_multipart>`_


text:
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Constants } from '../../utils/constants';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  public canActivate() {
    // TODO - use angular2 location object
    let previousRoute: string = window.location.toString();

    if (previousRoute && previousRoute.indexOf('#') !== -1) {
      previousRoute = previousRoute.substring(previousRoute.indexOf('#') + 1);
    } else {
      previousRoute = '/';
    }

    sessionStorage.setItem('previousRoute', previousRoute);

    const credentials = sessionStorage.getItem(Constants.CREDENTIALS_KEY);

    if (credentials) {
      return true;
    }

    this.router.navigate(['/login']);

    return false;
  }
}


text:
package com.mrfawy.npc.objects;

import java.util.Date;
import java.util.List;

public class TestObjB {
	private int z;
	private String k;
	private Date date = new Date();

	private List<TestObjC> testObjCList;

	public int getZ() {
		return z;
	}

	public void setZ(int z) {
		this.z = z;
	}

	public String getK() {
		return k;
	}

	public void setK(String k) {
		this.k = k;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public List<TestObjC> getTestObjCList() {
		return testObjCList;
	}

	public void setTestObjCList(List<TestObjC> testObjCList) {
		this.testObjCList = testObjCList;
	}

}


text:
<input type="checkbox" ng-model="showControl">Display form</input>
<div ng-form="loginForm" ng-hide="!showControl" class="login-form">
	<input type="text" ng-model="user.name" />
	<input type="password" ng-model="user.password" />
	<ng-transclude></ng-transclude>
	<button ng-click="submitLogin()">Login</button>
	<button ng-click="submitRegister()">Register</button>
</div>


text:
namespace Bakery.Cqrs.Exception
{
	using System;

	public class MissingRegistrationException
		: InvalidOperationException
	{
		private readonly Type type;

		public MissingRegistrationException(Type type)
		{
			if (type == null)
				throw new ArgumentNullException(nameof(type));

			this.type = type;
		}

		public override String Message => $"Registration not found for {type.Name}.";
	}
}


text:
import './styles';

import { exportEntity } from 'odgn-entity/src/util/export/json';
import { Entity } from 'odgn-entity/src/entity';
import { EntitySet } from 'odgn-entity/src/entity_set';

export default ({ InlineCSS, e, deps, es, site, ...args }) => {

    return <>
        <InlineCSS />
        {processDeps(es, e, deps)}
    </>;
}

function processDeps(es: EntitySet, e: Entity, deps:Entity[]) {
    return
        Dependencies Of {e.id}
        { deps !== undefined ?
            deps.map( dep => depToElement(es, e, dep))
            : null
        }

}

function depToElement( es:EntitySet, e:Entity, dep:Entity ){
    const com = dep.Dep;
    const { '@d': did, '@e': eid, src, type } = com;

    let label = dep.Meta?.meta.label ?? '';

    return

<a href={`/_e/${src}`}>{src}

←

{type}

{label}

}


text:
require 'test_helper'

class ABITypeTest < Minitest::Test
  include Ethereum::ABI

  def test_type_parse
    assert_equal Type.new('uint',  '8', []),              Type.parse("uint8")
    assert_equal Type.new('bytes', '32', []),             Type.parse("bytes32")
    assert_equal Type.new('uint',  '256',     [10]),      Type.parse("uint256[10]")
    assert_equal Type.new('fixed', '128x128', [1,2,3,0]), Type.parse("fixed128x128[1][2][3][]")
  end

  def test_type_parse_validations
    assert_raises(Type::ParseError) { Type.parse("string8") }
    assert_raises(Type::ParseError) { Type.parse("bytes33") }
    assert_raises(Type::ParseError) { Type.parse('hash')}
    assert_raises(Type::ParseError) { Type.parse('address8') }
    assert_raises(Type::ParseError) { Type.parse('bool8') }
    assert_raises(Type::ParseError) { Type.parse('decimal') }

    assert_raises(Type::ParseError) { Type.parse("int") }
    assert_raises(Type::ParseError) { Type.parse("int2") }
    assert_raises(Type::ParseError) { Type.parse("int20") }
    assert_raises(Type::ParseError) { Type.parse("int512") }

    assert_raises(Type::ParseError) { Type.parse("fixed") }
    assert_raises(Type::ParseError) { Type.parse("fixed256") }
    assert_raises(Type::ParseError) { Type.parse("fixed2x2") }
    assert_raises(Type::ParseError) { Type.parse("fixed20x20") }
    assert_raises(Type::ParseError) { Type.parse("fixed256x256") }
  end

  def test_type_size
    assert_nil Type.parse("string").size
    assert_nil Type.parse("bytes").size
    assert_nil Type.parse("uint256[]").size
    assert_nil Type.parse("uint256[4][]").size

    assert_equal 32, Type.parse("uint256").size
    assert_equal 32, Type.parse("fixed128x128").size
    assert_equal 32, Type.parse("bool").size

    assert_equal 64, Type.parse("uint256[2]").size
    assert_equal 128, Type.parse("address[2][2]").size
    assert_equal 1024, Type.parse("ufixed192x64[2][2][2][2][2]").size
  end

  def test_subtype_of_array
    assert_equal [], Type.parse("uint256").subtype.dims
    assert_equal [2], Type.parse("uint256[2][]").subtype.dims
    assert_equal [2], Type.parse("uint256[2][2]").subtype.dims
  end

end


text:
<?php

echo $db->table('my_table')->like('title', 'match')->countAllResults();
// Produces an integer, like 5


text:
package edu.illinois.my.wiki.portlet;

final class ServerKeys {
    static final String WIKI = "wikiServer";

    private ServerKeys() {}
}


text:
package com.ppweather.app.activity;

import com.ppweather.app.R;
import com.ppweather.app.service.AutoUpdateService;
import com.ppweather.app.util.HttpCallbackListener;
import com.ppweather.app.util.HttpUtil;
import com.ppweather.app.util.Utility;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WeatherActivity extends Activity implements OnClickListener{

	private LinearLayout weatherInfoLayout;

	/**
	 * 显示城市名
	 */
	private TextView cityNameText;
	/**
	 * 显示发布时间
	 */
	private TextView publishText;
	/**
	 * 显示天气描述信息
	 */
	private TextView weatherDespText;
	/**
	 * 显示气温1
	 */
	private TextView temp1Text;
	/**
	 * 显示气温2
	 */
	private TextView temp2Text;
	/**
	 * 显示当前日期
	 */
	private TextView currentDateText;
	/**
	 * 切换城市
	 */
	private Button switchCity;
	/**
	 *更新天气
	 */
	private Button refreshWeather;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.weather_layout);

		weatherInfoLayout = (LinearLayout)findViewById(R.id.weather_info_layout);
		cityNameText = (TextView)findViewById(R.id.city_name);
		publishText = (TextView)findViewById(R.id.publish_text);
		weatherDespText = (TextView)findViewById(R.id.weather_desp);
		temp1Text = (TextView)findViewById(R.id.temp1);
		temp2Text = (TextView)findViewById(R.id.temp2);
		currentDateText = (TextView)findViewById(R.id.current_date);
		switchCity = (Button)findViewById(R.id.switch_city);
		refreshWeather = (Button)findViewById(R.id.refresh_weather);

		switchCity.setOnClickListener(this);
		refreshWeather.setOnClickListener(this);

		String countyCode = getIntent().getStringExtra("county_code");
		if (!TextUtils.isEmpty(countyCode)) {
			//有县级代号时就去查询天气
			publishText.setText("同步中。。。");
			Log.d("ssss", "countyCode = " + countyCode);
			weatherInfoLayout.setVisibility(View.INVISIBLE);
			cityNameText.setVisibility(View.INVISIBLE);
			queryWeatherCode(countyCode);
		} else {
			//没有县级代号就直接显示本地天气
			showWeather();
		}
	}

	/**
	 * 查询县级代号对应的天气代号
	 * @param countyCode
	 */
	private void queryWeatherCode(String countyCode) {
		String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml";
		queryFromServer(address, "countyCode");
	}

	/**
	 * 查询天气代号对应的天气
	 * @param weatherCode
	 */
	private void queryWeatherInfo(String weatherCode) {
		String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html";
		queryFromServer(address, "weatherCode");
	}

	private void queryFromServer(final String address, final String type) {
		// TODO Auto-generated method stub
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {

			@Override
			public void onFinish(final String response) {
				// TODO Auto-generated method stub
				if ("countyCode".equals(type)) {
					if (!TextUtils.isEmpty(response)) {
						String[] array = response.split("\\|");
						if (array != null && array.length == 2) {
							String weatherCode = array[1];
							queryWeatherInfo(weatherCode);
						}
					}
				} else if("weatherCode".equals(type)) {
					Log.d("ssss", "weatherCode run ");
					Utility.handleWeatherResponse(WeatherActivity.this, response);
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							showWeather();
						}
					});
				}
			}

			@Override
			public void onError(Exception e) {
				// TODO Auto-generated method stub
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						publishText.setText("同步失败");
					}
				});
			}
		});
	}

	/**
	 * 从SharedPreference文件中读取存储的天气信息,并显示到桌面上
	 */
	private void showWeather() {
		// TODO Auto-generated method stub
		SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
		cityNameText.setText(prefs.getString("city_name", ""));
		Log.d("ssss", "cityNameText = " + cityNameText.getText());
		temp1Text.setText(prefs.getString("temp1", ""));
		temp2Text.setText(prefs.getString("temp2", ""));
		weatherDespText.setText(prefs.getString("weather_desp", ""));
		publishText.setText("今天" + prefs.getString("publish_time", "") + "发布");
		currentDateText.setText(prefs.getString("current_date", ""));
		weatherInfoLayout.setVisibility(View.VISIBLE);
		cityNameText.setVisibility(View.VISIBLE);
		//在showWeather中启动AutoUpdateService。这样一旦选中某城市并成功更新天气,AutoUpdateService就会在后台运行,并8小时更新一次天气
		Intent intent = new Intent(this,AutoUpdateService.class);
		startService(intent);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.switch_city:
			Intent intent = new Intent(this, ChooseAreaActivity.class);
			intent.putExtra("from_weather_activity", true);
			startActivity(intent);
			finish();
			break;
		case R.id.refresh_weather:
			publishText.setText("同步中...");
			//从SharedPreferences中读取天气代号
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			String weatherCode = prefs.getString("weather_code", "");
			if (!TextUtils.isEmpty(weatherCode)) {
				queryWeatherInfo(weatherCode);
			}

		default:
			break;
		}
	}
}


text:
This plugin allows you to build a web application for your project.

You can learn about the features of the Webapp Plugin on the [wiki](https://github.com/inversoft/savant-webapp-plugin/wiki/Home).

You can also use the project's JavaDoc as a reference for the features of the plugin. The JavaDoc are located at https://inversoft.github.io/savant-webapp-plugin/


text:
import unittest
import numpy as np
from quant_dequant_test import QuantDequantTest
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
from paddle.fluid.core import PassVersionChecker
from paddle.fluid.core import AnalysisConfig

class TensorRTMatMulQuantDequantDims3Test(QuantDequantTest):
    def setUp(self):
        self.set_params()

        def network():
            self.data = fluid.data(
                name='data', shape=[1, 28, 28], dtype='float32'
            )
            self.label = fluid.data(name='label', shape=[1, 1], dtype='int64')
            matmul_out = fluid.layers.matmul(
                x=self.data,
                y=self.data,
                transpose_x=self.transpose_x,
                transpose_y=self.transpose_y,
                alpha=self.alpha,
            )
            fc_out = fluid.layers.fc(
                input=matmul_out,
                size=10,
                num_flatten_dims=1,
                bias_attr=False,
                act=None,
            )
            result = fluid.layers.relu(fc_out)
            loss = fluid.layers.cross_entropy(input=result, label=self.label)
            avg_loss = paddle.mean(loss)
            return avg_loss, result

        self.main_program.random_seed = 2
        self.startup_program.random_seed = 2
        self.test_main_program.random_seed = 2
        # self.test_startup_program.random_seed = 2
        with fluid.unique_name.guard():
            with fluid.program_guard(self.main_program, self.startup_program):
                self.loss, result = network()
                opt = fluid.optimizer.Adam(learning_rate=0.0001)
                opt.minimize(self.loss)
        with fluid.unique_name.guard():
            with fluid.program_guard(
                self.test_main_program, self.startup_program
            ):
                network()
        self.feeds = {"data": np.random.random([1, 28, 28]).astype("float32")}
        self.fetch_list = [result]
        self.enable_trt = True
        self.trt_parameters = TensorRTMatMulQuantDequantDims3Test.TensorRTParam(
            1 << 30, 32, 0, AnalysisConfig.Precision.Int8, False, False
        )
        self.activation_quantize_type = 'moving_average_abs_max'
        self.weight_quantize_type = 'channel_wise_abs_max'

    def set_params(self):
        self.transpose_x = False
        self.transpose_y = False
        self.alpha = 1.0

    def test_check_output(self):
        # self.quant_dequant()
        if core.is_compiled_with_cuda():
            use_gpu = True
            self.check_output_with_option(
                use_gpu, atol=1, flatten=False, rtol=1e-1
            )
            self.assertTrue(
                PassVersionChecker.IsCompatible('tensorrt_subgraph_pass')
            )

class TensorRTMatMulQuantDequantDims3TransposeXTest(
    TensorRTMatMulQuantDequantDims3Test
):
    def set_params(self):
        self.transpose_x = True
        self.transpose_y = False
        self.alpha = 2.1

class TensorRTMatMulQuantDequantDims3TransposeYTest(
    TensorRTMatMulQuantDequantDims3Test
):
    def set_params(self):
        self.transpose_x = False
        self.transpose_y = True
        self.alpha = 3.9

class TensorRTMatMulQuantDequantDims3TransposeXYTest(
    TensorRTMatMulQuantDequantDims3Test
):
    def set_params(self):
        self.transpose_x = True
        self.transpose_y = True
        self.alpha = 8.4

class TensorRTMatMulQuantDequantDims4Test(QuantDequantTest):
    def setUp(self):
        self.set_params()

        def network():
            self.data = fluid.data(
                name='data', shape=[1, 28, 28], dtype='float32'
            )
            self.label = fluid.data(name='label', shape=[1, 1], dtype='int64')
            reshape_out = fluid.layers.reshape(self.data, shape=[1, 4, 14, 14])
            matmul_out = fluid.layers.matmul(
                x=reshape_out,
                y=reshape_out,
                transpose_x=self.transpose_x,
                transpose_y=self.transpose_y,
                alpha=self.alpha,
            )
            out = fluid.layers.batch_norm(matmul_out, is_test=True)
            fc_out = fluid.layers.fc(
                input=matmul_out,
                size=10,
                num_flatten_dims=1,
                bias_attr=False,
                act=None,
            )
            result = fluid.layers.relu(fc_out)
            loss = fluid.layers.cross_entropy(input=result, label=self.label)
            avg_loss = paddle.mean(loss)
            return avg_loss, result

        self.main_program.random_seed = 2
        self.startup_program.random_seed = 2
        self.test_main_program.random_seed = 2
        # self.test_startup_program.random_seed = 2
        with fluid.unique_name.guard():
            with fluid.program_guard(self.main_program, self.startup_program):
                self.loss, result = network()
                opt = fluid.optimizer.Adam(learning_rate=0.0001)
                opt.minimize(self.loss)
        with fluid.unique_name.guard():
            with fluid.program_guard(
                self.test_main_program, self.startup_program
            ):
                network()
        self.feeds = {"data": np.random.random([1, 28, 28]).astype("float32")}
        self.fetch_list = [result]
        self.enable_trt = True
        self.trt_parameters = TensorRTMatMulQuantDequantDims4Test.TensorRTParam(
            1 << 30, 32, 0, AnalysisConfig.Precision.Int8, False, False
        )
        self.activation_quantize_type = 'moving_average_abs_max'
        self.weight_quantize_type = 'channel_wise_abs_max'

    def set_params(self):
        self.transpose_x = False
        self.transpose_y = False
        self.alpha = 1.0

    def test_check_output(self):
        # self.quant_dequant()
        if core.is_compiled_with_cuda():
            use_gpu = True
            self.check_output_with_option(
                use_gpu, atol=1, flatten=False, rtol=1e-1
            )
            self.assertTrue(
                PassVersionChecker.IsCompatible('tensorrt_subgraph_pass')
            )

class TensorRTMatMulQuantDequantDims4TransposeXTest(
    TensorRTMatMulQuantDequantDims4Test
):
    def set_params(self):
        self.transpose_x = True
        self.transpose_y = False
        self.alpha = 3.2

class TensorRTMatMulQuantDequantDims4TransposeYTest(
    TensorRTMatMulQuantDequantDims4Test
):
    def set_params(self):
        self.transpose_x = False
        self.transpose_y = True
        self.alpha = 7.5

class TensorRTMatMulQuantDequantDims4TransposeXYTest(
    TensorRTMatMulQuantDequantDims4Test
):
    def set_params(self):
        self.transpose_x = True
        self.transpose_y = True
        self.alpha = 11.2

class TensorRTMatMulQuantDequantDims3DynamicTest(QuantDequantTest):
    def setUp(self):
        self.set_params()

        def network():
            self.data = fluid.data(
                name='data', shape=[-1, 28, 28], dtype='float32'
            )
            self.label = fluid.data(name='label', shape=[1, 1], dtype='int64')
            matmul_out = fluid.layers.matmul(
                x=self.data,
                y=self.data,
                transpose_x=self.transpose_x,
                transpose_y=self.transpose_y,
                alpha=self.alpha,
            )
            out = fluid.layers.batch_norm(matmul_out, is_test=True)
            fc_out = fluid.layers.fc(
                input=matmul_out,
                size=10,
                num_flatten_dims=1,
                bias_attr=False,
                act=None,
            )
            result = fluid.layers.relu(fc_out)
            loss = fluid.layers.cross_entropy(input=result, label=self.label)
            avg_loss = paddle.mean(loss)
            return avg_loss, result

        self.main_program.random_seed = 2
        self.startup_program.random_seed = 2
        self.test_main_program.random_seed = 2
        # self.test_startup_program.random_seed = 2
        with fluid.unique_name.guard():
            with fluid.program_guard(self.main_program, self.startup_program):
                self.loss, result = network()
                opt = fluid.optimizer.Adam(learning_rate=0.0001)
                opt.minimize(self.loss)
        with fluid.unique_name.guard():
            with fluid.program_guard(
                self.test_main_program, self.startup_program
            ):
                network()
        self.feeds = {"data": np.random.random([3, 28, 28]).astype("float32")}
        self.fetch_list = [result]
        self.enable_trt = True
        self.trt_parameters = (
            TensorRTMatMulQuantDequantDims3DynamicTest.TensorRTParam(
                1 << 30, 32, 0, AnalysisConfig.Precision.Int8, False, False
            )
        )
        self.dynamic_shape_params = (
            TensorRTMatMulQuantDequantDims3DynamicTest.DynamicShapeParam(
                {'data': [1, 28, 28]},
                {'data': [4, 28, 28]},
                {'data': [3, 28, 28]},
                False,
            )
        )
        self.activation_quantize_type = 'moving_average_abs_max'
        self.weight_quantize_type = 'channel_wise_abs_max'

    def set_params(self):
        self.transpose_x = False
        self.transpose_y = False
        self.alpha = 1.0

    def test_check_output(self):
        # self.quant_dequant()
        if core.is_compiled_with_cuda():
            use_gpu = True
            self.check_output_with_option(
                use_gpu, atol=1, flatten=False, rtol=1e-1
            )
            self.assertTrue(
                PassVersionChecker.IsCompatible('tensorrt_subgraph_pass')
            )

class TensorRTMatMulQuantDequantDims4TransposeXDynamicTest(
    TensorRTMatMulQuantDequantDims3DynamicTest
):
    def set_params(self):
        self.transpose_x = True
        self.transpose_y = False
        self.alpha = 2.0

class TensorRTMatMulQuantDequantDims4TransposeYDynamicTest(
    TensorRTMatMulQuantDequantDims3DynamicTest
):
    def set_params(self):
        self.transpose_x = False
        self.transpose_y = True
        self.alpha = 2.2

class TensorRTMatMulQuantDequantDims4TransposeXYDynamicTest(
    TensorRTMatMulQuantDequantDims3DynamicTest
):
    def set_params(self):
        self.transpose_x = True
        self.transpose_y = True
        self.alpha = 7.8

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


text:
require "redis"
require "redis-lock"

module Contacts
  class DistributedLock
    LIFETIME = (5 * 60) # seconds. The lock expires automatically after this time

    def lock
      Redis.new.lock("contacts-admin:organisations:import", life: LIFETIME) do
        Rails.logger.debug("Successfully got a lock. Running...")
        yield
      end
    rescue Redis::Lock::LockNotAcquired => e
      Rails.logger.debug("Failed to get lock for organisations:import (#{e.message}). Another process probably got there first.")
    end
  end
end


text:
import java.awt.Color;

/**
 * Provides geometric and mathematical utility functions.
 */
public class Geo
{
	/**
	 * Linear interpolate from A to B by fraction F.
	 */
	public static double lerp( double a, double b, double f ) {
		return a + (b-a) * f;
	}

	/**
	 * Linear interpolate from A to B by fraction F.
	 */
	public static Vec2 lerp( Vec2 a, Vec2 b, double f ) {
		return new Vec2(
			lerp( a.x, b.x, f ),
			lerp( a.y, b.y, f )
		);
	}

	/**
	 * Linear interpolate colour from A to B by fraction F.
	 */
	public static Color lerp( Color a, Color b, double f ) {
		return new Color(
			(int) lerp( a.getRed(),   b.getRed(),   f ),
			(int) lerp( a.getGreen(), b.getGreen(), f ),
			(int) lerp( a.getBlue(),  b.getBlue(),  f )
		);
	}

	/**
	 * Transform a linear [0:1] interpolant into a hermite curve.
	 */
	public static double hermite( double f ) {
		return f * f * (3.0 - (2.0 * f));
	}

	/**
	 * Hermite interpolate from A to B by fraction F.
	 */
	public static double herp( double a, double b, double f ) {
		return lerp( a, b, hermite(f) );
	}

	/**
	 * Normalise given current value and min/max.
	 */
	public static double unlerp( double v, double minv, double maxv ) {
		double base  = v    - minv;
		double delta = maxv - minv;
		return base / delta;
	}

	/**
	 * Clamp to inclusive range.
	 */
	public static double clamp( double v, double minv, double maxv  ) {
		return Math.min( Math.max(v,minv), maxv );
	}

	/**
	 * Transform a monotonically increasing linear input into a sinewave.
	 * Waveform: One dip and rise per period, zero at edges and centre.
	 * Cycle:    Dip -> zero -> rise -> zero  [v^]
	 * Range:    [-1:+1] inclusive.
	 */
	public static double sineSync( double input, double wavelength ) {
	    double half = wavelength * 0.5;
	    double mod  = (input % wavelength) - half;
	    double pm1  = mod / half;
	    return Math.sin( pm1 * Math.PI );
	}

	/**
	 * Same as sineSync but with user-defined output range.
	 */
	public static double sineSync( double input, double wavelength, double low, double high ) {
	    double sine = sineSync( input, wavelength );
	    double f    = (sine * 0.5) + 0.5;
	    return lerp( low, high, f );
	}

	/**
	 * Get relative coordinate offset for given length and direction.
	 */
	public static Vec2 lenDir( double len, double dir ) {
		double radians = Math.toRadians( dir );
		return new Vec2( Math.cos(radians) * len,
					    -Math.sin(radians) * len );
	}
}


text:
package com.gliffy.test.restunit;

import java.util.*;

import com.gliffy.restunit.*;
import com.gliffy.restunit.http.*;

import org.testng.*;
import org.testng.annotations.*;

import static org.easymock.classextension.EasyMock.*;

public class TestExecutor
{
    @Test(groups = {"executor"})
    public void testBadSetup()
    {
        Executor executor = new Executor();
        executor.setBaseURL("http://www.google.com/");

        try
        {
            executor.execute(CallFactory.getRandomCall());
            assert false : "Expected an exception when HTTP wasn't configured";
        }
        catch (IllegalStateException e)
        {
            // successful test
        }
    }

    @Test(dataProvider = "methods", groups={"executor"})
    public void testBasicMethodNoBaseURL(String method)
    {
        Http mockHttp = getMockHttp(method.toUpperCase());

        replay(mockHttp);

        RestCall test = CallFactory.getRandomCall();
        test.setURL("http://www.google.com/" + test.getURL());
        test.setMethod(method.toUpperCase());
        test.getResponse().setStatusCode(200);
        clearHeaderRequirements(test);

        Executor executor = new Executor();
        executor.setHttp(mockHttp);
        RestCallResult result = executor.execute(test);

        assert result.getResult() == Result.PASS : "Got " + result.getResult() + " for " + result.toString() + " instead of " + Result.PASS.toString();

        verify(mockHttp);
    }

    /** Runs a basic test for a method to see that it gets called.
     * @param method the method to use
     */
    @Test(dataProvider = "methods", groups={"executor"})
    public void testBasicMethod(String method)
    {
        Http mockHttp = getMockHttp(method.toUpperCase());

        replay(mockHttp);

        RestCall test = CallFactory.getRandomCall();
        test.setMethod(method.toUpperCase());
        test.getResponse().setStatusCode(200);
        clearHeaderRequirements(test);

        Executor executor = new Executor();
        executor.setHttp(mockHttp);
        executor.setBaseURL("http://www.google.com/");
        RestCallResult result = executor.execute(test);

        assert result.getResult() == Result.PASS : "Got " + result.getResult() + " for " + result.toString() + " instead of " + Result.PASS.toString();

        verify(mockHttp);
    }

    /** This tests that the HttpRequest created by the Executor to give to Http was done using the actual
     * test information; the Executor must interrogate the test to find out what to request
     */
    @Test(groups = {"executor"})
    public void testRequestCreation()
    {
        RestCall mockCall = createMock(RestCall.class);
        RestCall randomCall = CallFactory.getRandomGetCall();

        expect(mockCall.getName()).andReturn("Mock Call").anyTimes();
        expect(mockCall.getMethod()).andReturn("GET");
        expect(mockCall.getURL()).andReturn(randomCall.getURL());
        expect(mockCall.getParameters()).andReturn(randomCall.getParameters());
        expect(mockCall.getHeaders()).andReturn(randomCall.getHeaders());
        expect(mockCall.getResponse()).andReturn(randomCall.getResponse());

        Http mockHttp = getMockHttp("GET");
        replay (mockHttp);
        replay (mockCall);

        Executor executor =  new Executor();
        executor.setHttp(mockHttp);
        executor.setBaseURL("http://www.google.com/");
        executor.execute(mockCall);

        verify(mockHttp);
        verify(mockCall);
    }

    /** This tests that the results returned from the MockHTTP service ended up in the right place in the test results
     */
    @Test(groups = {"executor"})
    public void testResultPopulationSuccess()
    {
        RestCall fakeCall = CallFactory.getRandomGetCall();
        fakeCall.setMethod("GET");
        fakeCall.getResponse().setStatusCode(200);

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());
        Http mockHttp = getMockHttp("GET",response);
        Executor executor = new Executor();
        executor.setHttp(mockHttp);
        executor.setBaseURL("http://www.google.com");
        replay(mockHttp);
        RestCallResult result = executor.execute(fakeCall);
        verify(mockHttp);

        assert result.getResult() == Result.PASS : "Expected test to pass " + result.toString();
    }

    @Test(dataProvider="methods", groups = {"executor"})
    public void testResultPopulationSuccessSimple(String method)
    {
        RestCall fakeCall = CallFactory.getRandomCall();
        fakeCall.setMethod(method);
        fakeCall.getResponse().setStatusCode(200);

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());
        Http mockHttp = getMockHttp(method,response);
        Executor executor = new Executor();
        executor.setHttp(mockHttp);
        executor.setBaseURL("http://www.google.com");
        replay(mockHttp);
        RestCallResult result = executor.execute(fakeCall);
        verify(mockHttp);

        assert result.getResult() == Result.PASS : "Expected test to pass " + result.toString();
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureHeadersBanned()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());

        // Make it so the response omits a header the test requires
        response.getHeaders().put(fakeCall.getResponse().getBannedHeaders().iterator().next(),"BLAH");
        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we put a header that was banned in the response");
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureDifferentBody()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());

        byte copy[] = new byte[response.getBody().length];
        for (int i=0;i<response.getBody().length; i++)
        {
            copy[i] = (byte)(255 - response.getBody()[i]);
        }
        response.setBody(copy);

        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we had the response send a shorter body");
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureNoBodyReceived()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());
        response.setBody(null);

        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we expected no body, but had one sent");
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureNoBodyExpected()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());

        ((BodyResponse)(fakeCall.getResponse())).setBody(null);
        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we expected no body, but had one sent");
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureShorterBody()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());

        byte copy[] = new byte[response.getBody().length - 1];
        System.arraycopy(response.getBody(),0,copy,0,copy.length);
        response.setBody(copy);

        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we had the response send a shorter body");
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureNoBody()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());

        response.setBody(new byte[0]);

        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we had the response send no body");
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureHeadersExpectedValue()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());

        // Make it so the response omits a header the test requires
        response.getHeaders().put(CallFactory.HEADERS_WE_WONT_USE[2],
                response.getHeaders().get(CallFactory.HEADERS_WE_WONT_USE[2]) + "BLAH"
                );

        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we changed the value of a header in the response");
    }

    @Test(groups = {"executor"})
    public void testResultPopulationFailureHeadersExpected()
    {
        RestCall fakeCall = createCallForPopulationCall();

        HttpResponse response = CallFactory.createMatchingResponse(fakeCall.getResponse());

        // Make it so the response omits a header the test requires
        response.getHeaders().remove(CallFactory.HEADERS_WE_WONT_USE[2]);
        testResultPopulation(fakeCall,response,Result.FAIL,"Expected test to fail, since we removed a header from the response");
    }

    @DataProvider(name = "methods")
    public Object[][] getMethods()
    {
        return new Object[][] {
            { "GET" },
            { "HEAD" },
            { "POST" },
            { "PUT" },
            { "DELETE" },
        };
    }

    private void testResultPopulation(RestCall fakeCall, HttpResponse response, Result res, String error)
    {
        Http mockHttp = getMockHttp("GET",response);
        Executor executor = new Executor();
        executor.setHttp(mockHttp);
        executor.setBaseURL("http://www.google.com");
        replay(mockHttp);
        RestCallResult result = executor.execute(fakeCall);
        verify(mockHttp);

        assert result.getResult() == res : error + "(" + result.toString() + ")";
    }

    private RestCall createCallForPopulationCall()
    {
        RestCall fakeCall = CallFactory.getRandomGetCall();
        fakeCall.setMethod("GET");
        fakeCall.getResponse().setStatusCode(200);
        // Make sure each has at least one value
        fakeCall.getResponse().getBannedHeaders().add(CallFactory.HEADERS_WE_WONT_USE[0]);
        fakeCall.getResponse().getRequiredHeaders().add(CallFactory.HEADERS_WE_WONT_USE[1]);
        fakeCall.getResponse().getHeaders().put(CallFactory.HEADERS_WE_WONT_USE[2],CallFactory.HEADERS_WE_WONT_USE[3]);
        return fakeCall;
    }

    /** Returns a mock http object (not in replay mode) with a non-mock, but fake, response.
     * @param method the method that we expect to get called
     * @return an HTTP mock implementation
     */
    private Http getMockHttp(String method)
    {
        HttpResponse fakeResponse = new HttpResponse();
        fakeResponse.setStatusCode(200);
        fakeResponse.setBody(null);
        return getMockHttp(method,fakeResponse);
    }

    /** Returns a mock object (not in replay mode) with the given response.
     * @param method the method that we expect to get called
     * @param fakeResponse the response that we expect this object to return from its method
     * @return an HTTP mock implementation
     */
    private Http getMockHttp(String method, HttpResponse fakeResponse)
    {
        try
        {
            HttpRequest anyRequest = anyObject();
            Http mockHttp = createMock(Http.class);
            if (method.equalsIgnoreCase("get"))
                expect(mockHttp.get(anyRequest)).andReturn(fakeResponse);
            else if (method.equalsIgnoreCase("put"))
                expect(mockHttp.put(anyRequest)).andReturn(fakeResponse);
            else if (method.equalsIgnoreCase("post"))
                expect(mockHttp.post(anyRequest)).andReturn(fakeResponse);
            else if (method.equalsIgnoreCase("delete"))
                expect(mockHttp.delete(anyRequest)).andReturn(fakeResponse);
            else if (method.equalsIgnoreCase("head"))
                expect(mockHttp.head(anyRequest)).andReturn(fakeResponse);
            else
                throw new IllegalArgumentException(method + " isn't supported");
            return mockHttp;
        }
        catch (IllegalStateException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    private void clearHeaderRequirements(RestCall test)
    {
        test.getResponse().setHeaders(new HashMap<String,String>());
        test.getResponse().setBannedHeaders(new HashSet<String>());
        test.getResponse().setRequiredHeaders(new HashSet<String>());
    }

}


text:
.class final Landroid/support/constraint/solver/Pools;
.super Ljava/lang/Object;
.source "Pools.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/support/constraint/solver/Pools$SimplePool;,
        Landroid/support/constraint/solver/Pools$Pool;
    }
.end annotation

# static fields
.field private static final DEBUG:Z

# direct methods
.method private constructor <init>()V
    .registers 1

    .prologue
    .line 75
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 77
    return-void
.end method


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Shouldly;
using SlackConnector.Connections.Sockets.Messages.Inbound;
using SlackConnector.Models;
using Xunit;

namespace SlackConnector.Tests.Unit.Models
{
    public class MessageSubTypeEnumTests
    {
        [Fact]
        public void should_have_same_number_of_enum_values_as_internal_enum_type()
        {
            // given
            int numberOfInternalEnumNames = Enum.GetNames(typeof(MessageSubType)).Length;
            int numberOfPublicEnumNames = Enum.GetNames(typeof(SlackMessageSubType)).Length;

            // then
            numberOfPublicEnumNames.ShouldBe(numberOfInternalEnumNames);
        }

        [Fact]
        public void should_have_same_message_types_as_internal_models()
        {
            // given
            var internalEnumNames = Enum.GetNames(typeof(MessageSubType))
                .Select(x => x.Replace("_", string.Empty))
                .Select(x => x.ToLower());
            var publicEnumNames = Enum.GetNames(typeof(SlackMessageSubType))
                .Select(x => x.ToLower());

            // then
            publicEnumNames.All(x => internalEnumNames.Contains(x)).ShouldBeTrue();
        }

        [Fact]
        public void should_have_same_message_type_values_as_internal_models()
        {
            // given
            var internalEnumValues = GetEnumValues<MessageSubType>();
            var publicEnumValues = GetEnumValues<SlackMessageSubType>();

            // then
            foreach (var publicEnumName in publicEnumValues.Keys)
            {
                publicEnumValues[publicEnumName].ShouldBe(internalEnumValues[publicEnumName]);
            }
        }

        private static Dictionary<string, int> GetEnumValues<T>() where T : struct, IConvertible
        {
            var internalEnumNames = Enum.GetNames(typeof(T));

            var vals = new Dictionary<string, int>();
            foreach (var enumName in internalEnumNames)
            {
                T thingy;
                Enum.TryParse(enumName, out thingy);

                var name = enumName
                    .Replace("_", string.Empty)
                    .ToLower();

                vals.Add(name, thingy.ToInt32(new NumberFormatInfo()));
            }
            return vals;
        }
    }
}


text:
Add the blog post as a markdown file in the format `2015-01-01-topic.md` in the `_posts` folder. Follow the same schema as existing files. Please paste your images used in this blog posts in the `images/blog_images` folder.

#### Adding images to a blog post

__Please notice 👆__ Imagery should be:
- preferably vector graphics (SVG)
- compressed
- small (< 3MB)

To add one or more images to a blog post takes two steps:
- define the image path(s) as `variables` in the front matter (`relative` or `absolute`)
- include the `image` template and pass the image variable

Example:
```yaml
---
layout: post
title: "Neues Design"
date: 2017-05-11
author: Felix
abstract: "Unsere Internetseite hat einen neuen Anstrich bekommen! Es gibt einen neuen Style, einen Blog, und viele kleine Änderungen"
thumbnail: /images/blog_images/screenshot_osem.png
image1: /images/blog_images/screenshot_osem.png
image2: http://localhost:4000/images/instructions_edu_bg.jpg
lang: de
---
Neuer Style
============
...

Introducing Blog
============
...

{% include image.html image=page.image1 %}

Produktpräsentation
============
...

Pressekit
============
...

{% include image.html image=page.image2 %}
```

You can also add imagery in the markdown syntax

```md
![alt image name](path-to-your-image.png)
```


text:
extern crate build;
fn main() {
    build::link("dnslib", true)
}


text:
require 'stringio'
require File.expand_path('../base', __FILE__)

class FtMiscTest < Test::Unit::TestCase
  include FunctionalBase

  def test_noisy

    result = String.new
    out = StringIO.new(result, 'w+')

    prev = $stdout
    $stdout = out

    @dashboard.noisy = true

    wfid = @dashboard.launch(Ruote.define do
      echo 'nada'
    end)

    @dashboard.wait_for(wfid)

    out.close
    $stdout = prev

    assert_not_nil result
  end

  class NoCancel
    def consume(workitem)
      # do nothing
    end
    # no cancel method implementation
  end

  def test_participant_missing_cancel_method

    pdef = Ruote.define do
      participant 'no_cancel'
    end

    @dashboard.register 'no_cancel', NoCancel

    #@dashboard.noisy = true

    wfid = @dashboard.launch(pdef)

    @dashboard.wait_for(:no_cancel)

    @dashboard.cancel(wfid)

    @dashboard.wait_for(wfid)

    assert_match(
      /undefined method `on_cancel' for/,
      @dashboard.ps(wfid).errors.first.message)
  end
end


text:
import Scroll from './Scroll';
import './Scroll.scss';

export default Scroll;


text:
<?php
/**
 * Name       : MW WP Form Field Submit Button
 * Description: 確認ボタンと送信ボタンを自動出力
 * Version    : 1.5.0
 * Author     : Takashi Kitajima
 * Author URI : http://2inc.org
 * Created    : December 14, 2012
 * Modified   : January 2, 2015
 * License    : GPLv2
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 */
class MW_WP_Form_Field_Submit_Button extends MW_WP_Form_Abstract_Form_Field {

	/**
	 * $type
	 * フォームタグの種類 input|select|button|error|other
	 * @var string
	 */
	public $type = 'button';

	/**
	 * set_names
	 * shortcode_name、display_nameを定義。各子クラスで上書きする。
	 * @return array shortcode_name, display_name
	 */
	protected function set_names() {
		return array(
			'shortcode_name' => 'mwform_submitButton',
			'display_name'   => __( 'Confirm & Submit', MWF_Config::DOMAIN ),
		);
	}

	/**
	 * set_defaults
	 * $this->defaultsを設定し返す
	 * @return array defaults
	 */
	protected function set_defaults() {
		return array(
			'name' => '',
			'confirm_value' => __( 'Confirm', MWF_Config::DOMAIN ),
			'submit_value'  => __( 'Send', MWF_Config::DOMAIN ),
		);
	}

	/**
	 * input_page
	 * 入力ページでのフォーム項目を返す
	 * @return string HTML
	 */
	protected function input_page() {
		if ( !empty( $this->atts['confirm_value'] ) ) {
			return $this->Form->submit( MWF_Config::CONFIRM_BUTTON, $this->atts['confirm_value'] );
		}
		return $this->Form->submit( $this->atts['name'], $this->atts['submit_value'] );
	}

	/**
	 * confirm_page
	 * 確認ページでのフォーム項目を返す
	 * @return string HTML
	 */
	protected function confirm_page() {
		return $this->Form->submit( $this->atts['name'], $this->atts['submit_value'] );
	}

	/**
	 * add_mwform_tag_generator
	 * フォームタグジェネレーター
	 */
	public function mwform_tag_generator_dialog( array $options = array() ) {
		?>

			name
			<?php $name = $this->get_value_for_generator( 'name', $options ); ?>
			<input type="text" name="name" value="<?php echo esc_attr( $name ); ?>" />

			<?php esc_html_e( 'String on the confirm button', MWF_Config::DOMAIN ); ?>
			<?php $confirm_value = $this->get_value_for_generator( 'confirm_value', $options ); ?>
			<input type="text" name="confirm_value" value="<?php echo esc_attr( $confirm_value ); ?>" />

			<?php esc_html_e( 'String on the submit button', MWF_Config::DOMAIN ); ?>
			<?php $submit_value = $this->get_value_for_generator( 'submit_value', $options ); ?>
			<input type="text" name="submit_value" value="<?php echo esc_attr( $submit_value ); ?>" />

		<?php
	}
}


text:
package org.jcrom.entities;

import org.jcrom.AbstractJcrEntity;
import org.jcrom.annotations.JcrProperty;

/**
 *
 * @author Olafur Gauti Gudmundsson
 * @author Nicolas Dos Santos
 */
public class Circle extends AbstractJcrEntity implements Shape {

    private static final long serialVersionUID = 1L;

    @JcrProperty
    private double radius;

    public Circle() {
    }

    public Circle(double radius) {
        super();
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI * (radius * radius);
    }

    public double getRadius() {
        return radius;
    }

}


text:
var app = angular.module("WebAppMaker", ['ngRoute']);

function setupRouting() {
  var Config = function($routeProvider) {
    $routeProvider
      .when("/", {
        templateUrl: "views/user/templates/login.view.client.html",
        controller: "LoginController",
        controllerAs: "model"
      })
      .when("/login", {
        templateUrl: "views/user/templates/login.view.client.html",
        controller: "LoginController",
        controllerAs: "model"
      })
      .when("/profile", {
        templateUrl: "views/user/templates/profile.view.client.html"
      })
      .when("/default", { templateUrl: "views/user/login.view.client.html"})
      .when("/register", {
        templateUrl: "views/user/templates/register.view.client.html",
        controller: "RegisterController",
        controllerAs: "model",
      })
      .when("/profile/:uid", {
        templateUrl: "views/user/templates/profile.view.client.html",
        controller: "ProfileController",
        controllerAs: "model"
      })
      .when("/profile/:uid/website", {
        templateUrl: "views/website/templates/website-list.view.client.html",
        controller: "WebsiteListController",
        controllerAs: "model"
      })
      .when("/profile/:uid/website/new", {
        templateUrl: "views/website/templates/website-new.view.client.html",
        controller: "WebsiteNewController",
        controllerAs: "model"
      })
      .when("/profile/:uid/website/:wid", {
        templateUrl: "views/website/templates/website-edit.view.client.html",
        controller: "WebsiteEditController",
        controllerAs: "model"
      })
      .when("/profile/:uid/website/:wid/page", {
        templateUrl: "views/page/templates/page-list.view.client.html",
        controller: "PageController",
        controllerAs: "model",
      })
      .when("/profile/:uid/website/:wid/page/new", {
        templateUrl: "views/page/templates/page-new.view.client.html",
        controller: "PageController",
        controllerAs: "model",
      })
      .when("/profile/:uid/website/:wid/page/:pid", {
        templateUrl: "views/page/templates/page-edit.view.client.html",
        controller: "PageController",
        controllerAs: "model",
      })
      .when("/profile/:uid/website/:wid/page/:pid/widget", {
        templateUrl: "views/widget/templates/widget-list.view.client.html",
        controller: "WidgetController",
        controllerAs: "model"
      })
      .when("/profile/:uid/website/:wid/page/:pid/widget/new", {
        templateUrl: "views/widget/templates/widget-chooser.view.client.html",
        controller: "WidgetController",
        controllerAs: "model"
      })
      .when("/profile/:uid/website/:wid/page/:pid/widget/:wgid", {
        templateUrl: "views/widget/templates/widget-edit.view.client.html",
        controller: "WidgetController",
        controllerAs: "model"
      }).otherwise({redirectTo: "/login"});
  };

  app.config(Config);
}

// annonimous function will be called only after all the resources are loaded
(function(){
  setupRouting();
  app.factory("UserService", UserService);
  app.factory("WebsiteService", WebsiteService);
  app.factory("PageService", PageService);
  app.factory("WidgetService", WidgetService);
  app.controller("LoginController", LoginController);
  app.controller("RegisterController", RegisterController);
  app.controller("ProfileController", ProfileController);
  app.controller("WebsiteListController", WebsiteListController);
  app.controller("WebsiteEditController", WebsiteEditController);
  app.controller("WebsiteNewController", WebsiteNewController);
  app.controller("PageController", PageController);
  app.controller("WidgetController", WidgetController);
})();


text:
import axios from 'axios';

export default {
  state: {
    posts: [],
  },
  mutations: {
    POSTS_UPDATE: (state, posts) => { state.posts = posts },
    POSTS_UPDATE_ONE: (state, newPost) => {
      /* eslint no-confusing-arrow: 0 */
      state.posts = state.posts.map(post => newPost._id === post._id ? newPost : post);
    },
    POSTS_DELETE: (state, id) => { state.posts = state.posts.filter(post => post._id !== id); },
  },
  actions: {
    GETPOSTS: async ({ commit }) => {
      const res = await axios.get('/api/posts/meta');
      commit('POSTS_UPDATE', res.data);
    },
    POSTS_PUBLISH: async ({ commit }, id) => {
      const res = await axios.get(`/api/publish/${id}`);
      commit('POSTS_UPDATE_ONE', res.data);
    },
    POSTS_DELETE_ONE: async ({ commit }, id) => {
      const res = await axios.delete(`/api/post/${id}`);
      commit('POSTS_DELETE', id);
      return res;
    },
  },
}


text:
define(function(require) {
    'use strict';

    const _ = require('underscore');

    return {
        extractPureEmailAddress: function(fullEmailAddress) {
            let atPos;
            const words = fullEmailAddress.split(' ').reverse();
            const rawEmail = _.find(words, function(word) {
                atPos = word.lastIndexOf('@');
                return atPos !== -1;
            });

            if (!rawEmail) {
                return fullEmailAddress;
            }

            const startPos = rawEmail.lastIndexOf('<', atPos);
            if (startPos === -1) {
                return rawEmail;
            }

            const endPos = rawEmail.indexOf('>', atPos);
            if (endPos === -1) {
                return rawEmail;
            }

            return rawEmail.substring(startPos + 1, endPos);
        }
    };
});


text:
Android Repository
==================

This repository contains complete code for Android blog posts on [hmkcode.com](http://hmkcode.com)


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="index,follow" />
<meta name="keywords" content="midknights,rpg,game" />
<meta name="author" content="Juan Manuel Serrano" />
<meta name="publisher" content="Juan Manuel Serrano" />
<meta name="copyright" content="Juan Manuel Serrano, 2017" />
<meta name="language" content="en_EN" />
<meta name="description" content="A web based rpg." />
<title>Midknights II</title>
<link href="/css/main.css" rel="stylesheet" type="text/css"></link>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.png" />
<link rel="icon" type="image/x-icon" href="/favicon.png" />

Midknights II

			Home • Register

		This is a home page. Here go news, the ranking, and the login form.

	By Mantis Shrimp • Repository


text:
package com.matthewmitchell.peercoinj.core;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.Test;

import com.matthewmitchell.peercoinj.params.MainNetParams;

public class DumpedPrivateKeyTest {
    @Test
    public void testJavaSerialization() throws Exception {

        DumpedPrivateKey key = new DumpedPrivateKey(MainNetParams.get(), new ECKey().getPrivKeyBytes(), true);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        new ObjectOutputStream(os).writeObject(key);
        DumpedPrivateKey keyCopy = (DumpedPrivateKey) new ObjectInputStream(new ByteArrayInputStream(os.toByteArray()))
                .readObject();
        assertEquals(key, keyCopy);
    }
}


text:
package com.github.liaochong.ratel.tools.excel;

/**
 * @author liaochong
 * @Type TD
 * @Desc
 * @Date 2017/8/11
 * @Version V1.0
 */
public class TD {

    private int rowspan = 1;

    private int colspan = 1;

    private int x;

    private int y;

    private String content;

    private Short bgColor;

    public int getRowspan() {
        return rowspan;
    }

    public void setRowspan(int rowspan) {
        this.rowspan = rowspan;
    }

    public int getColspan() {
        return colspan;
    }

    public void setColspan(int colspan) {
        this.colspan = colspan;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Short getBgColor() {
        return bgColor;
    }

    public void setBgColor(Short bgColor) {
        this.bgColor = bgColor;
    }
}


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var core_1 = require('@angular/core');
var validation_summary_1 = require('devextreme/ui/validation_summary');
var component_1 = require('../core/component');
var template_host_1 = require('../core/template-host');
var template_1 = require('../core/template');
var nested_option_1 = require('../core/nested-option');
var watcher_helper_1 = require('../core/watcher-helper');
var iterable_differ_helper_1 = require('../core/iterable-differ-helper');
var item_dxi_1 = require('./nested/item-dxi');
var item_dxi_2 = require('./nested/item-dxi');
var DxValidationSummaryComponent = (function (_super) {
    __extends(DxValidationSummaryComponent, _super);
    function DxValidationSummaryComponent(elementRef, ngZone, templateHost, _watcherHelper, _idh, optionHost) {
        _super.call(this, elementRef, ngZone, templateHost, _watcherHelper);
        this._watcherHelper = _watcherHelper;
        this._idh = _idh;
        this._createEventEmitters([
            { subscribe: 'disposing', emit: 'onDisposing' },
            { subscribe: 'initialized', emit: 'onInitialized' },
            { subscribe: 'optionChanged', emit: 'onOptionChanged' },
            { subscribe: 'contentReady', emit: 'onContentReady' },
            { subscribe: 'itemClick', emit: 'onItemClick' },
            { emit: 'elementAttrChange' },
            { emit: 'hoverStateEnabledChange' },
            { emit: 'itemTemplateChange' },
            { emit: 'itemsChange' },
            { emit: 'validationGroupChange' }
        ]);
        this._idh.setHost(this);
        optionHost.setHost(this);
    }
    Object.defineProperty(DxValidationSummaryComponent.prototype, "elementAttr", {
        get: function () {
            return this._getOption('elementAttr');
        },
        set: function (value) {
            this._setOption('elementAttr', value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DxValidationSummaryComponent.prototype, "hoverStateEnabled", {
        get: function () {
            return this._getOption('hoverStateEnabled');
        },
        set: function (value) {
            this._setOption('hoverStateEnabled', value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DxValidationSummaryComponent.prototype, "itemTemplate", {
        get: function () {
            return this._getOption('itemTemplate');
        },
        set: function (value) {
            this._setOption('itemTemplate', value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DxValidationSummaryComponent.prototype, "items", {
        get: function () {
            return this._getOption('items');
        },
        set: function (value) {
            this._setOption('items', value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DxValidationSummaryComponent.prototype, "validationGroup", {
        get: function () {
            return this._getOption('validationGroup');
        },
        set: function (value) {
            this._setOption('validationGroup', value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DxValidationSummaryComponent.prototype, "itemsChildren", {
        get: function () {
            return this._getOption('items');
        },
        set: function (value) {
            this.setChildren('items', value);
        },
        enumerable: true,
        configurable: true
    });
    DxValidationSummaryComponent.prototype._createInstance = function (element, options) {
        return new validation_summary_1.default(element, options);
    };
    DxValidationSummaryComponent.prototype.ngOnDestroy = function () {
        this._destroyWidget();
    };
    DxValidationSummaryComponent.prototype.ngOnChanges = function (changes) {
        this._idh.setup('items', changes);
    };
    DxValidationSummaryComponent.prototype.ngDoCheck = function () {
        this._idh.doCheck('items');
        this._watcherHelper.checkWatchers();
    };
    DxValidationSummaryComponent.prototype.ngAfterViewInit = function () {
        this._createWidget(this.element.nativeElement);
    };
    DxValidationSummaryComponent.decorators = [
        { type: core_1.Component, args: [{
                    selector: 'dx-validation-summary',
                    template: '',
                    providers: [
                        template_host_1.DxTemplateHost,
                        watcher_helper_1.WatcherHelper,
                        nested_option_1.NestedOptionHost,
                        iterable_differ_helper_1.IterableDifferHelper
                    ]
                },] },
    ];
    DxValidationSummaryComponent.ctorParameters = function () { return [
        { type: core_1.ElementRef, },
        { type: core_1.NgZone, },
        { type: template_host_1.DxTemplateHost, },
        { type: watcher_helper_1.WatcherHelper, },
        { type: iterable_differ_helper_1.IterableDifferHelper, },
        { type: nested_option_1.NestedOptionHost, },
    ]; };
    DxValidationSummaryComponent.propDecorators = {
        'elementAttr': [{ type: core_1.Input },],
        'hoverStateEnabled': [{ type: core_1.Input },],
        'itemTemplate': [{ type: core_1.Input },],
        'items': [{ type: core_1.Input },],
        'validationGroup': [{ type: core_1.Input },],
        'onDisposing': [{ type: core_1.Output },],
        'onInitialized': [{ type: core_1.Output },],
        'onOptionChanged': [{ type: core_1.Output },],
        'onContentReady': [{ type: core_1.Output },],
        'onItemClick': [{ type: core_1.Output },],
        'elementAttrChange': [{ type: core_1.Output },],
        'hoverStateEnabledChange': [{ type: core_1.Output },],
        'itemTemplateChange': [{ type: core_1.Output },],
        'itemsChange': [{ type: core_1.Output },],
        'validationGroupChange': [{ type: core_1.Output },],
        'itemsChildren': [{ type: core_1.ContentChildren, args: [item_dxi_2.DxiItemComponent,] },],
    };
    return DxValidationSummaryComponent;
}(component_1.DxComponent));
exports.DxValidationSummaryComponent = DxValidationSummaryComponent;
var DxValidationSummaryModule = (function () {
    function DxValidationSummaryModule() {
    }
    DxValidationSummaryModule.decorators = [
        { type: core_1.NgModule, args: [{
                    imports: [
                        item_dxi_1.DxiItemModule,
                        template_1.DxTemplateModule
                    ],
                    declarations: [
                        DxValidationSummaryComponent
                    ],
                    exports: [
                        DxValidationSummaryComponent,
                        item_dxi_1.DxiItemModule,
                        template_1.DxTemplateModule
                    ],
                },] },
    ];
    DxValidationSummaryModule.ctorParameters = function () { return []; };
    return DxValidationSummaryModule;
}());
exports.DxValidationSummaryModule = DxValidationSummaryModule;
//# sourceMappingURL=validation-summary.js.map