text:
package org.apache.maven.bridge;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
import org.apache.maven.artifact.repository.Authentication;
import org.apache.maven.artifact.repository.MavenArtifactRepository;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout2;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.apache.maven.model.Plugin;
import org.apache.maven.repository.Proxy;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.settings.Mirror;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.StringUtils;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.AuthenticationContext;
import org.eclipse.aether.repository.AuthenticationSelector;
import org.eclipse.aether.repository.ProxySelector;
import org.eclipse.aether.repository.RemoteRepository;

/**
 * @author Jason van Zyl
 */
@Component( role = MavenRepositorySystem.class, hint = "default" )
public class MavenRepositorySystem
{
    @Requirement
    private ArtifactHandlerManager artifactHandlerManager;

    @Requirement( role = ArtifactRepositoryLayout.class )
    private Map<String, ArtifactRepositoryLayout> layouts;

    // DefaultProjectBuilder
    public Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type )
    {
        return XcreateArtifact( groupId, artifactId, version, scope, type );
    }

    // DefaultProjectBuilder
    public Artifact createProjectArtifact( String groupId, String artifactId, String metaVersionId )
    {
        return XcreateProjectArtifact( groupId, artifactId, metaVersionId );
    }

    // DefaultProjectBuilder
    public Artifact createDependencyArtifact( Dependency d )
    {
        if ( d.getVersion() == null )
        {
            return null;
        }

        VersionRange versionRange;
        try
        {
            versionRange = VersionRange.createFromVersionSpec( d.getVersion() );
        }
        catch ( InvalidVersionSpecificationException e )
        {
            return null;
        }

        Artifact artifact =
            XcreateDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(),
                                                      d.getClassifier(), d.getScope(), d.isOptional() );

        if ( Artifact.SCOPE_SYSTEM.equals( d.getScope() ) && d.getSystemPath() != null )
        {
            artifact.setFile( new File( d.getSystemPath() ) );
        }

        if ( !d.getExclusions().isEmpty() )
        {
            List<String> exclusions = new ArrayList<>();

            for ( Exclusion exclusion : d.getExclusions() )
            {
                exclusions.add( exclusion.getGroupId() + ':' + exclusion.getArtifactId() );
            }

            artifact.setDependencyFilter( new ExcludesArtifactFilter( exclusions ) );
        }

        return artifact;
    }

    // DefaultProjectBuilder
    public Artifact createExtensionArtifact( String groupId, String artifactId, String version )
    {
        VersionRange versionRange;
        try
        {
            versionRange = VersionRange.createFromVersionSpec( version );
        }
        catch ( InvalidVersionSpecificationException e )
        {
            return null;
        }

        return XcreateExtensionArtifact( groupId, artifactId, versionRange );
    }

    // DefaultProjectBuilder
    public Artifact createParentArtifact( String groupId, String artifactId, String version )
    {
        return XcreateParentArtifact( groupId, artifactId, version );
    }

    // DefaultProjectBuilder
    public Artifact createPluginArtifact( Plugin plugin )
    {
        VersionRange versionRange;
        try
        {
            String version = plugin.getVersion();
            if ( StringUtils.isEmpty( version ) )
            {
                version = "RELEASE";
            }
            versionRange = VersionRange.createFromVersionSpec( version );
        }
        catch ( InvalidVersionSpecificationException e )
        {
            return null;
        }

        return XcreatePluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), versionRange );
    }

    public void injectMirror( List<ArtifactRepository> repositories, List<Mirror> mirrors )
    {
        if ( repositories != null && mirrors != null )
        {
            for ( ArtifactRepository repository : repositories )
            {
                Mirror mirror = getMirror( repository, mirrors );
                injectMirror( repository, mirror );
            }
        }
    }

    private Mirror getMirror( RepositorySystemSession session, ArtifactRepository repository )
    {
        if ( session != null )
        {
            org.eclipse.aether.repository.MirrorSelector selector = session.getMirrorSelector();
            if ( selector != null )
            {
                RemoteRepository repo = selector.getMirror( RepositoryUtils.toRepo( repository ) );
                if ( repo != null )
                {
                    Mirror mirror = new Mirror();
                    mirror.setId( repo.getId() );
                    mirror.setUrl( repo.getUrl() );
                    mirror.setLayout( repo.getContentType() );
                    return mirror;
                }
            }
        }
        return null;
    }

    public void injectMirror( RepositorySystemSession session, List<ArtifactRepository> repositories )
    {
        if ( repositories != null && session != null )
        {
            for ( ArtifactRepository repository : repositories )
            {
                Mirror mirror = getMirror( session, repository );
                injectMirror( repository, mirror );
            }
        }
    }

    private void injectMirror( ArtifactRepository repository, Mirror mirror )
    {
        if ( mirror != null )
        {
            ArtifactRepository original =
                createArtifactRepository( repository.getId(), repository.getUrl(), repository.getLayout(),
                                          repository.getSnapshots(), repository.getReleases() );

            repository.setMirroredRepositories( Collections.singletonList( original ) );

            repository.setId( mirror.getId() );
            repository.setUrl( mirror.getUrl() );

            if ( StringUtils.isNotEmpty( mirror.getLayout() ) )
            {
                repository.setLayout( getLayout( mirror.getLayout() ) );
            }
        }
    }

    private Authentication getAuthentication( RepositorySystemSession session, ArtifactRepository repository )
    {
        if ( session != null )
        {
            AuthenticationSelector selector = session.getAuthenticationSelector();
            if ( selector != null )
            {
                RemoteRepository repo = RepositoryUtils.toRepo( repository );
                org.eclipse.aether.repository.Authentication auth = selector.getAuthentication( repo );
                if ( auth != null )
                {
                    repo = new RemoteRepository.Builder( repo ).setAuthentication( auth ).build();
                    AuthenticationContext authCtx = AuthenticationContext.forRepository( session, repo );
                    Authentication result =
                        new Authentication( authCtx.get( AuthenticationContext.USERNAME ),
                                            authCtx.get( AuthenticationContext.PASSWORD ) );
                    result.setPrivateKey( authCtx.get( AuthenticationContext.PRIVATE_KEY_PATH ) );
                    result.setPassphrase( authCtx.get( AuthenticationContext.PRIVATE_KEY_PASSPHRASE ) );
                    authCtx.close();
                    return result;
                }
            }
        }
        return null;
    }

    public void injectAuthentication( RepositorySystemSession session, List<ArtifactRepository> repositories )
    {
        if ( repositories != null && session != null )
        {
            for ( ArtifactRepository repository : repositories )
            {
                repository.setAuthentication( getAuthentication( session, repository ) );
            }
        }
    }

    private Proxy getProxy( RepositorySystemSession session, ArtifactRepository repository )
    {
        if ( session != null )
        {
            ProxySelector selector = session.getProxySelector();
            if ( selector != null )
            {
                RemoteRepository repo = RepositoryUtils.toRepo( repository );
                org.eclipse.aether.repository.Proxy proxy = selector.getProxy( repo );
                if ( proxy != null )
                {
                    Proxy p = new Proxy();
                    p.setHost( proxy.getHost() );
                    p.setProtocol( proxy.getType() );
                    p.setPort( proxy.getPort() );
                    if ( proxy.getAuthentication() != null )
                    {
                        repo = new RemoteRepository.Builder( repo ).setProxy( proxy ).build();
                        AuthenticationContext authCtx = AuthenticationContext.forProxy( session, repo );
                        p.setUserName( authCtx.get( AuthenticationContext.USERNAME ) );
                        p.setPassword( authCtx.get( AuthenticationContext.PASSWORD ) );
                        p.setNtlmDomain( authCtx.get( AuthenticationContext.NTLM_DOMAIN ) );
                        p.setNtlmHost( authCtx.get( AuthenticationContext.NTLM_WORKSTATION ) );
                        authCtx.close();
                    }
                    return p;
                }
            }
        }
        return null;
    }

    public void injectProxy( RepositorySystemSession session, List<ArtifactRepository> repositories )
    {
        if ( repositories != null && session != null )
        {
            for ( ArtifactRepository repository : repositories )
            {
                repository.setProxy( getProxy( session, repository ) );
            }
        }
    }

    private ArtifactRepositoryLayout getLayout( String id )
    {
        ArtifactRepositoryLayout layout = layouts.get( id );

        return layout;
    }

    //
    // Taken from LegacyRepositorySystem
    //

    public static org.apache.maven.model.Repository fromSettingsRepository( org.apache.maven.settings.Repository
                                                                            settingsRepository )
    {
        org.apache.maven.model.Repository modelRepository = new org.apache.maven.model.Repository();
        modelRepository.setId( settingsRepository.getId() );
        modelRepository.setLayout( settingsRepository.getLayout() );
        modelRepository.setName( settingsRepository.getName() );
        modelRepository.setUrl( settingsRepository.getUrl() );
        modelRepository.setReleases( fromSettingsRepositoryPolicy( settingsRepository.getReleases() ) );
        modelRepository.setSnapshots( fromSettingsRepositoryPolicy( settingsRepository.getSnapshots() ) );
        return modelRepository;
    }

    public static org.apache.maven.model.RepositoryPolicy fromSettingsRepositoryPolicy(
                                                 org.apache.maven.settings.RepositoryPolicy settingsRepositoryPolicy )
    {
        org.apache.maven.model.RepositoryPolicy modelRepositoryPolicy = new org.apache.maven.model.RepositoryPolicy();
        if ( settingsRepositoryPolicy != null )
        {
            modelRepositoryPolicy.setEnabled( settingsRepositoryPolicy.isEnabled() );
            modelRepositoryPolicy.setUpdatePolicy( settingsRepositoryPolicy.getUpdatePolicy() );
            modelRepositoryPolicy.setChecksumPolicy( settingsRepositoryPolicy.getChecksumPolicy() );
        }
        return modelRepositoryPolicy;
    }

    public static ArtifactRepository buildArtifactRepository( org.apache.maven.settings.Repository repo )
        throws InvalidRepositoryException
    {
        return buildArtifactRepository( fromSettingsRepository( repo ) );
    }

    public static ArtifactRepository buildArtifactRepository( org.apache.maven.model.Repository repo )
        throws InvalidRepositoryException
    {
        if ( repo != null )
        {
            String id = repo.getId();

            if ( StringUtils.isEmpty( id ) )
            {
                throw new InvalidRepositoryException( "Repository identifier missing", "" );
            }

            String url = repo.getUrl();

            if ( StringUtils.isEmpty( url ) )
            {
                throw new InvalidRepositoryException( "URL missing for repository " + id, id );
            }

            ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy( repo.getSnapshots() );

            ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy( repo.getReleases() );

            ArtifactRepositoryLayout layout = new DefaultRepositoryLayout();

            return createArtifactRepository( id, url, layout, snapshots, releases );
        }
        else
        {
            return null;
        }
    }

    public static ArtifactRepositoryPolicy buildArtifactRepositoryPolicy( org.apache.maven.model.RepositoryPolicy
                                                                          policy )
    {
        boolean enabled = true;

        String updatePolicy = null;

        String checksumPolicy = null;

        if ( policy != null )
        {
            enabled = policy.isEnabled();

            if ( policy.getUpdatePolicy() != null )
            {
                updatePolicy = policy.getUpdatePolicy();
            }
            if ( policy.getChecksumPolicy() != null )
            {
                checksumPolicy = policy.getChecksumPolicy();
            }
        }

        return new ArtifactRepositoryPolicy( enabled, updatePolicy, checksumPolicy );
    }

    public ArtifactRepository createArtifactRepository( String id, String url, String layoutId,
                                                        ArtifactRepositoryPolicy snapshots,
                                                        ArtifactRepositoryPolicy releases )
        throws Exception
    {
        ArtifactRepositoryLayout layout = layouts.get( layoutId );

        checkLayout( id, layoutId, layout );

        return createArtifactRepository( id, url, layout, snapshots, releases );
    }

    private void checkLayout( String repositoryId, String layoutId, ArtifactRepositoryLayout layout )
        throws Exception
    {
        if ( layout == null )
        {
            throw new Exception( String.format( "Cannot find ArtifactRepositoryLayout instance for: %s %s", layoutId,
                                                repositoryId ) );
        }
    }

    public static ArtifactRepository createArtifactRepository( String id, String url,
                                                        ArtifactRepositoryLayout repositoryLayout,
                                                        ArtifactRepositoryPolicy snapshots,
                                                        ArtifactRepositoryPolicy releases )
    {
        if ( snapshots == null )
        {
            snapshots = new ArtifactRepositoryPolicy();
        }

        if ( releases == null )
        {
            releases = new ArtifactRepositoryPolicy();
        }

        ArtifactRepository repository;
        if ( repositoryLayout instanceof ArtifactRepositoryLayout2 )
        {
            repository =
                ( (ArtifactRepositoryLayout2) repositoryLayout ).newMavenArtifactRepository( id, url, snapshots,
                                                                                releases );
        }
        else
        {
            repository = new MavenArtifactRepository( id, url, repositoryLayout, snapshots, releases );
        }

        return repository;
    }

    // ArtifactFactory
    private Artifact XcreateArtifact( String groupId, String artifactId, String version, String scope, String type )
    {
        return XcreateArtifact( groupId, artifactId, version, scope, type, null, null );
    }

    private Artifact XcreateDependencyArtifact( String groupId, String artifactId, VersionRange versionRange,
                                              String type, String classifier, String scope, boolean optional )
    {
        return XcreateArtifact( groupId, artifactId, versionRange, type, classifier, scope, null, optional );
    }

    private Artifact XcreateProjectArtifact( String groupId, String artifactId, String version )
    {
        return XcreateProjectArtifact( groupId, artifactId, version, null );
    }

    private Artifact XcreateParentArtifact( String groupId, String artifactId, String version )
    {
        return XcreateProjectArtifact( groupId, artifactId, version );
    }

    private Artifact XcreatePluginArtifact( String groupId, String artifactId, VersionRange versionRange )
    {
        return XcreateArtifact( groupId, artifactId, versionRange, "maven-plugin", null, Artifact.SCOPE_RUNTIME, null );
    }

    private Artifact XcreateProjectArtifact( String groupId, String artifactId, String version, String scope )
    {
        return XcreateArtifact( groupId, artifactId, version, scope, "pom" );
    }

    private Artifact XcreateExtensionArtifact( String groupId, String artifactId, VersionRange versionRange )
    {
        return XcreateArtifact( groupId, artifactId, versionRange, "jar", null, Artifact.SCOPE_RUNTIME, null );
    }

    private Artifact XcreateArtifact( String groupId, String artifactId, String version, String scope, String type,
                                     String classifier, String inheritedScope )
    {
        VersionRange versionRange = null;
        if ( version != null )
        {
            versionRange = VersionRange.createFromVersion( version );
        }
        return XcreateArtifact( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope );
    }

    private Artifact XcreateArtifact( String groupId, String artifactId, VersionRange versionRange, String type,
                                     String classifier, String scope, String inheritedScope )
    {
        return XcreateArtifact( groupId, artifactId, versionRange, type, classifier, scope, inheritedScope, false );
    }

    private Artifact XcreateArtifact( String groupId, String artifactId, VersionRange versionRange, String type,
                                     String classifier, String scope, String inheritedScope, boolean optional )
    {
        String desiredScope = Artifact.SCOPE_RUNTIME;

        if ( inheritedScope == null )
        {
            desiredScope = scope;
        }
        else if ( Artifact.SCOPE_TEST.equals( scope ) || Artifact.SCOPE_PROVIDED.equals( scope ) )
        {
            return null;
        }
        else if ( Artifact.SCOPE_COMPILE.equals( scope ) && Artifact.SCOPE_COMPILE.equals( inheritedScope ) )
        {
            // added to retain compile artifactScope. Remove if you want compile inherited as runtime
            desiredScope = Artifact.SCOPE_COMPILE;
        }

        if ( Artifact.SCOPE_TEST.equals( inheritedScope ) )
        {
            desiredScope = Artifact.SCOPE_TEST;
        }

        if ( Artifact.SCOPE_PROVIDED.equals( inheritedScope ) )
        {
            desiredScope = Artifact.SCOPE_PROVIDED;
        }

        if ( Artifact.SCOPE_SYSTEM.equals( scope ) )
        {
            // system scopes come through unchanged...
            desiredScope = Artifact.SCOPE_SYSTEM;
        }

        ArtifactHandler handler = artifactHandlerManager.getArtifactHandler( type );

        return new DefaultArtifact( groupId, artifactId, versionRange, desiredScope, type, classifier, handler,
                                    optional );
    }

    //
    // Code taken from LegacyRepositorySystem
    //
    /**
     * @deprecation As of 3.4, Maven no longer falls back to a hard-coded default repository with identifier
     * {@code central} if such a repository is not provided in the settings or the POM.
     */
    @Deprecated
    public ArtifactRepository createDefaultRemoteRepository( MavenExecutionRequest request )
        throws Exception
    {
        throw new UnsupportedOperationException();
    }

    public ArtifactRepository createRepository( String url, String repositoryId, boolean releases,
                                                 String releaseUpdates, boolean snapshots, String snapshotUpdates,
                                                 String checksumPolicy ) throws Exception
    {
        ArtifactRepositoryPolicy snapshotsPolicy =
            new ArtifactRepositoryPolicy( snapshots, snapshotUpdates, checksumPolicy );

        ArtifactRepositoryPolicy releasesPolicy =
            new ArtifactRepositoryPolicy( releases, releaseUpdates, checksumPolicy );

        return createArtifactRepository( repositoryId, url, "default", snapshotsPolicy, releasesPolicy );
    }

    public Set<String> getRepoIds( List<ArtifactRepository> repositories )
    {
        Set<String> repoIds = new HashSet<>();

        if ( repositories != null )
        {
            for ( ArtifactRepository repository : repositories )
            {
                repoIds.add( repository.getId() );
            }
        }

        return repoIds;
    }

    public ArtifactRepository createLocalRepository( MavenExecutionRequest request, File localRepository )
        throws Exception
    {
        return createRepository( "file://" + localRepository.toURI().getRawPath(),
                                 RepositorySystem.DEFAULT_LOCAL_REPO_ID, true,
                                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, true,
                                 ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
                                 ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE );
    }

    private static final String WILDCARD = "*";

    private static final String EXTERNAL_WILDCARD = "external:*";

    public static Mirror getMirror( ArtifactRepository repository, List<Mirror> mirrors )
    {
        String repoId = repository.getId();

        if ( repoId != null && mirrors != null )
        {
            for ( Mirror mirror : mirrors )
            {
                if ( repoId.equals( mirror.getMirrorOf() ) && matchesLayout( repository, mirror ) )
                {
                    return mirror;
                }
            }

            for ( Mirror mirror : mirrors )
            {
                if ( matchPattern( repository, mirror.getMirrorOf() ) && matchesLayout( repository, mirror ) )
                {
                    return mirror;
                }
            }
        }

        return null;
    }

    /**
     * This method checks if the pattern matches the originalRepository. Valid patterns: * = everything external:* =
     * everything not on the localhost and not file based. repo,repo1 = repo or repo1 *,!repo1 = everything except repo1
     *
     * @param originalRepository to compare for a match.
     * @param pattern used for match. Currently only '*' is supported.
     * @return true if the repository is a match to this pattern.
     */
    static boolean matchPattern( ArtifactRepository originalRepository, String pattern )
    {
        boolean result = false;
        String originalId = originalRepository.getId();

        // simple checks first to short circuit processing below.
        if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) )
        {
            result = true;
        }
        else
        {
            // process the list
            String[] repos = pattern.split( "," );
            for ( String repo : repos )
            {
                // see if this is a negative match
                if ( repo.length() > 1 && repo.startsWith( "!" ) )
                {
                    if ( repo.substring( 1 ).equals( originalId ) )
                    {
                        // explicitly exclude. Set result and stop processing.
                        result = false;
                        break;
                    }
                }
                // check for exact match
                else if ( repo.equals( originalId ) )
                {
                    result = true;
                    break;
                }
                // check for external:*
                else if ( EXTERNAL_WILDCARD.equals( repo ) && isExternalRepo( originalRepository ) )
                {
                    result = true;
                    // don't stop processing in case a future segment explicitly excludes this repo
                }
                else if ( WILDCARD.equals( repo ) )
                {
                    result = true;
                    // don't stop processing in case a future segment explicitly excludes this repo
                }
            }
        }
        return result;
    }

    /**
     * Checks the URL to see if this repository refers to an external repository
     *
     * @param originalRepository
     * @return true if external.
     */
    static boolean isExternalRepo( ArtifactRepository originalRepository )
    {
        try
        {
            URL url = new URL( originalRepository.getUrl() );
            return !( url.getHost().equals( "localhost" ) || url.getHost().equals( "127.0.0.1" )
                            || url.getProtocol().equals( "file" ) );
        }
        catch ( MalformedURLException e )
        {
            // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
            return false;
        }
    }

    static boolean matchesLayout( ArtifactRepository repository, Mirror mirror )
    {
        return matchesLayout( RepositoryUtils.getLayout( repository ), mirror.getMirrorOfLayouts() );
    }

    /**
     * Checks whether the layouts configured for a mirror match with the layout of the repository.
     *
     * @param repoLayout The layout of the repository, may be {@code null}.
     * @param mirrorLayout The layouts supported by the mirror, may be {@code null}.
     * @return {@code true} if the layouts associated with the mirror match the layout of the original repository,
     *         {@code false} otherwise.
     */
    static boolean matchesLayout( String repoLayout, String mirrorLayout )
    {
        boolean result = false;

        // simple checks first to short circuit processing below.
        if ( StringUtils.isEmpty( mirrorLayout ) || WILDCARD.equals( mirrorLayout ) )
        {
            result = true;
        }
        else if ( mirrorLayout.equals( repoLayout ) )
        {
            result = true;
        }
        else
        {
            // process the list
            String[] layouts = mirrorLayout.split( "," );
            for ( String layout : layouts )
            {
                // see if this is a negative match
                if ( layout.length() > 1 && layout.startsWith( "!" ) )
                {
                    if ( layout.substring( 1 ).equals( repoLayout ) )
                    {
                        // explicitly exclude. Set result and stop processing.
                        result = false;
                        break;
                    }
                }
                // check for exact match
                else if ( layout.equals( repoLayout ) )
                {
                    result = true;
                    break;
                }
                else if ( WILDCARD.equals( layout ) )
                {
                    result = true;
                    // don't stop processing in case a future segment explicitly excludes this repo
                }
            }
        }

        return result;
    }
}


