text:
import React from 'react';
import { connect } from 'react-redux';
import {
  every,
  filter,
  get,
  includes,
  isEmpty,
  isEqual,
  mapValues,
  omitBy,
  orderBy,
  replace,
  some,
  startCase,
  toLower,
  values,
} from 'lodash';
import {
  compose,
  setDisplayName,
  withHandlers,
  withProps,
  withPropsOnChange,
  withState,
} from 'recompose';
import SearchIcon from 'react-icons/lib/fa/search';

import {
  addAllFacets,
  changeExpandedStatus,
  expandOneCategory,
  showingMoreByCategory,
  IExpandedStatusStateProps,
  IExpandedStatusActionProps,
} from '@ncigdc/dux/facetsExpandedStatus';

import { withTheme } from '@ncigdc/theme';
import withFacetSelection from '@ncigdc/utils/withFacetSelection';
import FacetHeader from '@ncigdc/components/Aggregations/FacetHeader';
import styled from '@ncigdc/theme/styled';
import termCapitaliser from '@ncigdc/utils/customisation';
import tryParseJSON from '@ncigdc/utils/tryParseJSON';
import {
  clinicalFacets,
  customSorting,
  presetFacets,
} from '@ncigdc/containers/explore/presetFacets';

import { Column, Row } from '@ncigdc/uikit/Flex';
import { WrapperComponent } from '@ncigdc/components/FacetWrapper';
import { internalHighlight } from '@ncigdc/uikit/Highlight';
import Input from '@ncigdc/uikit/Form/Input';
import AngleIcon from '@ncigdc/theme/icons/AngleIcon';
import {
  ToggleMoreLink,
  BottomRow,
} from '@ncigdc/components/Aggregations/TermAggregation';

import { ITheme } from '@ncigdc/theme/types';
import { IGroupFilter } from '@ncigdc/utils/filters/types';

export interface IFacetProps {
  customSort: number,
  description: string,
  doc_type: string,
  field: string,
  full: string,
  type: string,
  additionalProps?: any,
}

interface IBucketProps {
  key: string,
  doc_count: number,
}

interface IAggregationProps {
  buckets?: IBucketProps[],
  count?: number,
  stats?: { count: number, [x: string]: number },
}

interface IParsedFacetsProps {
  [x: string]: IAggregationProps,
}

export interface IFilteredFacetsProps {
  [x: string]: IFacetProps[],
}

interface INotificationProps {
  components: string[],
  level: string,
  id: string,
  dismissible: boolean,
  message: JSX.Element,
  dismissed?: boolean,
}

interface IClinicalProps {
  allExpanded: { [x: string]: boolean },
  clinicalCollapsed: boolean,
  dispatch: (action: IExpandedStatusActionProps) => void,
  facetsExpandedStatus: IExpandedStatusStateProps,
  filteredFacets: IFilteredFacetsProps,
  globalFilters: IGroupFilter,
  handleQueryInputChange: () => void,
  handleQueryInputClear: () => void,
  isLoadingParsedFacets: boolean,
  maxFacetsPanelHeight: number,
  notifications: INotificationProps[],
  parsedFacets: IParsedFacetsProps | {},
  searchValue: string,

  setClinicalCollapsed: (clinicalCollapsed: boolean) => void,
  setSearchValue: (searchValue: string) => void,
  setUselessFacetVisibility: (uselessFacetVisibility: boolean) => void,
  shouldHideUselessFacets: boolean,
  theme: ITheme,
}

interface IFieldProps {
  __dataID: string,
  customSort: number,
  description: string,
  name: string,
  type: { name: string, __dataID: string },
}

interface IClinicalViewer {
  explore: {
    cases: {
      customCaseFacets: string
    }
  }
}

interface IClinicalQueryProps extends IClinicalProps {
  clinicalAnalysisFields: [IFieldProps],
  variables: {
    viewer: IClinicalViewer
  },
  viewer: IClinicalViewer
}

interface IParsedClinicalAggs extends IClinicalQueryProps {
  facetMapping: IFacetProps,
  facetExclusionTest: (facet: IFacetProps) => IFacetProps
}

const headersHeight = 44;

const facetMatchesQuery = (
  facet: IFacetProps,
  elements: IBucketProps[],
  searchValue: string,
): boolean => {
  return some(
    [
      replace(facet.field.split('.').pop() || '', /_/g, ' '),
      ...(elements || []).map((e: IBucketProps) => e.key),
      facet.description,
    ]
      .filter((n: string) => n)
      .map(toLower),
    searchTarget => includes(
      searchTarget.toLocaleLowerCase(),
      searchValue.toLocaleLowerCase(),
    ),
  );
};

const MagnifyingGlass = styled(SearchIcon, {
  backgroundColor: ({ theme }: { theme: ITheme }) => theme.greyScale5,
  border: ({ theme }: { theme: ITheme }) => `1px solid ${theme.greyScale4}`,
  borderRadius: '4px 0 0 4px',
  borderRight: 'none',
  color: ({ theme }: { theme: ITheme }) => theme.greyScale2,
  height: '3.4rem',
  padding: '0.8rem',
  width: '3.4rem',
});

const enhance = compose<IClinicalProps, IClinicalProps>(
  setDisplayName('EnhancedClinicalAggregations_Modern'),
  withTheme,
  connect(
    ({
      bannerNotification,
      facetsExpandedStatus,
    }: {
      facetsExpandedStatus: IExpandedStatusStateProps,
      bannerNotification: INotificationProps[],
    }) => ({
      allExpanded: mapValues(facetsExpandedStatus, status => some(values(status.facets))),
      facetsExpandedStatus,
      notifications: bannerNotification,
    }),
  ),
  withState('clinicalCollapsed', 'setClinicalCollapsed', false),
  withState('isLoadingParsedFacets', 'setIsLoadingParsedFacets', false),
  withState('shouldHideUselessFacets', 'setShouldHideUselessFacets', true),
  withState('searchValue', 'setSearchValue', ''),
  withFacetSelection({
    entityType: 'ExploreCases',
    presetFacetFields: presetFacets.map(x => x.field),
    validFacetDocTypes: ['cases'],
    validFacetPrefixes: [
      'cases.demographic',
      'cases.diagnoses',
      'cases.diagnoses.treatments',
      'cases.exposures',
      'cases.follow_up',
      'cases.molecular_tests',
    ],
  }),
  withPropsOnChange(
    (props: IClinicalQueryProps, nextProps: IClinicalQueryProps) => !isEqual(props.globalFilters, nextProps.globalFilters),
    ({ clinicalAnalysisFields }) => ({
      facetMapping: clinicalAnalysisFields.reduce((
        acc: { [x: string]: IFacetProps } | {},
        {
          description,
          name,
          type,
        }: IFieldProps,
      ) => {
        const dottedName = name.replace(/__/g, '.');
        return ({
          ...acc,
          [`cases.${dottedName}`]: {
            additionalProps: { convertDays: name.includes('age_at_diagnosis') },
            customSort: customSorting(dottedName),
            description,
            doc_type: 'cases',
            field: dottedName,
            full: `cases.${dottedName}`,
            type: type.name === 'Aggregations' ? 'keyword' : 'long',
          },
        });
      }, {}),
    }),
  ),
  withProps(
    ({
      setShouldHideUselessFacets,
    }) => ({
      setUselessFacetVisibility: (shouldHide: boolean) => {
        setShouldHideUselessFacets(shouldHide);
        localStorage.setItem(
          'shouldHideUselessFacets',
          JSON.stringify(shouldHide),
        );
      },
    }),
  ),
  withPropsOnChange(
    (props: IParsedClinicalAggs, nextProps: IParsedClinicalAggs) => !(
      isEqual(props.facetMapping, nextProps.facetMapping) &&
      isEqual(props.viewer.explore.cases.customCaseFacets, nextProps.viewer.explore.cases.customCaseFacets) &&
      props.shouldHideUselessFacets === nextProps.shouldHideUselessFacets &&
      props.searchValue === nextProps.searchValue
    ),
    ({
      dispatch,
      facetExclusionTest,
      facetMapping,
      searchValue,
      shouldHideUselessFacets,
      viewer: { explore: { cases: { customCaseFacets } } },
    }) => {
      const parsedFacets: IParsedFacetsProps | {} = isEmpty(customCaseFacets)
        ? {}
        : tryParseJSON(customCaseFacets, {});

      const usefulFacets = omitBy(
        parsedFacets,
        (aggregation: IAggregationProps) => some([
          !aggregation,
          aggregation.buckets &&
          aggregation.buckets.filter(
            (bucket: IBucketProps) => bucket.key !== '_missing',
          ).length === 0,
          aggregation.count === 0,
          aggregation.count === null,
          aggregation.stats && aggregation.stats.count === 0,
        ]),
      );

      const filteredFacets = clinicalFacets.reduce((acc, header) => {
        return {
          ...acc,
          [header.field]: filter(facetMapping, facet => {
            return every([
              facetMatchesQuery(
                facet,
                filter(
                  get(parsedFacets[facet.field], 'buckets', undefined),
                  obj => obj.key !== '_missing',
                ),
                searchValue,
              ),
              !facetExclusionTest(facet),
              !shouldHideUselessFacets ||
              Object.prototype.hasOwnProperty.call(usefulFacets, facet.field),
              !header.excluded || facet.full.startsWith(header.full),
              !some(
                header.excluded.map((regex: RegExp) => regex.test(facet.full)),
              ),
            ]);
          }),
        };
      }, {});
      dispatch(addAllFacets(filteredFacets));
      return {
        filteredFacets,
        parsedFacets,
      };
    },
  ),
  withHandlers({
    handleQueryInputChange:
      ({ setSearchValue }) => (event: any) => setSearchValue(event.target.value),
    handleQueryInputClear:
      ({ setSearchValue }) => () => setSearchValue(''),
  }),
);