text:
import React, {Fragment} from 'react'
import {compose} from 'redux'
import {connect} from 'react-redux'
import {withDataProviders} from 'data-provider'
import {chunk} from 'lodash'
import Info from '../../shared/Info/Info'
import {entityDetailProvider} from '../../../dataProviders/sharedDataProviders'
import {entityDetailsSelector} from '../../../selectors/index'
import {MAX_ENTITY_REQUEST_COUNT} from '../../../constants'
import type {NewEntityDetail} from '../../../state'
import type {ObjectMap} from '../../../types/commonTypes'
import './InfoLoader.css'

type Props = {
  eids: number[],
  data: ObjectMap<NewEntityDetail>,
}

const InfoLoader = ({data, eids}: Props) => (
  <Fragment>
    {eids.map((eid) => (

        <Info data={data[eid]} />

    ))}
  </Fragment>
)

export default compose(
  withDataProviders(({eids}: Props) =>
    chunk(eids, MAX_ENTITY_REQUEST_COUNT).map((ids) => entityDetailProvider(ids))
  ),
  connect((state, {eids}) => ({
    data: entityDetailsSelector(state, eids),
  }))
)(InfoLoader)

redpajama_set_name: RedPajamaGithub


text:
module SocialProfile
  module Providers
    class Twitch < Base
      def picture_url
        info 'image'
      end

      def profile_url
        info('urls')['Twitch']
      end
    end
  end
end


text:
package org.wso2.carbon.appmgt.gateway;

import org.apache.axis2.Constants;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.http.HttpHeaders;
import org.apache.synapse.MessageContext;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
import org.apache.synapse.rest.RESTConstants;

import java.util.HashMap;
import java.util.Map;

public class TestUtils {

    public static MessageContext getMessageContext(String context, String version, String apiKey) {
        MessageContext synCtx = getMessageContext(context, version);
        org.apache.axis2.context.MessageContext axisMsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
        Map<String,String> headers = new HashMap<String, String>();
        headers.put(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);
        axisMsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers);
        return synCtx;
    }

    public static MessageContext getMessageContext(String context, String version) {
        SynapseConfiguration synCfg = new SynapseConfiguration();
        org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
        axisMsgCtx.setIncomingTransportName("http");
        axisMsgCtx.setProperty(Constants.Configuration.TRANSPORT_IN_URL, "/test/1.0.0/search.atom");
        AxisConfiguration axisConfig = new AxisConfiguration();
        ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig);
        MessageContext synCtx = new Axis2MessageContext(axisMsgCtx, synCfg,
                new Axis2SynapseEnvironment(cfgCtx, synCfg));
        synCtx.setProperty(RESTConstants.REST_API_CONTEXT, context);
        synCtx.setProperty(RESTConstants.SYNAPSE_REST_API_VERSION, version);
        return synCtx;
    }

}