const ClinicalAggregations = ({
  allExpanded,
  clinicalCollapsed,
  dispatch,
  facetsExpandedStatus,
  filteredFacets,
  handleQueryInputChange,
  handleQueryInputClear,
  isLoadingParsedFacets,
  maxFacetsPanelHeight,
  parsedFacets,
  searchValue,
  setClinicalCollapsed,
  setUselessFacetVisibility,
  shouldHideUselessFacets,
  theme,
}: IClinicalProps) => (
  <React.Fragment>
    <FacetHeader
      collapsed={clinicalCollapsed}
      setCollapsed={setClinicalCollapsed}
      title="Search Clinical Data"
      />
    {clinicalCollapsed || (
      <Row
        key="row"
        style={{
          margin: '0 1.2rem',
        }}
        >
        <MagnifyingGlass />
        <Input
          aria-label="Search..."
          autoFocus
          defaultValue={searchValue}
          handleClear={handleQueryInputClear}
          onChange={handleQueryInputChange}
          placeholder="Search..."
          style={{
            borderRadius: '0 4px 4px 0',
            marginBottom: '6px',
          }}
          value={searchValue}
          />
      </Row>
    )}
    <label htmlFor="clinical-agg-search" key="label">
      <input
        checked={shouldHideUselessFacets}
        className="test-filter-useful-facet"
        id="clinical-agg-search"
        onChange={event => setUselessFacetVisibility(event.target.checked)}
        style={{ margin: '12px' }}
        type="checkbox"
        />
      {`Only show fields with values (${
          isLoadingParsedFacets
            ? '...'
            : values(filteredFacets).reduce(
              (acc: number, facet: IFacetProps[]) => acc + facet.length,
              0,
            )
        } fields shown)`}
    </label>
    <div
      className="cohortBuilder"
      key="1"
      style={{
        maxHeight: `${maxFacetsPanelHeight - headersHeight}px`,
        overflowY: 'scroll',
        paddingBottom: '20px',
      }}
      >
      {clinicalFacets
        .filter(
          facet => !searchValue || filteredFacets[facet.field].length > 0,
            // If the user is searching for something, hide the presetFacet with no value.
        )
        .map(facet => {
          return (
            <div key={`${facet.title}div`}>
              <Row
                style={{
                  alignItems: 'center',
                  background: '#eeeeee',
                  cursor: 'pointer',
                  justifyContent: 'space-between',
                  margin: '0.5rem 1rem 0rem 0rem',
                  padding: '1rem 1.2rem 0.5rem 1.2rem',
                  position: 'sticky',
                  top: 0,
                  zIndex: 10,
                }}
                >
                <div
                  onClick={() => dispatch(changeExpandedStatus(facet.field, ''))}
                  style={{
                    color: theme.primary,
                    fontSize: '1.7rem',
                  }}
                  >
                  <AngleIcon
                    style={{
                      display: 'flex',
                      padding: '0.25rem 0.25rem 0.25rem 0rem',
                      float: 'left',
                      transform: `rotate(${
                          facetsExpandedStatus[facet.field].expanded
                            ? 0
                            : 270}deg)`,
                    }}
                    />
                  {facet.title}
                </div>
                {facetsExpandedStatus[facet.field].expanded && (
                  <span
                    onClick={() => {
                      dispatch(
                        expandOneCategory(
                          facet.field,
                          !allExpanded[facet.field],
                        ),
                      );
                    }}
                    style={{
                      display: 'flex',
                      float: 'right',
                      fontSize: '12px',
                    }}
                    >
                    {(searchValue || filteredFacets[facet.field].length === 0) ||
                        allExpanded[facet.field]
                          ? 'Collapse All'
                          : 'Expand All'}
                  </span>
                )}
              </Row>
              {facetsExpandedStatus[facet.field].expanded && (
                <Column>
                  {filteredFacets[facet.field].length > 0
                      ? (
                        orderBy(
                          filteredFacets[facet.field],
                          ['customSort', 'field'],
                        )
                          .slice(
                            0,
                            facetsExpandedStatus[facet.field].showingMore
                              ? Infinity
                              : 5,
                          )
                          .map((componentFacet: IFacetProps) => {
                            const fieldName = componentFacet.full.split('.').pop() || '';
                            return [
                              <WrapperComponent
                                additionalProps={{
                                  ...componentFacet.additionalProps,
                                  style: { paddingBottom: 0 },
                                }}
                                aggregation={parsedFacets[componentFacet.field]}
                                allExpanded={allExpanded[facet.field]}
                                category={facet.field}
                                collapsed={
                                  searchValue.length === 0
                                    ? !facetsExpandedStatus[facet.field].facets[
                                      fieldName
                                    ]
                                    : false
                                }
                                countLabel="Cases"
                                DescriptionComponent={(
                                  <div
                                    key={componentFacet.description}
                                    style={{
                                      fontStyle: 'italic',
                                      paddingLeft: '30px',
                                      paddingRight: '10px',
                                      width: '320px',
                                    }}
                                    >
                                    {internalHighlight(
                                      searchValue,
                                      componentFacet.description,
                                      {
                                        backgroundColor: '#FFFF00',
                                      },
                                    )}
                                  </div>
                                )}
                                facet={componentFacet}
                                headerStyle={{
                                  fontSize: '16px',
                                  padding: '1.2rem',
                                }}
                                isMatchingSearchValue={(componentFacet.full +
                                  componentFacet.description
                                )
                                  .toLocaleLowerCase()
                                  .includes(searchValue.toLocaleLowerCase())}
                                key={componentFacet.full}
                                relayVarName="exploreCaseCustomFacetFields"
                                searchValue={searchValue}
                                setCollapsed={() => dispatch(
                                  changeExpandedStatus(
                                    facet.field,
                                    fieldName,
                                  ),
                                )}
                                style={{ paddingLeft: '10px' }}
                                title={startCase(
                                  termCapitaliser(fieldName),
                                )}
                                />,
                            ];
                          }))
                      : (
                        <article
                          style={{
                            fontSize: '1.5rem',
                            padding: '2rem 3rem',
                          }}
                          >
                          No data is available for this clinical category.
                        </article>
                      )}

                  {filteredFacets[facet.field].length > 5 && (
                    <BottomRow style={{ marginRight: '1rem' }}>
                      <ToggleMoreLink
                        onClick={() => dispatch(showingMoreByCategory(facet.field))}
                        >
                        {facetsExpandedStatus[facet.field].showingMore
                            ? 'Less...'
                            : filteredFacets[facet.field].length - 5 &&
                            `${filteredFacets[facet.field].length -
                            5} More...`}
                      </ToggleMoreLink>
                    </BottomRow>
                  )}
                </Column>
              )}
            </div>
          );
        })}
    </div>
  </React.Fragment>
);

export default enhance(ClinicalAggregations);


text:
package corewar.shared;

public final class HexIntConverter {

	private HexIntConverter() {
	}

	public static int hexToInt(String hex) {
		return hexToIntImpl(hex.startsWith(Constants.HEX_PREFIX) ? hex.substring(2) : hex);
	}

	public static String intToHex(int value, int nbNibbles) {
		return intToHexImpl(value, nbNibbles, false);
	}

	public static String intToHexWithPrefix(int value, int nbNibbles) {
		return intToHexImpl(value, nbNibbles, true);
	}

	public static String intToLittleEndianHex(int value, int nbNibbles) {
		return new StringBuilder(intToHexImpl(value, nbNibbles, false)).reverse().toString();
	}

	private static int hexToIntImpl(String hex) {
		int res = 0;
		byte[] bytes = hex.toLowerCase().getBytes();
		int i = 0;
		for (; i < bytes.length; i++) {
			res |= Utilities.charToByte((char) bytes[bytes.length - i - 1]) << (4 * i);
		}

		int shift = 8 - i;
		if (shift > 0) {
			res <<= shift * 4;
			// Using arithmetic shift to retrieve the correct sign.
			res >>= shift * 4;
		}

		return res;
	}

	private static String intToHexImpl(int value, int nbNibbles, boolean withPrefix) {
		StringBuilder stringBuilder = new StringBuilder(withPrefix ? Constants.HEX_PREFIX : "");
		String hexString = Integer.toHexString(value);
		int hexLength = hexString.length();
		if (hexLength < nbNibbles) {
			for (int i = 0; i < nbNibbles - hexLength; i++) {
				stringBuilder.append("0");
			}
		} else if (hexLength > nbNibbles) {
			hexString = hexString.substring(hexLength - nbNibbles, hexLength);
		}
		stringBuilder.append(hexString);
		return stringBuilder.toString();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.osgi.test.cases.networkadapter.util;

import java.util.LinkedList;
import java.util.List;

import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;

public class TestServiceListener implements ServiceListener {

	private List<ServiceReference< ? >>	list	= new LinkedList<>();
    private int type;

    public TestServiceListener(int type) {
        this.type = type;
    }

    @Override
	public void serviceChanged(ServiceEvent event) {
        if (event.getType() == type) {
			ServiceReference< ? > ref = event.getServiceReference();
            list.add(ref);

            System.out.println("Callback: " + ref);
        }
    }

    public int size() {
        return list.size();
    }

    public void clear() {
        list.clear();
    }

	public ServiceReference< ? > get(int index) {
        return list.get(index);
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class NatRuleCondition : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(IpProtocols))
            {
                writer.WritePropertyName("ipProtocols");
                writer.WriteStartArray();
                foreach (var item in IpProtocols)
                {
                    writer.WriteStringValue(item.ToString());
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(SourceAddresses))
            {
                writer.WritePropertyName("sourceAddresses");
                writer.WriteStartArray();
                foreach (var item in SourceAddresses)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(DestinationAddresses))
            {
                writer.WritePropertyName("destinationAddresses");
                writer.WriteStartArray();
                foreach (var item in DestinationAddresses)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(DestinationPorts))
            {
                writer.WritePropertyName("destinationPorts");
                writer.WriteStartArray();
                foreach (var item in DestinationPorts)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(SourceIpGroups))
            {
                writer.WritePropertyName("sourceIpGroups");
                writer.WriteStartArray();
                foreach (var item in SourceIpGroups)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(TerminateTLS))
            {
                writer.WritePropertyName("terminateTLS");
                writer.WriteBooleanValue(TerminateTLS.Value);
            }
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            if (Optional.IsDefined(Description))
            {
                writer.WritePropertyName("description");
                writer.WriteStringValue(Description);
            }
            writer.WritePropertyName("ruleConditionType");
            writer.WriteStringValue(RuleConditionType.ToString());
            writer.WriteEndObject();
        }

        internal static NatRuleCondition DeserializeNatRuleCondition(JsonElement element)
        {
            Optional<IList<FirewallPolicyRuleConditionNetworkProtocol>> ipProtocols = default;
            Optional<IList<string>> sourceAddresses = default;
            Optional<IList<string>> destinationAddresses = default;
            Optional<IList<string>> destinationPorts = default;
            Optional<IList<string>> sourceIpGroups = default;
            Optional<bool> terminateTLS = default;
            Optional<string> name = default;
            Optional<string> description = default;
            FirewallPolicyRuleConditionType ruleConditionType = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("ipProtocols"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<FirewallPolicyRuleConditionNetworkProtocol> array = new List<FirewallPolicyRuleConditionNetworkProtocol>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(new FirewallPolicyRuleConditionNetworkProtocol(item.GetString()));
                    }
                    ipProtocols = array;
                    continue;
                }
                if (property.NameEquals("sourceAddresses"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    sourceAddresses = array;
                    continue;
                }
                if (property.NameEquals("destinationAddresses"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    destinationAddresses = array;
                    continue;
                }
                if (property.NameEquals("destinationPorts"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    destinationPorts = array;
                    continue;
                }
                if (property.NameEquals("sourceIpGroups"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    sourceIpGroups = array;
                    continue;
                }
                if (property.NameEquals("terminateTLS"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    terminateTLS = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("description"))
                {
                    description = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("ruleConditionType"))
                {
                    ruleConditionType = new FirewallPolicyRuleConditionType(property.Value.GetString());
                    continue;
                }
            }
            return new NatRuleCondition(name.Value, description.Value, ruleConditionType, Optional.ToList(ipProtocols), Optional.ToList(sourceAddresses), Optional.ToList(destinationAddresses), Optional.ToList(destinationPorts), Optional.ToList(sourceIpGroups), Optional.ToNullable(terminateTLS));
        }
    }
}


text:
<map>
  <entry>
    <string>plugin_identifier</string>
    <string>org.lockss.plugin.definable.LargeTestPlugin</string>
  </entry>
  <entry>
    <string>au_def_pause_time</string>
    <long>30000</long>
  </entry>
  <entry>
    <string>plugin_version</string>
    <string>7</string>
  </entry>
  <entry>
    <string>au_name</string>
    <string>"Large Plugin AU, Base URL %s, Resolver URL %s, Journal Code %s, Year %d, Issues %s, Range %s", base_url, resolver_url, journal_code, year, issue_set, num_issue_range</string>
  </entry>
  <entry>
    <string>au_redirect_to_login_url_pattern</string>
    <string>"%sdenial/denial\.cfm", base_url</string>
  </entry>
  <entry>
    <string>plugin_name</string>
    <string>Large Test Plugin</string>
  </entry>
  <entry>
    <string>au_def_new_content_crawl</string>
    <long>1209600000</long>
  </entry>
  <entry>
    <string>plugin_notes</string>
    <string>Make it a C-note, miss, and I'll take the case.</string>
  </entry>
<!--   <entry> -->
<!--     <string>text/html_filter_factory</string> -->
<!--     <string>org.lockss.plugin.definable.MissingHtmlFilterFactory</string> -->
<!--   </entry> -->
  <entry>
    <string>au_refetch_depth</string>
    <int>3</int>
  </entry>
  <entry>
    <string>au_crawlrules</string>
    <list>
      <string>4,"^(%s|%s)", base_url, resolver_url</string>
      <string>1,"^%spublishing/journals/lockss/\?journalcode=%s&year=%d", base_url, journal_code, year</string>
      <string>1,"^%s\?DOI=", resolver_url</string>
      <string>2,"^%serrorpage\.asp", base_url</string>
      <string>2,"^%shost/%s", base_url,base_url_host</string>
      <string>1,"^%spublishing/journals/%s/article\.asp\?Type=Issue&VolumeYear=%d&JournalCode=%s", base_url, journal_code, year, journal_code</string>
      <string>1,"^%s.*\.(bmp|css|ico|gif|jpe?g|js|mol|png|tif?f)$", base_url</string>
      <string>1,"%sissueset/issue-%s/.*", base_url, issue_set</string>
      <string>1,"%sissuerange/issue-%s/.*", base_url, num_issue_range</string>
    </list>
  </entry>
  <entry>
    <string>au_start_url</string>
    <list>
     <string>"%spublishing/journals/lockss/?journalcode=%s&year=%d", base_url, journal_code, year</string>
     <string>"%sissuestart/issue-%s/", base_url, issue_set</string>
    </list>
  </entry>
  <entry>
    <string>plugin_config_props</string>
    <list>
      <org.lockss.daemon.ConfigParamDescr>
        <key>resolver_url</key>
        <displayName>Resolver Url</displayName>
        <description>Resolver for xlink.rsc.org</description>
        <type>3</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>journal_code</key>
        <displayName>Journal Code</displayName>
        <description>The journal's short journal code</description>
        <type>1</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>base_url</key>
        <displayName>Base URL</displayName>
        <description>Usually of the form http://<journal-name>.com/</description>
        <type>3</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>year</key>
        <displayName>Year</displayName>
        <description></description>
        <type>2</type>
        <size>4</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>issue_set</key>
        <displayName>Issue Set</displayName>
        <description>A comma delimited list of issues. (eg issue1, issue2)</description>
        <type>9</type>
        <size>20</size>
        <definitional>false</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>num_issue_range</key>
        <displayName>Numeric Issue Range</displayName>
        <description>A Range of issues in the form: min-max</description>
        <type>8</type>
        <size>20</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
    </list>
  </entry>
  <entry>
    <string>au_permission_url</string>
    <list>
      <string>"%spublishing/journals/lockss/?journalcode=%s&year=%d", base_url, journal_code, year</string>
      <string>"%slockss.htm", resolver_url</string>
      <string>"%s/issue-%d/issue.htm", resolver_url, num_issue_range</string>
    </list>
  </entry>
  <entry>
    <string>au_additional_url_stems</string>
    <list>
      <string>"%s", to_https(base_url)</string>
      <string>"%s", to_http(base_url)</string>
    </list>
  </entry>
  <entry>
    <string>au_http_cookie</string>
    <list>
      <string>uid=gingerbread</string>
      <string>s_vi=[CS]v1|26-60[CE]</string>
    </list>
  </entry>
  <entry>
    <string>au_http_request_header</string>
    <list>
      <string>Accept-Language:Klingon</string>
      <string>Expect 5 misformatted request header errors</string>
      <string></string>
      <string>foo:</string>
      <string>:bar</string>
      <string>no_colon</string>
      <string>An:other</string>
    </list>
  </entry>
  <entry>
    <string>plugin_article_iterator_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$ArtIterFact</string>
  </entry>
  <entry>
    <string>plugin_default_article_mime_type</string>
    <string>application/pdf</string>
  </entry>
  <entry>
    <string>plugin_article_metadata_extractor_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$MetaExtFact</string>
  </entry>
  <entry>
    <string>text/xml_metadata_extractor_factory_map</string>
    <map>
      <entry>
        <string>*; DublinCore</string>
	<string>org.lockss.plugin.definable.MockFactories$XmlMetaExtFact</string>
      </entry>
      <entry>
        <string>DublinRind</string>
	<string>org.lockss.plugin.definable.MockFactories$XmlRindMetaExtFact</string>
      </entry>
    </map>
  </entry>
  <entry>
    <string>text/javascript_link_rewriter_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$JsRewriterFact</string>
  </entry>
  <entry>
    <string>text/*_content_validator_factory</string>
    <string>org.lockss.test.MockContentValidatorFactory</string>
  </entry>
  <entry>
    <string>*/*_content_validator_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$AllContentValidatorFactory</string>
  </entry>
  <entry>
    <string>application/pdf_content_validator_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$PdfContentValidatorFactory</string>
  </entry>
  <entry>
    <string>plugin_substance_predicate_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$SubstPredFact</string>
  </entry>
  <entry>
    <string>plugin_url_fetcher_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$UrlFetFact</string>
  </entry>
  <entry>
    <string>plugin_url_consumer_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$UrlConsFact</string>
  </entry>
  <entry>
    <string>plugin_crawl_seed_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$CrawlSeedFact</string>
  </entry>
  <entry>
    <string>plugin_access_url_factory</string>
    <string>org.lockss.plugin.definable.MockFactories$FeatureUrlHelperFact</string>
  </entry>
  <entry>
    <string>au_exclude_urls_from_polls_pattern</string>
    <list>
      <string>"%s.*/rotating_ad.*", base_url</string>
      <string>"%s.*\.css", base_url</string>
    </list>
  </entry>
  <entry>
    <string>au_url_poll_result_weight</string>
    <list>
      <string>"%s.*/rotating_ad.*", base_url , 0</string>
      <string>"%s.*\.css", base_url , .5</string>
      <string>"%s%s.*\.html", base_url,journal_code , 1</string>
    </list>
  </entry>

  <entry>
    <string>au_substance_url_pattern</string>
    <map>
      <entry>
        <string>ABSTRACT</string>
	<string>"%sabstract/.*\.html", base_url</string>
      </entry>
      <entry>
        <string>FULLTEXT; *</string>
	<list>
	  <string>"%sarticle/.*\.pdf", base_url</string>
	  <string>"%sletters/.*\.html", base_url</string>
	</list>
      </entry>
    </map>
  </entry>
  <entry>
    <string>au_non_substance_url_pattern</string>
    <string>"%sfluff/", base_url</string>
  </entry>
  <entry>
    <string>au_permitted_host_pattern</string>
    <list>
      <string>".*\.cdn\.%s", url_host(base_url)</string>
      <string>".*\.cdn\.net"</string>
    </list>
  </entry>
  <entry>
    <string>au_repair_from_peer_if_missing_url_pattern</string>
    <list>
      <string>".*\.css$"</string>
      <string>"%simg/", base_url</string>
    </list>
  </entry>

  <entry>
    <!-- Crawl window open from midnight to 6:00AM EST -->
    <string>au_crawlwindow_ser</string>
    <org.lockss.daemon.CrawlWindows-Interval>
      <start>
        <time>1277362837493</time>
        <timezone>America/Los_Angeles</timezone>
      </start>
      <end>
        <time>1277298037493</time>
        <timezone>America/Los_Angeles</timezone>
      </end>
      <fieldMask>3</fieldMask>
      <timeZoneId>US/Eastern</timeZoneId>
    </org.lockss.daemon.CrawlWindows-Interval>
  </entry>
  <entry>
    <string>plugin_bulk_content</string>
    <boolean>true</boolean>
  </entry>
  <entry>
    <string>plugin_send_referrer</string>
    <boolean>false</boolean>
  </entry>
  <entry>
    <string>plugin_store_probe_permission</string>
    <boolean>false</boolean>
  </entry>
  <entry>
    <string>plugin_archive_file_types</string>
    <org.lockss.plugin.ArchiveFileTypes>
      <extMimeMap>
	<entry>
          <string>.zip</string>
	  <string>.zip</string>
	</entry>
	<entry>
          <string>application/x-tar</string>
	  <string>.tar</string>
	</entry>
      </extMimeMap>
    </org.lockss.plugin.ArchiveFileTypes>
  </entry>
  <entry>
    <string>au_url_mime_type</string>
    <list>
      <string>.*\.ris$, application/x-research-info-systems</string>
      <string>"%s.*/pdf_url.*", base_url,application/pdf</string>
    </list>
  </entry>
  <entry>
    <string>plugin_cache_result_list</string>
    <list>
      <string>300=org.lockss.util.urlconn.CacheException$PermissionException</string>
      <string>500=org.lockss.util.urlconn.CacheException$RetryableNetworkException_5_60S</string>
      <string>java.io.IOException=org.lockss.util.urlconn.CacheException$RetryableNetworkException_5_30S</string>
      <string>522=org.lockss.plugin.definable.LargeTestHttpResponseHandler</string>
      <string>EmptyFile=org.lockss.util.urlconn.CacheException$NoRetryHostException</string>
    </list>
  </entry>
  <entry>
    <string>au_feature_urls</string>
    <map>
      <entry>
	<string>au_feat_single</string>
	<string>"%s?issue=%d", base_url, num_issue_range</string>
      </entry>
      <entry>
	<string>au_feat_list</string>
	<list>
	  <string>"%s?issue=%d", base_url, num_issue_range</string>
	  <string>"%sfoo", base_url</string>
	  <string>"%sset/%s", base_url, issue_set</string>
	</list>
      </entry>
      <entry>
	<string>au_feat_map</string>
	<map>
	  <entry>
	    <string>key1</string>
	    <string>"%sbar", base_url</string>
	  </entry>
	  <entry>
	    <string>key2;*</string>
	    <list>
	      <string>"%s222", base_url</string>
	      <string>"%s333/%s", base_url, issue_set</string>
	    </list>
	  </entry>
	</map>
      </entry>
      <entry>
	<string>au_feat_fn_single</string>
	<string>"%s?issue=%d", add_www(base_url), num_issue_range</string>
      </entry>
      <entry>
	<string>au_feat_fn_list</string>
	<list>
	  <string>"%s?issue=%d", add_www(base_url), num_issue_range</string>
	  <string>"%sfoo", base_url</string>
	  <string>"%sset/%s", base_url, issue_set</string>
	</list>
      </entry>
    </map>
  </entry>
</map>


text:
r'''
Utility functionality
=====================

.. currentmodule:: micronota.util

This module (:mod:`micronota.util`) provides various utility functionality,
'''

# ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------

from unittest import TestCase
from sqlite3 import connect
from logging import getLogger

from skbio import read, write, Sequence, DNA

logger = getLogger(__name__)

def convert(in_f, in_fmt, out_f, out_fmt):
    '''convert between file formats

    Parameters
    ----------
    in_fmt : str
        input file format
    out_fmt : str
        output file format
    in_f : str
        input file path
    out_f: str
        output file path
    '''
    for obj in read(in_f, format=in_fmt):
        write(obj, format=out_fmt, into=out_f)

def _filter_sequence_ids(in_fp, out_fp, ids, negate=False):
    '''Filter away the seq with specified IDs.'''
    with open(out_fp, 'w') as out:
        for seq in read(in_fp, format='fasta', constructor=Sequence):
            seq_id = seq.metadata['id']
            if seq_id not in ids:
                write(seq, format='fasta', into=out)

def _add_cds_metadata(seq_id, imd, cds_metadata):
    '''Add metadata to all the CDS interval features.'''
    for intvl in imd._intervals:
        md = intvl.metadata
        # this md is parsed from prodigal output, which
        # has ID like "seq1_1", "seq1_2" for genes
        idx = md['ID'].rsplit('_', 1)[1]
        md['ID'] = '%s_%s' % (seq_id, idx)
        if idx in cds_metadata:
            md.update(cds_metadata[idx])

def filter_ident_overlap(df, pident=90, overlap=80):
    '''Filter away the hits using the same UniRef clustering standards.

    Parameters
    ----------
    df : ``pandas.DataFrame``
        it must have columns of 'pident', 'gaps', and 'slen'
    pident : ``Numeric``
        minimal percentage of identity
    overlap : ``Numeric``
        minimal percentage of overlap for subject sequences.

    Returns
    -------
    ``pandas.DataFrame``
        The data frame only containing hits that pass the thresholds.
    '''
    select_id = df.pident >= pident
    overlap_length = df.length - df.gaps
    select_overlap = overlap_length * 100 / df.slen >= overlap
    # if qlen * 100 / len(row.sequence) >= 80:
    df_filtered = df[select_id & select_overlap]
    # df_filtered.set_index('qseqid', drop=True, inplace=True)
    return df_filtered

def check_seq(in_seq, in_fmt=None, discard=lambda s: len(s) < 500):
    '''Validate and filter input seq file.

    1. filter seq;
    2. validate seq IDs (no duplicates)
    3. remove gaps in the sequence if there is any

    Parameters
    ----------
    in_seq : str or Iterable of ``Sequence`` objects
        input seq file path if it is a str
    in_fmt : str
        the format of seq file
    discard : callable
        a callable that applies on a ``Sequence`` and return a boolean

    Yields
    ------
    ``Sequence`` object

    TODO
    ----
    add an option to ignore the abnormal seq and continue yielding
    '''
    logger.info('Filter and validate input sequences')
    ids = set()

    if isinstance(in_seq, str):
        # allow lowercase in DNA seq
        in_seq = read(in_seq, format=in_fmt, constructor=DNA, lowercase=True)

    for seq in in_seq:
        seq = seq.degap()
        if discard(seq):
            continue

        if in_fmt == 'genbank':
            seq.metadata['id'] = seq.metadata['LOCUS']['locus_name']
        try:
            ident = seq.metadata['id']
        except KeyError:
            raise KeyError('Ill input file format: at least one sequences do not have IDs.')
        if ident in ids:
            raise ValueError(
                'Duplicate seq IDs in your input file: {}'.format(ident))
        else:
            ids.add(ident)
            yield seq

def filter_partial_genes(in_fp, out_fp, out_fmt='gff3'):
    '''filter out partial genes from Prodigal predicted CDS.

    It uses "partial" tag in the GFF3 from Prodigal to identify partial genes.

    Parameters
    ----------
    in_fp : str
        input gff3 file
    out_fp : str
        output gff3 file
    '''
    logger.info('filter out partial genes for genome %s' % in_fp)
    with open(out_fp, 'w') as out:
        for seq_id, imd in read(in_fp, format='gff3'):
            for i in imd.query(metadata={'partial': '01'}):
                i.drop()
            for i in imd.query(metadata={'partial': '10'}):
                i.drop()
            imd.write(out, seq_id=seq_id, format='gff3')

class _DBTest(TestCase):
    def _test_eq_db(self, db1, db2):
        '''Test if two database files have the same contents.'''
        with connect(db1) as o, connect(db2) as e:
            co = o.cursor()
            ce = e.cursor()
            # compare each table
            for table, in e.execute(
                    "SELECT name FROM sqlite_master WHERE type='table'"):
                co.execute('SELECT * FROM %s' % table)
                ce.execute('SELECT * FROM %s' % table)
                self.assertEqual(co.fetchall(), ce.fetchall())

def split(is_another, construct=None, ignore=None, **kwargs):
    '''Return a function to yield record.

    Parameters
    ----------
    is_another : callable
        accept a string and return a bool indicating if the current
        line starts a new record or not.
    construct : callable (optional)
        accept a string and return a modified each input line. Default
        is to strip the whitespaces at the ends. Do nothing if it is
        ``None``.
    ignore : callable (optional)
        A callable to ignore the line if it returns ``True``. Do nothing
        if it is ``None``.
    kwargs : dict
        optional key word arguments passing to ``is_another``

    Returns
    -------
    function
        a function that accepts a file-object-like and yields record
        one by one from it.

    '''
    def parse(stream):
        lines = []
        for line in stream:
            if ignore is not None and ignore(line):
                continue
            if is_another(line, **kwargs):
                if lines:
                    yield lines
                    lines = []
            if construct is not None:
                line = construct(line)
            lines.append(line)
        if lines:
            yield lines
    return parse

def split_head(line, is_head=lambda line: line.startswith('>')):
    '''

    Examples
    --------
    >>> import io
    >>> s = """>seq1
    ... ATGC
    ... >seq2
    ... A
    ... T
    ... """
    >>> f = io.StringIO(s)
    >>> gen = split(split_head, construct=lambda x: x.strip())
    >>> list(gen(f))
    [['>seq1', 'ATGC'], ['>seq2', 'A', 'T']]
    '''
    if is_head(line):
        return True
    else:
        return False

class SplitterTail:
    r'''Split a stream of lines into record delimited by its tail of each record.

    Parameters
    ----------
    is_tail : callable
        to return a bool indicating if the current line concludes current record

    Examples
    --------
    Let's create a file object that has sequences separated by "//" at
    the end of each record (similar to multiple GenBank records in a file):

    >>> import io
    >>> s = """seq1
    ... AT
    ... //
    ... seq2
    ... ATGC
    ... //
    ... """
    >>> f = io.StringIO(s)

    And then we can yield each sequence with this code:

    >>> splitter = SplitterTail(lambda x: x == '//\n')
    >>> gen = split(splitter, construct=lambda x: x.strip())
    >>> list(gen(f))
    [['seq1', 'AT', '//'], ['seq2', 'ATGC', '//']]
    '''
    def __init__(self, is_tail):
        self.is_tail = is_tail
        self._flag = False

    def __call__(self, line):
        if self.is_tail(line):
            self._flag = True
            return False
        else:
            if self._flag:
                self._flag = False
                return True

class SplitterID:
    r'''Split a stream of lines into record based on every line of each record.

    Parameters
    ----------
    identify : callable
        accept a string and return a value. By comparing the value to
        that of its previous line, it judges if the current line is
        like its previous line belonging to the same record

    Examples
    --------
    >>> from pprint import pprint
    >>> import io
    >>> s = """##gff-version 3
    ... ctg123\t.\texon\t1300\t1500\t.\t+\t.\tID=exon00001
    ... ctg123\t.\texon\t1050\t1500\t.\t+\t.\tID=exon00002
    ... ctg124\t.\texon\t3000\t3902\t.\t+\t.\tID=exon00003
    ... """
    >>> f = io.StringIO(s)
    >>> splitter = SplitterID(lambda x: x.split('\t')[0])
    >>> gen = split(splitter, lambda x: x.strip(), lambda x: x.startswith('#'))
    >>> pprint(list(gen(f)))
    [['ctg123\t.\texon\t1300\t1500\t.\t+\t.\tID=exon00001',
      'ctg123\t.\texon\t1050\t1500\t.\t+\t.\tID=exon00002'],
     ['ctg124\t.\texon\t3000\t3902\t.\t+\t.\tID=exon00003']]

    '''
    def __init__(self, identify):
        self._ident = None
        self.identify = identify

    def __call__(self, line):
        ident = self.identify(line)
        if self._ident == ident:
            return False
        else:
            self._ident = ident
            return True


text:
<?php

declare(strict_types=1);

namespace Platform\Bundle\AdminBundle\Model;

use Sylius\Component\User\Model\UserInterface;

interface AdminUserInterface extends UserInterface
{
    public const DEFAULT_ADMIN_ROLE = 'ROLE_ADMINISTRATION_ACCESS';

    public function getFirstName(): ?string;

    public function setFirstName(?string $firstName): void;

    public function getLastName(): ?string;

    public function setLastName(?string $lastName): void;

    public function getLocaleCode(): ?string;

    public function setLocaleCode(?string $code): void;
}


text:
package io.udash.bindings.modifiers

import io.udash.properties.single.ReadableProperty
import io.udash.utils.Registration
import org.scalajs.dom.Node

private[bindings] class PropertyModifier[T](
  override val property: ReadableProperty[T],
  override val builder: (T, Binding.NestedInterceptor) => Seq[Node],
  override val checkNull: Boolean,
  override val customElementsReplace: DOMManipulator.ReplaceMethod
) extends ValueModifier[T] {

  def this(property: ReadableProperty[T], builder: T => Seq[Node], checkNull: Boolean, customElementsReplace: DOMManipulator.ReplaceMethod) = {
    this(property, (data: T, _: Binding.NestedInterceptor) => builder(data), checkNull, customElementsReplace)
  }

  def listen(callback: T => Unit): Registration =
    property.listen(callback)

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

    <copyright>
      <year>1999</year><year>2016</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

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

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

    </legalnotice>

    <title>CosTransactions_SubtransactionAwareResource</title>
    <prepared></prepared>
    <docno></docno>
    <checked></checked>
    <date>1999-04-12</date>
    <rev>PA1</rev>

  <module>CosTransactions_SubtransactionAwareResource</module>
  <modulesummary>This module implements the OMG CosTransactions::SubtransactionAwareResource interface.</modulesummary>
  <description>

This interface inherits the CosTransactions::Resource interface. Hence,
      it must also support all operations defined in the Resource interface.

To get access to the record definitions for the structures use:

<c>-include_lib("cosTransactions/include/CosTransactions.hrl").</c>

  </description>
  <funcs>
    <func>
      <name>commit_subtransaction(SubtransactionAwareResource, Coordinator) -> Return</name>
      <fsummary>Notify the target object that the transaction has committed</fsummary>
      <type>
        <v>SubtransactionAwareResource = #objref</v>
        <v>Coordinator = #objref</v>
        <v>Return = ok</v>
      </type>
      <desc>

If the <c>SubtransactionAwareResource</c> have been registered with a subtransaction
          using the operation <c>CosTransactions_Coordinator:register_subtran_aware/2</c>,
          it will be notified when the transaction has committed.

        <note>

The results of a committed subtransaction are relative to the completion of its ancestor
            transactions, that is, these results can be undone if any ancestor transaction is rolled back.

        </note>
      </desc>
    </func>
    <func>
      <name>rollback_subtransaction(SubtransactionAwareResource) -> Return</name>
      <fsummary>Notify the target object that the transaction has been rolled back</fsummary>
      <type>
        <v>SubtransactionAwareResource = #objref</v>
        <v>Return = ok</v>
      </type>
      <desc>

If the <c>SubtransactionAwareResource</c> have been registered with a transactions
          using the operation <c>CosTransactions_Coordinator:register_subtran_aware/2</c>
          it will be notified when the transaction has rolled back.

      </desc>
    </func>
  </funcs>

</erlref>


text:
/*
 * (c) 2009 Marc G. Bellemare.
 */

package org.rlcommunity.environments.continuousgridworld.observationmapping;

import org.rlcommunity.rlglue.codec.types.Observation;

/** A mapping encapsulating another mapping, which first scales the observations
 *   to be in [0,1] before passing them to the encapsulated mapping. The result
 *   is in the same scale as what was provided, e.g. scaling is only applied so
 *   that the data falls within the [0,1] range for the encapsulated mapping.
 *
 * @author Marc G. Bellemare (mg17 at cs ualberta ca)
 */
public class ScaledMapping implements ObservationMapping {
    protected final double[] aMins;
    protected final double[] aMaxes;

    protected ObservationMapping aMapping;

    public ScaledMapping(ObservationMapping pMap, double[] pMins, double[] pMaxes) {
        aMins = pMins;
        aMaxes = pMaxes;
        aMapping = pMap;
    }

    public Observation map(Observation pOriginal) {
        // Scale the observation
        Observation obs = new Observation(pOriginal);

        // Scale the observation vector to be in [0,1]^d
        for (int i = 0; i < obs.doubleArray.length; i++) {
            double v = pOriginal.doubleArray[i];
            obs.doubleArray[i] = (v - aMins[i]) / (aMaxes[i] - aMins[i]);
        }

        // Call the underlying map on the scaled observation
        Observation result = aMapping.map(obs);

        // Now un-scale it
        for (int i = 0; i < obs.doubleArray.length; i++) {
            double v = result.doubleArray[i];
            obs.doubleArray[i] = v * (aMaxes[i] - aMins[i]) + aMins[i];
        }

        return obs;
    }
}


text:
<?php

class ModuleMresource_EntityMresourceCategory extends Entity {

    public function getId() {
        return $this->getProp('id');
    }

    public function getLabel() {
        return $this->getProp('label');
    }

    public function getCount() {
        return $this->getProp('count');
    }
}

// EOF


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>net.sf.taverna</groupId>
	<artifactId>wsdl-generic</artifactId>
	<packaging>jar</packaging>
	<version>1.2-SNAPSHOT</version>
	<name>wsdl-generic</name>
	<description>
		WSDL handling classes that are shared between Taverna 1 and 2
	</description>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<skip>false</skip>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<releases />
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
			<id>mygrid-repository</id>
			<name>myGrid Repository</name>
			<url>http://www.mygrid.org.uk/maven/repository</url>
		</repository>
		<repository>
			<releases>
				<enabled>false</enabled>
			</releases>
			<snapshots />
			<id>mygrid-snapshot-repository</id>
			<name>myGrid Snapshot Repository</name>
			<url>
				http://www.mygrid.org.uk/maven/snapshot-repository
			</url>
		</repository>
	</repositories>
	<distributionManagement>
		<!-- use the following if you're not using a snapshot version. -->
		<repository>
			<id>mygrid-repository</id>
			<name>myGrid Repository</name>
			<url>
				scpexe://rosalind.cs.man.ac.uk/local/www/mygrid/maven/repository
			</url>
		</repository>
		<!-- use the following if you ARE using a snapshot version. -->
		<snapshotRepository>
			<id>mygrid-snapshot-repository</id>
			<name>myGrid Snapshot Repository</name>
			<url>
				scpexe://rosalind.cs.man.ac.uk/local/www/mygrid/maven/snapshot-repository
			</url>
		</snapshotRepository>
		<site>
			<id>website</id>
			<url>${siteurl}</url>
		</site>
	</distributionManagement>

	<dependencies>
		<dependency>
			<groupId>axis</groupId>
			<artifactId>axis-saaj</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>wsdl4j</groupId>
			<artifactId>wsdl4j</artifactId>
			<version>1.5.1</version>
		</dependency>
		<dependency>
			<groupId>jdom</groupId>
			<artifactId>jdom</artifactId>
			<version>1.0</version>
		</dependency>
		<dependency>
			<groupId>axis</groupId>
			<artifactId>axis-jaxrpc</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>uk.org.mygrid.resources</groupId>
			<artifactId>axis</artifactId>
			<version>1.4-taverna</version>
		</dependency>
		<dependency>
			<groupId>javax.activation</groupId>
			<artifactId>activation</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.12</version>
		</dependency>
		<dependency>
			<groupId>uk.org.mygrid.taverna.scufl</groupId>
			<artifactId>scufl-model</artifactId>
			<version>1.7.1.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>xerces</groupId>
			<artifactId>xmlParserAPIs</artifactId>
			<version>2.2.1</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.4</version>
			<scope>test</scope>
		</dependency>
			<dependency>
			<groupId>axis</groupId>
			<artifactId>addressing</artifactId>
			<version>1.0</version>
		</dependency>
	</dependencies>
</project>


text:
package com.sun.xml.ws.sdo.sample.service.types;

import commonj.sdo.DataObject;

public interface GetTotalComp extends DataObject {

   public java.math.BigInteger getEmpno();

   public void setEmpno(java.math.BigInteger value);

}


text:
package org.kuali.kra.award.document;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kuali.kra.test.infrastructure.KcIntegrationTestBase;
import org.kuali.rice.krad.UserSession;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.util.GlobalVariables;
import static org.junit.Assert.*;
public class AwardDocumentIntegrationTest extends KcIntegrationTestBase {

    @Test
    public void testSavingDocument() throws Exception {
        GlobalVariables.setUserSession(new UserSession("quickstart"));

        AwardDocument doc = (AwardDocument) KRADServiceLocatorWeb.getDocumentService().getNewDocument(AwardDocument.class);
        assertNotNull(doc);
    }
}


text:
package org.kuali.kra.award.printing.xmlstream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlbeans.XmlObject;
import org.kuali.coeus.common.framework.print.stream.xml.XmlStream;
import org.kuali.coeus.common.framework.print.util.PrintingUtils;
import org.kuali.coeus.common.framework.rolodex.Rolodex;
import org.kuali.coeus.common.framework.sponsor.Sponsor;
import org.kuali.coeus.common.framework.sponsor.term.SponsorTerm;
import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.kra.award.home.*;
import org.kuali.kra.award.paymentreports.Frequency;
import org.kuali.kra.award.paymentreports.FrequencyBase;
import org.kuali.kra.award.paymentreports.Report;
import org.kuali.kra.award.paymentreports.ReportClass;
import org.kuali.kra.award.printing.AwardPrintType;
import org.kuali.kra.printing.schema.*;
import org.kuali.kra.printing.schema.ContactType;
import org.kuali.kra.printing.schema.ReportTermDetailsType.MailCopies;
import org.kuali.kra.printing.schema.TemplateDocument.Template;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.krad.service.BusinessObjectService;

import java.sql.Date;
import java.util.*;

/**
 * This class generates XML that conforms with the XSD related to Award Template
 * Report. The data for XML is derived from {@link org.kuali.coeus.sys.framework.model.KcTransactionalDocumentBase} and
 * {@link Map} of details passed to the class.
 *
 *
 */
public class AwardTemplateXmlStream implements XmlStream {

	private static final Log LOG = LogFactory.getLog(AwardTemplateXmlStream.class);

	private BusinessObjectService businessObjectService = null;
	private DateTimeService dateTimeService = null;
	private static final String SCHOOL_NAME = "SCHOOL_NAME";
	private static final String SCHOOL_ACRONYM = "SCHOOL_ACRONYM";
	private String previousDescription="";

	/**
	 * This method generates XML for Award template Report. It uses data passed
	 * in {@link org.kuali.coeus.sys.framework.model.KcTransactionalDocumentBase} for populating the XML nodes. The XMl
	 * once generated is returned as {@link XmlObject}
	 *
	 * @param printableBusinessObject
	 *            using which XML is generated
	 * @param reportParameters
	 *            parameters related to XML generation
	 * @return {@link XmlObject} representing the XML
	 */
	public Map<String, XmlObject> generateXmlStream(
			KcPersistableBusinessObjectBase printableBusinessObject, Map<String, Object> reportParameters) {
		Map<String, XmlObject> awardTemplateXmlStream = new HashMap<String, XmlObject>();
		AwardTemplate awardTemplate = (AwardTemplate) printableBusinessObject;
		TemplateDocument templateDocument = TemplateDocument.Factory.newInstance();
		if (awardTemplate != null) {
			templateDocument.setTemplate(getTemplate(awardTemplate));
		}
		awardTemplateXmlStream.put(AwardPrintType.AWARD_TEMPLATE.getAwardPrintType(), templateDocument);
		return awardTemplateXmlStream;
	}

	/*
	 * This method will set the values to template elements and finally returns
	 * the template xml object.
	 */
	private Template getTemplate(AwardTemplate awardTemplate) {
		Template template = Template.Factory.newInstance();
		awardTemplate.refreshNonUpdateableReferences();
		template.setTemplateMaster(getTemplateMaster(awardTemplate));
		template.setSchoolInfo(getSchoolInfoType());
		template.setCommentArray(getCommentType(awardTemplate));
		template.setContactArray(getContactType(awardTemplate));
		template.setTermArray(getTerms(awardTemplate));
		template.setReportArray(getReportTermTypes(awardTemplate));
		return template;
	}

	private TemplateMasterData getTemplateMaster(AwardTemplate awardTemplate) {
	    TemplateMasterData templateMasterData = TemplateMasterData.Factory.newInstance();
	    templateMasterData.setCurrentDate(getDateTimeService().getCurrentCalendar());
	    templateMasterData.setDescription(awardTemplate.getDescription());
	    templateMasterData.setTemplateCode(awardTemplate.getTemplateCode());
	    if(awardTemplate.getBasisOfPaymentCode()!=null){
	        BasisPaymentType basisPayment = templateMasterData.addNewBasisPayment();
	        AwardBasisOfPayment awardBasisOfPayment = awardTemplate.getAwardBasisOfPayment();
	        if(awardBasisOfPayment!=null){
	            basisPayment.setBasisPaymentCode(awardBasisOfPayment.getBasisOfPaymentCode());
	            basisPayment.setBasisPaymentDesc(awardBasisOfPayment.getDescription());
	        }
	    }
	    if(awardTemplate.getCompetingRenewalPrpslDueCode()!=null){
	        CompetingRenewalType competingRenewal = templateMasterData.addNewCompetingRenewal();
	        competingRenewal.setCompetingRenewalCode(awardTemplate.getCompetingRenewalPrpslDueCode());
	    }
	    if(awardTemplate.getNonCompetingContPrpslDueCode()!=null){
	        NonCompetingContType nonCompetingCont = templateMasterData.addNewNonCompetingCont();
	        nonCompetingCont.setNonCompetingContCode(awardTemplate.getNonCompetingContPrpslDueCode());
	    }
	    if(awardTemplate.getMethodOfPaymentCode()!=null){
	        AwardMethodOfPayment awardMethodOfPayment = awardTemplate.getAwardMethodOfPayment();
	        PaymentMethodType paymentMethod = templateMasterData.addNewPaymentMethod();
	        paymentMethod.setPaymentMethodCode(awardMethodOfPayment.getMethodOfPaymentCode());
	        paymentMethod.setPaymentMethodDesc(awardMethodOfPayment.getDescription());
	    }
	    if(awardTemplate.getPrimeSponsorCode()!=null){
	        SponsorType sponsorType = templateMasterData.addNewPrimeSponsor();
	        Sponsor sponsor = awardTemplate.getPrimeSponsor();
	        sponsorType.setSponsorCode(sponsor.getSponsorCode());
	        sponsorType.setSponsorName(sponsor.getSponsorName());
	    }
	    if(awardTemplate.getStatusCode()!=null){
	        TemplateStatusType templateStatus = templateMasterData.addNewTemplateStatus();
	        AwardStatus awardTemplateStatus = awardTemplate.getAwardTemplateStatus();
	        templateStatus.setStatusCode(Integer.parseInt(awardTemplateStatus.getStatusCode()));
	        templateStatus.setStatusDesc(awardTemplateStatus.getDescription());
	    }
        return templateMasterData;
    }

    private TermType[] getTerms(AwardTemplate awardTemplate) {
        List<TermType> termTypes = new ArrayList<TermType>();
        for (AwardTemplateTerm awardTemplateTerm : awardTemplate.getAwardSponsorTerms()) {
            TermType termType = TermType.Factory.newInstance();
            setTermDetails(termType,awardTemplateTerm);
            termTypes.add(termType);
        }
        return termTypes.toArray(new TermType[0]);
    }

    private void setTermDetails(TermType termType,AwardTemplateTerm awardTemplateTerm) {
        awardTemplateTerm.refreshNonUpdateableReferences();
        SponsorTerm sponsorTerm = awardTemplateTerm.getSponsorTerm();
        if(sponsorTerm!=null){
           if(previousDescription.equals("")||!previousDescription.equals(awardTemplateTerm.getSponsorTerm().getSponsorTermType().getDescription())){
            termType.setDescription(awardTemplateTerm.getSponsorTerm().getSponsorTermType().getDescription());
            previousDescription=awardTemplateTerm.getSponsorTerm().getSponsorTermType().getDescription();
           }
            TermDetailsType termDetails = termType.addNewTermDetails();
            termDetails.setTermCode(Integer.parseInt(sponsorTerm.getSponsorTermCode()));
            termDetails.setTermDescription(sponsorTerm.getDescription());
        }
    }

    /*
	 * This method will set the values to report term types elements and finally
	 * returns the report term type.It iterates over the Award Template Report
	 * Term.
	 */
	private ReportTermType[] getReportTermTypes(AwardTemplate awardTemplate) {
		List<ReportTermType> reportTermTypes = new ArrayList<ReportTermType>();
		ReportTermType reportTermType = null;
		for (AwardTemplateReportTerm awardTemplateReportTerm : awardTemplate
				.getTemplateReportTerms()) {
			reportTermType = ReportTermType.Factory.newInstance();
			awardTemplateReportTerm.refreshNonUpdateableReferences();
			ReportClass reportClass = awardTemplateReportTerm.getReportClass();
			if (reportClass != null && reportClass.getDescription() != null) {
				reportTermType.setDescription(reportClass.getDescription());
			}
			reportTermType.setReportTermDetailsArray(getReportTermDetails(awardTemplateReportTerm));
			reportTermTypes.add(reportTermType);
		}
		return reportTermTypes.toArray(new ReportTermType[0]);
	}

	/*
	 * This method will set the values to report term details elements and
	 * finally return the array of the report term details type.It iterates over
	 * the
	 */
	private ReportTermDetailsType[] getReportTermDetails(AwardTemplateReportTerm awardTemplateReportTerm) {
		List<ReportTermDetailsType> reportTermDetailsTypes = new ArrayList<ReportTermDetailsType>();
		ReportTermDetailsType reportTermDetailsType = null;
		reportTermDetailsType = ReportTermDetailsType.Factory.newInstance();
		Date dueDate = awardTemplateReportTerm.getDueDate();
		if (dueDate != null) {
			reportTermDetailsType.setDueDate(dateTimeService.getCalendar(dueDate));
		}
		setFrequencyBaseDetails(awardTemplateReportTerm, reportTermDetailsType);
		setFrequencyDetails(awardTemplateReportTerm, reportTermDetailsType);
		setOspDistributionDetails(awardTemplateReportTerm,reportTermDetailsType);
		setReportClassDetails(awardTemplateReportTerm, reportTermDetailsType);
		setReportDetails(awardTemplateReportTerm, reportTermDetailsType);
		reportTermDetailsType.setMailCopiesArray(getMailCopies(awardTemplateReportTerm));
		reportTermDetailsTypes.add(reportTermDetailsType);
		return reportTermDetailsTypes.toArray(new ReportTermDetailsType[0]);
	}

	/*
	 * This method will set the values to report term details of report
	 * elements.
	 */
	private void setReportDetails(
			AwardTemplateReportTerm awardTemplateReportTerm,
			ReportTermDetailsType reportTermDetailsType) {
		Report report = awardTemplateReportTerm.getReport();
		String reportCode = report.getReportCode();
		String reportDescription = report.getDescription();
		if (reportCode != null) {
			reportTermDetailsType.setReportCode(Integer.valueOf(reportCode));
		}
		if (reportDescription != null) {
			reportTermDetailsType.setReportCodeDesc(reportDescription);
		}
	}

	/*
	 * This method will set the values to report term details of report class
	 * elements.
	 */
	private void setReportClassDetails(
			AwardTemplateReportTerm awardTemplateReportTerm,
			ReportTermDetailsType reportTermDetailsType) {
		ReportClass reportClass = awardTemplateReportTerm.getReportClass();
		String reportClassCode = reportClass.getReportClassCode();
		String reportClassDescription = reportClass.getDescription();
		if (reportClassCode != null) {
			reportTermDetailsType.setReportClassCode(Integer
					.valueOf(reportClassCode));
		}
		if (reportClassDescription != null) {
			reportTermDetailsType.setReportCodeDesc(reportClassDescription);
		}
	}

	/*
	 * This method will set the values to report term details of OSP
	 * distribution elements.
	 */
	private void setOspDistributionDetails(
			AwardTemplateReportTerm awardTemplateReportTerm,
			ReportTermDetailsType reportTermDetailsType) {
		String ospDistributionCode = awardTemplateReportTerm
				.getOspDistributionCode();
		if (ospDistributionCode != null) {
			reportTermDetailsType.setOSPDistributionCode(Integer
					.valueOf(ospDistributionCode));
		}
		Distribution distribution = awardTemplateReportTerm.getDistribution();
		String ospDescription = distribution.getDescription();
		if (ospDescription != null) {
			reportTermDetailsType.setOSPDistributionDesc(ospDescription);
		}
	}

	/*
	 * This method will set the values to report term details of frequency
	 * elements.
	 */
	private void setFrequencyDetails(
			AwardTemplateReportTerm awardTemplateReportTerm,
			ReportTermDetailsType reportTermDetailsType) {
		Frequency frequency = awardTemplateReportTerm.getFrequency();
		String frequencyCode = frequency.getFrequencyCode();
		String desription = frequency.getDescription();
		if (frequencyCode != null) {
			reportTermDetailsType.setFrequencyCode(Integer
					.valueOf(frequencyCode));
		}
		if (desription != null) {
			reportTermDetailsType.setFrequencyCodeDesc(desription);
		}
	}

	/*
	 * This method will set the values to report term details of frequency base
	 * elements.
	 */
	private void setFrequencyBaseDetails(
			AwardTemplateReportTerm awardTemplateReportTerm,
			ReportTermDetailsType reportTermDetailsType) {
		String frequencyBaseCode = awardTemplateReportTerm.getFrequencyBaseCode();
		if (frequencyBaseCode != null) {
			reportTermDetailsType.setFrequencyBaseCode(Integer
					.valueOf(frequencyBaseCode));
		}
		awardTemplateReportTerm.refreshNonUpdateableReferences();
		FrequencyBase frequencyBase = awardTemplateReportTerm.getFrequencyBase();
		if(frequencyBase!=null){
		String description = frequencyBase.getDescription();
    		if (description != null) {
    			reportTermDetailsType.setFrequencyBaseDesc(description);
    		}
		}
	}

	/*
	 * This method will set the values to mail copies elements and finally
	 * return the array of mail copies.It iterates over the award template
	 * report term recipient.
	 */
	private MailCopies[] getMailCopies(
			AwardTemplateReportTerm awardTemplateReportTerm) {
		List<MailCopies> mailCopiesList = new ArrayList<MailCopies>();
		MailCopies mailCopies = null;
		for (AwardTemplateReportTermRecipient awardTemplateReportTermRecipient : awardTemplateReportTerm
				.getAwardTemplateReportTermRecipients()) {
			mailCopies = MailCopies.Factory.newInstance();
			awardTemplateReportTermRecipient.refreshNonUpdateableReferences();
			org.kuali.kra.award.home.ContactType contactType = awardTemplateReportTermRecipient.getContactType();
			if(contactType!=null){
    			String contactTypeCode = contactType.getContactTypeCode();
    			String contactTypeDescription = contactType.getDescription();
    			if (contactTypeCode != null) {
    				mailCopies.setContactTypeCode(Integer.valueOf(contactTypeCode));
    			}
    			if (contactTypeDescription != null) {
    				mailCopies.setContactTypeDesc(contactTypeDescription);
    			}
			}
			Integer numberofmailCopies = awardTemplateReportTermRecipient.getNumberOfCopies();
			if (numberofmailCopies != null) {
				mailCopies.setNumberOfCopies(String.valueOf(numberofmailCopies));
			}
			Integer rolodexid = awardTemplateReportTermRecipient.getRolodexId();
			if (rolodexid != null) {
				mailCopies.setRolodexId(String.valueOf(rolodexid));
			}
			mailCopiesList.add(mailCopies);
		}
		return mailCopiesList.toArray(new MailCopies[0]);
	}

	/*
	 * This method will set the values to contact type elements and finally
	 * return the contact type array. From AwardTemplate get the list of
	 * AwardTemplateContact and iterates over it.
	 */
	private ContactType[] getContactType(AwardTemplate awardTemplate) {
		List<ContactType> contactTypes = new ArrayList<ContactType>();
		ContactType contactType = null;
		for (AwardTemplateContact awardTemplateContact : awardTemplate
				.getTemplateContacts()) {
			contactType = ContactType.Factory.newInstance();
			awardTemplateContact.refreshNonUpdateableReferences();
			org.kuali.kra.award.home.ContactType type = awardTemplateContact
					.getContactType();
			String contactTypeCode = null;
			String description =null;
			if (type != null) {
				contactTypeCode = type.getContactTypeCode();
				description= type.getDescription();
			}
			if (contactTypeCode != null) {
				contactType
						.setContactTypeCode(Integer.valueOf(contactTypeCode));
			}
			if (description != null) {
				contactType.setContactTypeDesc(description);
			}
			setRolodexDetails(contactType,awardTemplateContact);
			contactTypes.add(contactType);
		}
		return contactTypes.toArray(new ContactType[0]);
	}

	private void setRolodexDetails(ContactType contactType, AwardTemplateContact awardTemplateContact) {
	    if(awardTemplateContact.getRolodexId()!=null){
	        Rolodex rolodex = awardTemplateContact.getRolodex();
	        if(rolodex!=null){
	            RolodexDetailsType rolodexDetails = contactType.addNewRolodexDetails();
	            rolodexDetails.setAddress1(rolodex.getAddressLine1());
	            rolodexDetails.setAddress2(rolodex.getAddressLine2());
	            rolodexDetails.setAddress3(rolodex.getAddressLine3());
	            rolodexDetails.setCity(rolodex.getCity());
	            rolodexDetails.setComments(rolodex.getComments());
	            rolodexDetails.setCountryCode(rolodex.getCountryCode());
	            rolodexDetails.setCountryDescription(rolodex.getCountryCode());
	            rolodexDetails.setCounty(rolodex.getCounty());
	            rolodexDetails.setEmail(rolodex.getEmailAddress());
	            rolodexDetails.setFax(rolodex.getFaxNumber());
	            rolodexDetails.setFirstName(rolodex.getFirstName());
	            rolodexDetails.setLastName(rolodex.getLastName());
	            rolodexDetails.setMiddleName(rolodex.getMiddleName());
	            rolodexDetails.setOrganization(rolodex.getOrganization());
	            rolodexDetails.setOwnedByUnit(rolodex.getOwnedByUnit());
	            if(rolodex.getUnit()!=null){
	                rolodexDetails.setOwnedByUnitName(rolodex.getUnit().getUnitName());
	            }
	            rolodexDetails.setPhoneNumber(rolodex.getPhoneNumber());
	            rolodexDetails.setPostalCode(rolodex.getPostalCode());
	            rolodexDetails.setPrefix(rolodex.getPrefix());
	            rolodexDetails.setRolodexId(rolodex.getRolodexId().toString());
	            rolodexDetails.setSponsorCode(rolodex.getSponsorCode());
	            if(rolodex.getSponsor()!=null){
	                rolodexDetails.setSponsorName(rolodex.getSponsor().getSponsorName());
	            }
	            rolodexDetails.setStateCode(rolodex.getState());
	            rolodexDetails.setStateDescription(rolodex.getSponsorCode());
	            rolodexDetails.setSuffix(rolodex.getSuffix());
	            rolodexDetails.setTitle(rolodex.getTitle());
	        }

	    }
    }

    /*
	 * This method will set the values to comment type elements and finally
	 * return the comment type array. From AwardTemplate get the list of
	 * AwardTemplateComment and iterates over it.
	 */
	private CommentType[] getCommentType(AwardTemplate awardTemplate) {
		List<CommentType> commentTypes = new ArrayList<CommentType>();
		List<AwardTemplateComment> templateComments = awardTemplate
				.getTemplateComments();
		CommentType commentType = null;
		ArrayList templateCommentList=new ArrayList();
		HashMap<String,String> templateCommentHm=new HashMap<String,String>();
		for (AwardTemplateComment awardTemplateComment : templateComments) {
            String commentTypeCode = awardTemplateComment.getCommentTypeCode();
		    AwardTemplate template = awardTemplateComment.getTemplate();
		    String description = null;
            if (template != null) {
                awardTemplateComment.refreshReferenceObject("commentType");
                description= awardTemplateComment.getCommentType().getDescription();
                templateCommentList.add(description);
            }
            String comments = awardTemplateComment.getComments();
            if(comments!=null && description!=null){
                templateCommentHm.put(description, comments);
            }

		}
		 Collections.sort(templateCommentList);
		 for (int templateComment=0;templateComment<templateCommentList.size();templateComment++){
             if(templateCommentHm.containsKey(templateCommentList.get(templateComment))==true){
                 commentType = CommentType.Factory.newInstance();
                 String comments=(String)templateCommentHm.get(templateCommentList.get(templateComment));
                 String description =templateCommentList.get(templateComment).toString();
                 commentType.setDescription(description);
                 commentType.setComments(comments);

             }
             commentTypes.add(commentType);
        }

	        return commentTypes.toArray(new CommentType[0]);
	}

	/*
	 * This method will set the values to school info attributes and finally
	 * returns SchoolInfoType XmlObject
	 */
	private SchoolInfoType getSchoolInfoType() {
		SchoolInfoType schoolInfoType = SchoolInfoType.Factory.newInstance();
		String schoolName = getAwardParameterValue(SCHOOL_NAME);
		String schoolAcronym = getAwardParameterValue(SCHOOL_ACRONYM);
		if (schoolName != null) {
			schoolInfoType.setSchoolName(schoolName);
		}
		if (schoolAcronym != null) {
			schoolInfoType.setAcronym(schoolAcronym);
		}
		return schoolInfoType;
	}

	public BusinessObjectService getBusinessObjectService() {
		return businessObjectService;
	}

	public void setBusinessObjectService(
			BusinessObjectService businessObjectService) {
		this.businessObjectService = businessObjectService;
	}

	public DateTimeService getDateTimeService() {
		return dateTimeService;
	}

	public void setDateTimeService(DateTimeService dateTimeService) {
		this.dateTimeService = dateTimeService;
	}

	private String getAwardParameterValue(String param) {
		String value = null;
		try {
			value = PrintingUtils.getParameterValue(param);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return value;
	}
}


text:
package monocle.std

import monocle.Prism
import monocle.function.Index
import monocle.internal.{Bits, Bounded}

import scalaz.std.anyVal._

object long extends LongOptics

trait LongOptics {

  implicit val longBitIndex: Index[Long, Int, Boolean] =
    Bits.bitsIndex[Long]

  val longToInt: Prism[Long, Int]  =
    Bounded.orderingBoundedSafeCast[Long, Int](_.toInt)(_.toLong)

  val longToChar: Prism[Long, Char] =
    Bounded.orderingBoundedSafeCast[Long, Char](_.toChar)(_.toLong)

  val longToByte: Prism[Long, Byte] =
    Bounded.orderingBoundedSafeCast[Long, Byte](_.toByte)(_.toLong)

  val longToBoolean: Prism[Long, Boolean] =
    longToByte composePrism byte.byteToBoolean

}


text:
"""Measurement geometries
"""


text:
test_description='merge can handle submodules'

. ./test-lib.sh
. "$TEST_DIRECTORY"/lib-submodule-update.sh

# merges without conflicts
test_submodule_switch "git merge"

test_submodule_switch "git merge --ff"

test_submodule_switch "git merge --ff-only"

KNOWN_FAILURE_NOFF_MERGE_DOESNT_CREATE_EMPTY_SUBMODULE_DIR=1
KNOWN_FAILURE_NOFF_MERGE_ATTEMPTS_TO_MERGE_REMOVED_SUBMODULE_FILES=1
test_submodule_switch "git merge --no-ff"

test_done


text:
<?php

/*
 * A PSR7 aware cURL client (https://github.com/juliangut/spiral).
 *
 * @license BSD-3-Clause
 * @link https://github.com/juliangut/spiral
 * @author Julián Gutiérrez <juliangut@gmail.com>
 */

namespace Jgut\Spiral\Option;

/**
 * Boolean cURL option wrapper.
 */
class OptionBool extends DefaultOption
{
    /**
     * Create boolean cURL option.
     *
     * @param int $option
     */
    public function __construct($option)
    {
        parent::__construct($option);

        $this->value = false;
    }

    /**
     * {@inheritdoc}
     *
     * @param bool $value
     */
    public function setValue($value)
    {
        $this->value = $value === true;
    }
}


text:
cruddly.controller('UpdateCtrl', function ($scope, $state, $stateParams, DataSource) {

    var id = $stateParams.id;

    var load = function () {
        $scope.read = DataSource.read();
        var currentUser = DataSource.getById(id);
        $scope.model = currentUser;
    };

    $scope.update = function () {
        DataSource.update($scope.model);
        $state.go('read');
    };

    load();
});


text:
package org.gflogger.ring;

public final class AlertException extends RuntimeException {

	private static final long	serialVersionUID	= 1L;

	public static final AlertException ALERT_EXCEPTION = new AlertException();

	private AlertException() {
	}

	@Override
	public synchronized Throwable fillInStackTrace() {
		return this;
	}
}


text:
package me.panavtec.cleancontacts.data.api;

import me.panavtec.cleancontacts.data.api.responses.ApiContactsResponse;
import retrofit.http.GET;
import retrofit.http.Query;

public interface ContactsApiService {

  static final String API_VERSION = "/0.4.1";

  @GET(API_VERSION)
  public ApiContactsResponse obtainUser();

  @GET(API_VERSION)
  public ApiContactsResponse obtainUsers(@Query("results") int users);
}


text:
class Ansiweather < Formula
  desc "Weather in your terminal, with ANSI colors and Unicode symbols"
  homepage "https://github.com/fcambus/ansiweather"
  url "https://github.com/fcambus/ansiweather/archive/1.18.0.tar.gz"
  sha256 "362393918b64083de466414ca3ada3e0236206b29bfb2624d4ad1284774e6a7a"
  license "BSD-2-Clause"
  revision 1
  head "https://github.com/fcambus/ansiweather.git", branch: "master"

  bottle do
    sha256 cellar: :any_skip_relocation, all: "80cab6cc26ed03f58ec06f593fda3dd072cbf0a8255b9f6afbcd02f516d9cd7f"
  end

  depends_on "jq"

  uses_from_macos "bc"

  def install
    bin.install "ansiweather"
    man1.install "ansiweather.1"
  end

  test do
    assert_match "Wind", shell_output("#{bin}/ansiweather")
  end
end


text:
'use strict';

module.exports = Sandbox;

/**
 * @name h5.pubsub.Sandbox
 * @constructor
 * @implements {h5.pubsub.Broker}
 * @param {h5.pubsub.Broker} broker
 */
function Sandbox(broker)
{
  /**
   * @private
   * @type {h5.pubsub.Broker}
   */
  this.broker = broker;

  /**
   * @private
   * @type {object.<string, h5.pubsub.Subscription>}
   */
  this.subscriptions = {};

  /**
   * @private
   * @type {function(h5.pubsub.Subscription)}
   */
  this.removeSubscription = this.removeSubscription.bind(this);
}

Sandbox.prototype.destroy = function()
{
  var subscriptions = this.subscriptions;

  if (subscriptions !== null)
  {
    Object.keys(subscriptions).forEach(function(id)
    {
      subscriptions[id].cancel();
    });
  }

  this.subscriptions = null;
  this.broker = null;
};

/**
 * @returns {h5.pubsub.Sandbox}
 */
Sandbox.prototype.sandbox = function()
{
  return new Sandbox(this);
};

/**
 * @param {string} topic
 * @param {*} [message]
 * @param {object} [meta]
 * @returns {h5.pubsub.Sandbox}
 */
Sandbox.prototype.publish = function(topic, message, meta)
{
  this.broker.publish(topic, message, meta);

  return this;
};

/**
 * @param {string} topic
 * @param {function(string, *, object)} [onMessage]
 * @returns {h5.pubsub.Subscription}
 */
Sandbox.prototype.subscribe = function(topic, onMessage)
{
  var subscription = this.broker.subscribe(topic, onMessage);

  subscription.on('cancel', this.removeSubscription);

  this.subscriptions[subscription.getId()] = subscription;

  return subscription;
};

/**
 * @param {string} topic
 * @returns {h5.pubsub.Sandbox}
 */
Sandbox.prototype.unsubscribe = function(topic)
{
  var ids = [];
  var subscriptions = this.subscriptions;

  for (var id in subscriptions)
  {
    if (subscriptions.hasOwnProperty(id)
      && subscriptions[id].getTopic() === topic)
    {
      ids.push(id);
    }
  }

  for (var i = 0, l = ids.length; i < l; ++i)
  {
    subscriptions[ids[i]].cancel();
  }

  return this;
};

/**
 * @private
 * @param {h5.pubsub.Subscription} subscription
 */
Sandbox.prototype.removeSubscription = function(subscription)
{
  delete this.subscriptions[subscription.getId()];
};