text:
set -o errexit
set -o nounset
set -o pipefail

FRAKTI_ROOT=$(readlink -f $(dirname "${BASH_SOURCE}")/../..)
source "${FRAKTI_ROOT}/hack/lib/init.sh"

frakti::golang::build_binaries "$@"


text:
Perfpiece
=========

Perfpiece is a tool for measuring the performance of Lisp code, not
unlike the standard CL:TIME.

Features
--------

Here are its main features:

1. Lispy interface to [PAPI (Performance Application Programming
   Interface)][1]. PAPI is a library that enables access modern CPU's
   hardware counters. This allows us to measure several events such as
   processor cycles, cache misses, number of floating-point
   instructions, and almost two hundred other events. Perfpiece
   dynamically inspects the current platform's supported events at
   runtime and enables the user to inspect this list and measure these
   events. We also use this library to measure real (wall-clock) time
   and user (virtual) time.

2. Support for other non-PAPI events such as the number of GC runs,
   CPU usage, and operating system resource usage (via the getrusage()
   system call).

3. Transparent support for multi-threaded programs. It includes a
   helper C library that when loaded through the POSIX LD_PRELOAD
   mechanism will preempt pthread creation/termination calls and allow
   for the individual measurement of events across threads created
   during a measurement session. This includes both Lisp threads as
   well as threads created by C code. This is rather limited at the
   moment; only real/user/cpu time is measured for new threads.

4. Segregation of measurements between mutator and GC.

5. Support for sampling. Perfpiece can repeat a given measurement a
   number of times then calculate and report basic statistic analysis:
   minimums, maximums, geometric means, and standard deviations for
   each measured event.

Usage
-----

### ascertain

The simplest way to interact with this library is through the
ascertain macro, which works very much like cl:time. The
following example shows the default events measured for a very simple
arithmetic form:

PERFPIECE> (ascertain (+ 1 1))

                                          non-GC            GC         Total
────────────────────────────────────────────────────────────────────────────
                     Total cycles:         8,343             0         8,343
           Instructions completed:           481             0           481
        Level 2 data cache misses:            78             0            78
 Level 2 instruction cache misses:            24             0            24
                         GC count:             -             -             0
     Involuntary context-switches:             0             0             0
       Voluntary context-switches:             1             0             1
                      Page faults:             0             0             0
                    Page reclaims:             6             0             6
                      System time:             0             0             0
                        CPU usage:       100.00%             -       100.00%
                        User time:       6.00 µs             0       6.00 µs
                        Real time:        613 ns             0        613 ns

0 new threads were spawned

2 ; printed result of (+ 1 1)

Having loaded the helper library using LD_PRELOAD, we can
measure multi-threaded code:

PERFPIECE> (ascertain (loop repeat 2 do
                        (sb-thread:join-thread
                         (sb-thread:make-thread (lambda () (sleep 0.5)))))
                      :events '(:real-time :user-time :cpu-usage))

                                          non-GC            GC         Total
────────────────────────────────────────────────────────────────────────────
                        CPU usage:         0.02%             -         0.02%
                        User time:     206.00 µs             0     206.00 µs
                        Real time:       1.335 s             0       1.335 s

2 new threads were spawned
  #0 real: 667.54 ms, user: 101.00 µs, cpu: 0.02%
  #1 real: 667.60 ms, user: 144.00 µs, cpu: 0.02%

### sample

The other main function is sample. In the following
example, we're measuring FP instructions, invoking some code 10 times,
and aggregating measurements in several ways:

PERFPIECE> (sample (lambda () (* 2 pi)) :events '(:papi-fp-ins) :samples 10)

[Floating point instructions]       Min           Max          Mean     Stddev
──────────────────────────────────────────────────────────────────────────────
                   total:            35            36         35.60  ±  1.376%
                  non-gc:            35            36         35.60  ±  1.376%
                 gc-only:             0             0             0  ±  0.000%

sample's got a :report keyword argument that
you can use to get machine-readable results:

PERFPIECE> (sample (lambda () (* 2 pi)) :events '(:papi-fp-ins) :samples 10
                   :report nil)

((:PAPI-FP-INS :MIN (35 35 0)
               :MAX (38 38 0)
               :MEAN (184/5 184/5 0)
               :STDDEV (1.0770329 1.0770329 0.0)))

  [1]: http://icl.cs.utk.edu/papi/


text:
package net.linkedbuildingdata.rdf.data;

import com.hp.hpl.jena.rdf.model.RDFNode;

public interface IRdfNode {

	RdfNodeTypeEnum getRdfNodeType();

	RDFNode getNode();

	void setNode(RDFNode node);

}


text:
{id_beforeDot}

	{titolo}
	. - {biboEdition}
	 / {isbdRespEd}
	. - {isbdLuogo}
	: {isbdEditore}
	, {dataPubblicazioneSimple_formatItalian}
	. - {dctermsExtent}
	. - ({isbdIndicazione}
	; {isbdNserie})

note: {skosNote}

note editoriali: {skosEditorialNote}

sito web dell'editore: {rivista}


text:
var gulp = require('gulp');

var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var clean = require('gulp-clean');

var fs = require('fs');
var header  = require('gulp-header');

var getCopyright = function(){
  return fs.readFileSync('./copyright.js');
};

gulp.task('slider_clean',function(){
  return gulp.src(['./dist/slider.min.js'],{read:false})
        .pipe(clean({force:true}));
});

gulp.task('slider_js',['slider_clean'],function(){
  return gulp.src(['./js/slider.js'])
        .pipe(rename({suffix:'.min'}))
        .pipe(uglify())
        .pipe(header(getCopyright()))
        .pipe(gulp.dest('./dist'));
});

gulp.task('default',['slider_js']);


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.14: http://docutils.sourceforge.net/" />
<title>Mathematics</title>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />

Mathematics

Docutils supports inline math with the prefix or postfix <tt class="docutils literal">:math:</tt>
role specificator, <tt class="math">n! + \sin(x_n^2)</tt> and <tt class="math">A_\text{c} =
\frac{\pi}{4} d^2</tt>, as well as displayed math via the
math directive:

f(\epsilon) = \frac{1}{1 + \exp\left(\frac{\varepsilon}{k_\text{B}T}\right)}

Content may start on the first line of the directive, e.g.

N = \frac{\text{number of apples}}{7}

Equations can be labeled with a reference name using the <tt class="docutils literal">:name:</tt> option.
See eq:M and eq:schrödinger below.

The determinant of the matrix

\mathbf{M} = \left(\begin{matrix}a&b\\c&d\end{matrix}\right)

is <tt class="math">|\mathbf{M}| = ad - bc</tt>.

More than one display math block can be put in one math directive.
For example, the following sum and integral with limits:

\int_0^1 x^n dx = \frac{1}{n + 1}

\sum_{n=1}^m n = \frac{m(m+1)}{2}

LaTeX-supported Unicode math symbols can be used in math roles and
directives:

The Schrödinger equation

i\hbar \frac{\partial }{\partial t}\Psi  = \hat{H}\Psi ,

with the wave function <tt class="math">\Psi </tt>, describes how the quantum state of a
physical system changes in time.

Math-Accents:

<colgroup>
<col width="33%" />
<col width="33%" />
<col width="33%" />
</colgroup>

<tt class="math">\acute{a}</tt>      <tt class="docutils literal">\acute{a}</tt>
<tt class="math">\dot{t}</tt>        <tt class="docutils literal">\dot{t}</tt>
<tt class="math">\hat{\gamma}</tt>   <tt class="docutils literal">\hat{\gamma}</tt>

<tt class="math">\grave{a}</tt>      <tt class="docutils literal">\grave{a}</tt>
<tt class="math">\ddot{t}</tt>       <tt class="docutils literal">\ddot{t}</tt>
<tt class="math">\tilde{\alpha}</tt> <tt class="docutils literal">\tilde{\alpha}</tt>

<tt class="math">\breve{x}</tt>      <tt class="docutils literal">\breve{x}</tt>
<tt class="math">\dddot{t}</tt>      <tt class="docutils literal">\dddot{t}</tt>
<tt class="math">\vec{\imath}</tt>   <tt class="docutils literal">\vec{\imath}</tt>

<tt class="math">\check{a}</tt>      <tt class="docutils literal">\check{a}</tt>
<tt class="math">\bar{a}</tt>        <tt class="docutils literal">\bar{a}</tt>
<tt class="math">\vec{R}</tt>        <tt class="docutils literal">\vec{R}</tt>

Modulation Transfer Function:

\text{MTF} = \left|\frac{\mathcal{F}\{s(x)\}}
                        {\mathcal{F}\{ s(x)\} |_{\omega _{x}=0}}\right|
           = \mathrm{abs}\left(\frac
                 {\int _{-\infty }^{\infty }s(x) \mathrm{e}^{\mathrm{i}\omega _{x}x}\mathrm{d}{x}}
                 {\int _{-\infty }^{\infty }s(x)\mathrm{d}{x}}
             \right).

Math split over two lines: If a double backslash is detected outside a
<tt class="docutils literal">\begin{...} \end{...}</tt> pair, the math code is wrapped in an AMSmath
<tt class="docutils literal">align</tt> environment:

s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\
                    & = \int  s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x'

Cases ("manually", with <tt class="docutils literal">matrix</tt> environment):

\mathrm{sgn}(x) = \left\{\begin{matrix}
                    -1 & x<0\\
                    1 & x>0
                  \end{matrix}\right.

Cases with the AMSmath <tt class="docutils literal">cases</tt> environment (not (yet) supported by
HTML writers with <tt class="docutils literal">--math-output=MathML</tt>):

\mathrm{sgn}(x) = \begin{cases}
                    -1 & x<0\\
                     1 & x>0
                  \end{cases}


text:
class GURL;

namespace favicon {

class FaviconService;

// Request a favicon from |favicon_service| for the page at |page_url|.
// |callback| is run when the the favicon has been fetched. If |type| is:
// - favicon_base::FAVICON, the returned gfx::Image is a multi-resolution image
//   of gfx::kFaviconSize DIP width and height (the data from the cache is
//   resized if need be),
// - otherwise, the returned gfx::Image is a single-resolution image with the
//   largest bitmap in the cache for |page_url| and |type|.
base::CancelableTaskTracker::TaskId GetFaviconImageForPageURL(
    FaviconService* favicon_service,
    const GURL& page_url,
    favicon_base::IconType type,
    const favicon_base::FaviconImageCallback& callback,
    base::CancelableTaskTracker* tracker);

}  // namespace favicon

#endif  // COMPONENTS_FAVICON_CORE_FAVICON_UTIL_H_


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Fire success event - Exception thrown</title>
<link rel="help" href="https://w3c.github.io/IndexedDB/#fire-success-event">
<script src=/resources/testharness.js></script>
<script src=/resources/testharnessreport.js></script>
<script src=resources/support.js></script>
<script>
setup({allow_uncaught_exception:true});

function fire_success_event_test(func, description) {
  indexeddb_test(
    (t, db) => {
      db.createObjectStore('s');
    },
    (t, db) => {
      const tx = db.transaction('s', 'readonly', {durability: 'relaxed'});
      tx.oncomplete = t.unreached_func('transaction should abort');
      const store = tx.objectStore('s');
      const request = store.get(0);
      func(t, db, tx, request);
      tx.addEventListener('abort', t.step_func_done(() => {
        assert_equals(tx.error.name, 'AbortError');
      }));
    },
    description);
}

fire_success_event_test((t, db, tx, request) => {
  request.onsuccess = () => {
    throw Error();
  };
}, 'Exception in success event handler on request');

fire_success_event_test((t, db, tx, request) => {
  request.addEventListener('success', () => {
    throw Error();
  });
}, 'Exception in success event listener on request');

fire_success_event_test((t, db, tx, request) => {
  request.addEventListener('success', {
    get handleEvent() {
      throw new Error();
    },
  });
}, 'Exception in success event listener ("handleEvent" lookup) on request');

fire_success_event_test((t, db, tx, request) => {
  request.addEventListener('success', {
    handleEvent: null,
  });
}, 'Exception in success event listener (non-callable "handleEvent") on request');

fire_success_event_test((t, db, tx, request) => {
  request.addEventListener('success', () => {
    // no-op
  });
  request.addEventListener('success', () => {
    throw Error();
  });
}, 'Exception in second success event listener on request');

fire_success_event_test((t, db, tx, request) => {
  let second_listener_called = false;
  request.addEventListener('success', () => {
    throw Error();
  });
  request.addEventListener('success', t.step_func(() => {
    second_listener_called = true;
    assert_true(is_transaction_active(tx, 's'),
                'Transaction should be active until dispatch completes');
  }));
  tx.addEventListener('abort', t.step_func(() => {
    assert_true(second_listener_called);
  }));
}, 'Exception in first success event listener, tx active in second');

</script>


text:
package org.openrtb.dsp.intf.model;

import java.util.HashMap;
import java.util.Map;

import org.openrtb.common.api.BidRequest;

public class RTBRequestWrapper extends BidRequest {

	public RTBRequestWrapper() {
		super();
	}

	BidRequest request;
	RTBExchange exchange;
	final Map<String, RTBAdvertiser> advertisers = new HashMap<String, RTBAdvertiser>();
	long requestTimeoutMs;
	long offerTimeoutMs;
	private boolean isOfferTimerActive;

	public RTBRequestWrapper(BidRequest request) {

		super(request.getId(), request.getImp(), request.getSite(), request
				.getApp(), request.getDevice(), request.getUser(), request
				.getAt(), request.getTmax(), request.getWseat(), request
				.getAllimps(), request.getCur(), request.getBcat(), request
				.getBadv(), request.getExt());
		this.request = request;
	}

	public void setContext(RTBExchange exchange, Map<String, RTBAdvertiser> advertisers,
							long defaultRequestTO, long defaultOfferTO) {
		this.exchange = new RTBExchange(exchange);
		this.advertisers.clear();
		this.advertisers.putAll(advertisers);
		if (this.request.tmax == null) {
			this.requestTimeoutMs = defaultRequestTO;
		} else {
			this.requestTimeoutMs = this.request.tmax.longValue();
		}
		this.offerTimeoutMs = defaultOfferTO;
		this.isOfferTimerActive = false;
	}

	public BidRequest getRequest() {
		return request;
	}

	/**
	 * Builds a list of advertiser seat Ids that are allowed to bid on this
	 * request
	 *
	 * @param sspName
	 * @return seats
	 */
	public Map<String, String> getUnblockedSeats(String sspName) {
		Map<String, String> seats = new HashMap<String, String>();
		boolean checkWseat = ((this.request.getWseat() != null) && (!this.request
				.getWseat().isEmpty()));
		for (Map.Entry<String, RTBAdvertiser> a : this.advertisers.entrySet()) {
			// check if this is a private deal (checkWseat == true)
			CharSequence seatID = a.getValue().getSeat(sspName);
			// this.request.wseat.contains(seatID));
			/**
			 * if (checkWseat && !request.getWseat().contains(seatID)) {
			 *	 break;
			 * // yes its a private deal, but this adv is not part of it }
			 **/

			if (this.request.getBadv() != null) {
				// now check for blocked advertisers
				for (CharSequence badv : this.request.getBadv()) {

					if (badv.equals(a.getKey())) {
						break; // this advertiser is blocked for this request
					}
				}
			}
			// now check for blocked categories
			for (String acat : a.getValue().getCategories()) {
				if (this.request.getBcat() != null) {
					for (CharSequence bcat : this.request.getBcat()) {
						if (!acat.equals(bcat.toString())) {
							break; // this advertiser belongs to a category that
									// is
									// blocked for this request
						}
					}
				}
			}

			// if all tests pass, add seat as an allowed seat to return
			seats.put(seatID.toString(), a.getValue().getLandingPage());
		}
		return seats;
	}

	public String getSSPName() {
		if (exchange != null) {
			return exchange.getOrgName();
		}
		return null;
	}

	public RTBAdvertiser getAdvertiser(String landingPage) {
		return advertisers.get(landingPage);
	}

	public void setRequestTO(long requestTO) {
		this.requestTimeoutMs = requestTO;
	}

	public long getRequestTO() {
		return this.requestTimeoutMs;
	}

	public long getOfferTO() {
		return this.offerTimeoutMs;
	}

	public void setOfferTimerActive(boolean trueOrFalse) {
		this.isOfferTimerActive = trueOrFalse;
	}

	public boolean isOfferTimerActive() {
		return isOfferTimerActive;
	}
}


text:
angular.module('hap').directive('hapControl', HapControl);

HapControl.$inject = ['$http', '$compile'];
function HapControl($http, $compile) {
    var templateCache = {};

    return {
        restrict: 'E',
        bindToController: {
            item: '='
        },
        controller: ControlController,
        controllerAs: "me",
        scope: true,
        link: function (scope, element, attributes, ctrl) {
            var template = templateCache[ctrl.item.type];
            if (!template) {
                template =
                    $http.get('/templates/controls/' + ctrl.item.type +'.html')
                        .then(function(resp) {return resp.data;});
                templateCache[ctrl.item.type] = template;
            }

            template.then(function (html) {
                var control = angular.element(html);
                if (ctrl.item.width) control.attr('flex', ctrl.item.width);
                element.replaceWith($compile(control)(scope));
            });

            ctrl.init();
        }
    };
}

ControlController.$inject = ['WebEvents'];
function ControlController(events) {

    this.buttonClick = function() {
        events.emit('button-click', {
            id: this.item.id
        });
    };

    this.switchChanged = function() {
        events.emit('switch-changed', {
            id: this.item.id,
            state: this.item.state
        });
    };

    this.init = function() {
        if (!this.item.formatted)
            this.item.formatted = this.item.value;
    };

    this.sliderChanged = function() {
        events.emit('slider-changed', {
            id: this.item.id,
            value: this.item.value
        });
    };
}


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

using Mono.Upnp.Control;

namespace Mono.Upnp.Internal
{
    class Map<TKey, TValue> : IMap<TKey, TValue>
    {
        readonly IDictionary<TKey, TValue> dictionary;

        protected IDictionary<TKey, TValue> Dictionary {
            get { return dictionary; }
        }

        public Map (IDictionary<TKey, TValue> dictionary)
        {
            this.dictionary = dictionary;
        }

        public int Count {
            get { return dictionary.Count; }
        }

        public bool ContainsKey (TKey key)
        {
            return dictionary.ContainsKey (key);
        }

        public TValue this[TKey key] {
            get { return dictionary[key]; }
        }

        public bool TryGetValue (TKey key, out TValue value)
        {
            return dictionary.TryGetValue (key, out value);
        }

        public IEnumerable<TKey> Keys {
            get { return dictionary.Keys; }
        }

        public IEnumerable<TValue> Values {
            get { return dictionary.Values; }
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
        {
            return dictionary.GetEnumerator ();
        }

        IEnumerator IEnumerable.GetEnumerator ()
        {
            return GetEnumerator ();
        }
    }
}


text:
package com.panzareon.spellcircles.spell.parts;

import com.panzareon.spellcircles.exception.MissingAuraException;
import com.panzareon.spellcircles.spell.SpellPart;
import com.panzareon.spellcircles.spell.SpellPartValue;
import com.panzareon.spellcircles.spell.SpellReturnTypes;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;

public class SpellPartPickupBlock extends SpellPart
{
    private final float AuraUse = 20f;

    @Override
    public String getSpellName()
    {
        return "RTUZVBUZTDR";
    }

    @Override
    public String getSpellId()
    {
        return "pickup_block";
    }

    @Override
    public int getNrOfChildren()
    {
        return 1;
    }

    @Override
    public SpellReturnTypes[] getReturnValueTypes()
    {
        return new SpellReturnTypes[]{SpellReturnTypes.ACTION};
    }

    @Override
    protected SpellPartValue cast(SpellPartValue[] childValues) throws MissingAuraException
    {
        int nr = childValues[0].getBlockLength();
        if(nr > 0)
        {
            Block block;
            BlockPos blockPos;
            IBlockState blockState;
            float blockHardness;
            EntityPlayer player = environ.getCaster();
            Vec3d castPos = environ.getCastPosition();
            float auraAdd;
            World world = player.getEntityWorld();

            for(int i = 0; i < nr; i++)
            {
                blockPos = childValues[0].getBlock(i);
                if(blockPos == null || world.isAirBlock(blockPos))
                    continue;
                blockState = world.getBlockState(blockPos);
                block = blockState.getBlock();
                blockHardness = block.getBlockHardness(blockState, world,blockPos);

                if(block.getHarvestLevel(blockState) <= environ.strength)
                {
                    auraAdd = (float) castPos.distanceTo(new Vec3d(blockPos));
                    if (environ.useAura((int) ((AuraUse + auraAdd) * blockHardness), environ.strength))
                    {

                        if (!world.isRemote && !world.restoringBlockSnapshots) // do not drop items while restoring blockstates, prevents item dupe
                        {
                            java.util.List<ItemStack> items = block.getDrops(world, blockPos, blockState, 0);
                            float chance = net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(items, world, blockPos, blockState, 0, 1.0f, false, player);

                            for (ItemStack item : items)
                            {
                                if (world.rand.nextFloat() <= chance)
                                {
                                    EntityItem entityItem = new EntityItem(world, blockPos.getX(), blockPos.getY(), blockPos.getZ(), item);
                                    entityItem.setNoPickupDelay();

                                    int hook = net.minecraftforge.event.ForgeEventFactory.onItemPickup(entityItem, player, item);
                                    if (hook < 0) continue;
                                    if (player.inventory.addItemStackToInventory(item))
                                    {
                                        player.onItemPickup(entityItem, item.stackSize);

                                        net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerItemPickupEvent(player, entityItem);
                                        world.playSound(null, entityItem.posX, entityItem.posY, entityItem.posZ, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.2F, ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
                                    }
                                    if (item.stackSize > 0)
                                        block.spawnAsEntity(world, blockPos, item);
                                }
                            }
                            world.destroyBlock(blockPos, false);
                        }

                    }
                    else
                    {
                        throw new MissingAuraException(this);
                    }
                }
            }
        }
        return new SpellPartValue();
    }

    @Override
    public SpellReturnTypes getChildType(int childId)
    {
        if(childId == 0)
        {
            return SpellReturnTypes.BLOCK;
        }
        return super.getChildType(childId);
    }
}


text:
package org.reasm.testhelpers;

import javax.annotation.concurrent.Immutable;

import org.reasm.Symbol;
import org.reasm.expressions.SymbolLookup;

/**
 * An implementation of {@link SymbolLookup} that fails when its {@link #getSymbol(String)} method is called.
 *
 * @author Francis Gagné
 */
@Immutable
public final class DummySymbolLookup implements SymbolLookup {

    /** A default instance of the {@link DummySymbolLookup} class. */
    public static final DummySymbolLookup DEFAULT = new DummySymbolLookup();

    @Override
    public final Symbol getSymbol(String name) {
        throw new AssertionError("Symbol lookup shouldn't be invoked in this test");
    }

}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Brand'
        db.create_table(u'_backend_api_brand', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('brand_name', self.gf('django.db.models.fields.CharField')(max_length=255, unique=True, null=True, blank=True)),
            ('brand_founded', self.gf('django.db.models.fields.IntegerField')(max_length=4, null=True)),
            ('brand_origin_city', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
            ('brand_origin_state', self.gf('django.db.models.fields.CharField')(max_length=2, null=True, blank=True)),
            ('brand_about_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
            ('brand_collection_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
            ('slug', self.gf('django.db.models.fields.SlugField')(max_length=255, unique=True, null=True, blank=True)),
            ('brand_logo', self.gf('cloudinary.models.CloudinaryField')(max_length=100, null=True, blank=True)),
            ('brand_feature_image', self.gf('cloudinary.models.CloudinaryField')(max_length=100, null=True, blank=True)),
            ('brand_about_image', self.gf('cloudinary.models.CloudinaryField')(max_length=100, null=True, blank=True)),
            ('brand_collection_image', self.gf('cloudinary.models.CloudinaryField')(max_length=100, null=True, blank=True)),
            ('brand_connect_image', self.gf('cloudinary.models.CloudinaryField')(max_length=100, null=True, blank=True)),
            ('brand_website_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True)),
            ('brand_email', self.gf('django.db.models.fields.EmailField')(max_length=75, null=True, blank=True)),
            ('brand_state', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('brand_location_state', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('brand_email_state', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('brand_website_state', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('menswear', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('womenswear', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('date_added', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
            ('last_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, null=True, blank=True)),
        ))
        db.send_create_signal(u'_backend_api', ['Brand'])

        # Adding model 'Product'
        db.create_table(u'_backend_api_product', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('product_name', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
            ('product_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
            ('product_price', self.gf('django.db.models.fields.DecimalField')(default='0.0', max_digits=30, decimal_places=2)),
            ('product_image', self.gf('cloudinary.models.CloudinaryField')(max_length=255, null=True, blank=True)),
            ('date_added', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
            ('last_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, null=True, blank=True)),
            ('brand', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['_backend_api.Brand'], null=True)),
        ))
        db.send_create_signal(u'_backend_api', ['Product'])

        # Adding model 'Location'
        db.create_table(u'_backend_api_location', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('brand_address', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
            ('brand_city', self.gf('django.db.models.fields.CharField')(max_length=50, null=True, blank=True)),
            ('brand_state', self.gf('django.db.models.fields.CharField')(max_length=2, null=True, blank=True)),
            ('brand', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['_backend_api.Brand'], null=True)),
        ))
        db.send_create_signal(u'_backend_api', ['Location'])

    def backwards(self, orm):
        # Deleting model 'Brand'
        db.delete_table(u'_backend_api_brand')

        # Deleting model 'Product'
        db.delete_table(u'_backend_api_product')

        # Deleting model 'Location'
        db.delete_table(u'_backend_api_location')

    models = {
        u'_backend_api.brand': {
            'Meta': {'object_name': 'Brand'},
            'brand_about_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'brand_about_image': ('cloudinary.models.CloudinaryField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'brand_collection_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'brand_collection_image': ('cloudinary.models.CloudinaryField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'brand_connect_image': ('cloudinary.models.CloudinaryField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'brand_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
            'brand_email_state': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'brand_feature_image': ('cloudinary.models.CloudinaryField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'brand_founded': ('django.db.models.fields.IntegerField', [], {'max_length': '4', 'null': 'True'}),
            'brand_location_state': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'brand_logo': ('cloudinary.models.CloudinaryField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'brand_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
            'brand_origin_city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'brand_origin_state': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
            'brand_state': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'brand_website_state': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'brand_website_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
            'menswear': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
            'womenswear': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
        },
        u'_backend_api.location': {
            'Meta': {'object_name': 'Location'},
            'brand': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['_backend_api.Brand']", 'null': 'True'}),
            'brand_address': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'brand_city': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'brand_state': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'_backend_api.product': {
            'Meta': {'object_name': 'Product'},
            'brand': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['_backend_api.Brand']", 'null': 'True'}),
            'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
            'product_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'product_image': ('cloudinary.models.CloudinaryField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'product_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'product_price': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '30', 'decimal_places': '2'})
        }
    }

    complete_apps = ['_backend_api']


text:
package lk.lab.vertx.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class VertxLabApplication {

	public static void main(String[] args) {
		SpringApplication.run(VertxLabApplication.class, args);
	}
}


text:
/**
 * @file AliEmcalTriggerPatchFinder.h
 * @date Oct. 23, 2015
 * @author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory
 */
#ifndef ALIEMCALTRIGGERPATCHFINDER_H
#define ALIEMCALTRIGGERPATCHFINDER_H
/* Copyright(c) 1998-2015, ALICE Experiment at CERN, All rights reserved. *
 * See cxx source for full Copyright notice                               */

#include <TObject.h>
#include <vector>

#include "AliEMCALTriggerRawPatch.h"

template<typename T> class AliEMCALTriggerDataGrid;
template<typename T> class AliEMCALTriggerAlgorithm;

/**
 * @class AliEmcalTriggerPatchFinder
 * @ingroup EMCALTriggerBase
 * @brief Steering class for patch finder
 *
 * This class steers the trigger patch finding by calling
 * the trigger algorithms assigned to the patch finder. Trigger
 * algorithms are added via the function AddTriggerAlgorithm.
 * Patches are found via the function FindPatches.
 */
template<typename T>
class AliEMCALTriggerPatchFinder : public TObject {
public:
  /**
   * Constructor
   */
  AliEMCALTriggerPatchFinder();
  /**
   * Destructor
   */
  virtual ~AliEMCALTriggerPatchFinder();

  /**
   * Add trigger algorithm to the trigger patch finder
   * @param trigger Trigger algorithm assigned to the patch finder
   */
  void AddTriggerAlgorithm(AliEMCALTriggerAlgorithm<T> *trigger) { fTriggerAlgorithms.push_back(trigger); }

  /**
   * Find trigger patches usin the grid of adc values. All trigger patch finders are called one after each other.
   * The result contains the vector of patches from all trigger algorithms. The trigger patches are sorted in energy.
   * @param[in] adc Data grid with ADC values
   * @param[in] offlineAdc Data grid with ADC values calculated from FEE energies
   * @return List of trigger patches found by all trigger algorithms assigned to this trigger patch finder.
   */
  std::vector<AliEMCALTriggerRawPatch> FindPatches(const AliEMCALTriggerDataGrid<T> &adc, const AliEMCALTriggerDataGrid<T> &offlineAdc) const;

protected:
  std::vector<AliEMCALTriggerAlgorithm<T> *>                 fTriggerAlgorithms;      ///< Trigger algoritms to be used

  /// \cond CLASSIMP
  ClassDef(AliEMCALTriggerPatchFinder, 1);
  /// \endcond
};

#endif


text:
/**
 * Created by hoichi on 21.08.2016.
 */

/*
 * Mother of all chops
 * */
interface ChopData {
    id: ChopId;     // q: or does it belong on a generic `ChopSortable` interface?
}

type ChopId = number | string;

interface ChopEvent<T extends ChopData> {   // do we actually use it anywhere?
    action: string;     // TODO: [string] enum
    type?: string;
    data?: T;
    count?: number;     // HACK: I think count should be defined on a separate descendant interface
}

export interface ChopPageWritable {
    url: string;
}

/**
 * An abstract source file. Might be a content file, might be, say, a template.
 */
export interface ChopPage extends ChopData, ChopPageWritable {
    type: 'file';   // just in case
    path: PagePath;
    content: string;     // todo: fix `string | undefined`
}

/*
 * Source file path, parsed and ready for any reducing user might request
 * */
export interface PagePath {
    dir: string;
    dirs: string[];
    ext: string;
    name: string;
    path: string;
}

/*
 * Everything we need for collections to work properly.
 * So before we collect, all this data should be ready.
 */
interface PageCollectable extends ChopData {
    slug: string;
    cwd: string;
    path: PagePath;
    excerpt: string;
}

interface ContentMeta {
    // We should have defaults for everything
    title?: string;
    date?: Date;
    url?: string;
    published?: boolean;
    template?: string;  // does it belong here?
    [k: string]: any;
}

interface ChopSite {
    [k: string]: any;
}

interface Dictionary<T> {
    [key:string]: T;
}


text:
package org.apache.spark.sql.catalog.v2.utils

import java.util
import java.util.Collections

import scala.collection.JavaConverters._

import org.apache.spark.sql.catalog.v2.TableChange
import org.apache.spark.sql.catalog.v2.TableChange.{AddColumn, DeleteColumn, RemoveProperty, RenameColumn, SetProperty, UpdateColumnComment, UpdateColumnType}
import org.apache.spark.sql.types.{StructField, StructType}

object CatalogV2Util {
  /**
   * Apply properties changes to a map and return the result.
   */
  def applyPropertiesChanges(
      properties: Map[String, String],
      changes: Seq[TableChange]): Map[String, String] = {
    applyPropertiesChanges(properties.asJava, changes).asScala.toMap
  }

  /**
   * Apply properties changes to a Java map and return the result.
   */
  def applyPropertiesChanges(
      properties: util.Map[String, String],
      changes: Seq[TableChange]): util.Map[String, String] = {
    val newProperties = new util.HashMap[String, String](properties)

    changes.foreach {
      case set: SetProperty =>
        newProperties.put(set.property, set.value)

      case unset: RemoveProperty =>
        newProperties.remove(unset.property)

      case _ =>
      // ignore non-property changes
    }

    Collections.unmodifiableMap(newProperties)
  }

  /**
   * Apply schema changes to a schema and return the result.
   */
  def applySchemaChanges(schema: StructType, changes: Seq[TableChange]): StructType = {
    changes.foldLeft(schema) { (schema, change) =>
      change match {
        case add: AddColumn =>
          add.fieldNames match {
            case Array(name) =>
              val newField = StructField(name, add.dataType, nullable = add.isNullable)
              Option(add.comment) match {
                case Some(comment) =>
                  schema.add(newField.withComment(comment))
                case _ =>
                  schema.add(newField)
              }

            case names =>
              replace(schema, names.init, parent => parent.dataType match {
                case parentType: StructType =>
                  val field = StructField(names.last, add.dataType, nullable = add.isNullable)
                  val newParentType = Option(add.comment) match {
                    case Some(comment) =>
                      parentType.add(field.withComment(comment))
                    case None =>
                      parentType.add(field)
                  }

                  Some(StructField(parent.name, newParentType, parent.nullable, parent.metadata))

                case _ =>
                  throw new IllegalArgumentException(s"Not a struct: ${names.init.last}")
              })
          }

        case rename: RenameColumn =>
          replace(schema, rename.fieldNames, field =>
            Some(StructField(rename.newName, field.dataType, field.nullable, field.metadata)))

        case update: UpdateColumnType =>
          replace(schema, update.fieldNames, field => {
            if (!update.isNullable && field.nullable) {
              throw new IllegalArgumentException(
                s"Cannot change optional column to required: $field.name")
            }
            Some(StructField(field.name, update.newDataType, update.isNullable, field.metadata))
          })

        case update: UpdateColumnComment =>
          replace(schema, update.fieldNames, field =>
            Some(field.withComment(update.newComment)))

        case delete: DeleteColumn =>
          replace(schema, delete.fieldNames, _ => None)

        case _ =>
          // ignore non-schema changes
          schema
      }
    }
  }

  private def replace(
      struct: StructType,
      fieldNames: Seq[String],
      update: StructField => Option[StructField]): StructType = {

    val pos = struct.getFieldIndex(fieldNames.head)
        .getOrElse(throw new IllegalArgumentException(s"Cannot find field: ${fieldNames.head}"))
    val field = struct.fields(pos)
    val replacement: Option[StructField] = if (fieldNames.tail.isEmpty) {
      update(field)
    } else {
      field.dataType match {
        case nestedStruct: StructType =>
          val updatedType: StructType = replace(nestedStruct, fieldNames.tail, update)
          Some(StructField(field.name, updatedType, field.nullable, field.metadata))
        case _ =>
          throw new IllegalArgumentException(s"Not a struct: ${fieldNames.head}")
      }
    }

    val newFields = struct.fields.zipWithIndex.flatMap {
      case (_, index) if pos == index =>
        replacement
      case (other, _) =>
        Some(other)
    }

    new StructType(newFields)
  }
}