text:
package org.elasticsearch.action.search;

import com.carrotsearch.hppc.IntArrayList;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.search.ScoreDoc;
import org.elasticsearch.action.OriginalIndices;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.search.RescoreDocIds;
import org.elasticsearch.search.SearchPhaseResult;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.dfs.AggregatedDfs;
import org.elasticsearch.search.fetch.FetchSearchResult;
import org.elasticsearch.search.fetch.ShardFetchSearchRequest;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.search.internal.ShardSearchContextId;
import org.elasticsearch.search.internal.ShardSearchRequest;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.transport.Transport;

import java.util.List;
import java.util.function.BiFunction;

/**
 * This search phase merges the query results from the previous phase together and calculates the topN hits for this search.
 * Then it reaches out to all relevant shards to fetch the topN hits.
 */
final class FetchSearchPhase extends SearchPhase {
    private final ArraySearchPhaseResults<FetchSearchResult> fetchResults;
    private final SearchPhaseController searchPhaseController;
    private final AtomicArray<SearchPhaseResult> queryResults;
    private final BiFunction<InternalSearchResponse, AtomicArray<SearchPhaseResult>, SearchPhase> nextPhaseFactory;
    private final SearchPhaseContext context;
    private final Logger logger;
    private final SearchPhaseResults<SearchPhaseResult> resultConsumer;
    private final SearchProgressListener progressListener;
    private final AggregatedDfs aggregatedDfs;

    FetchSearchPhase(SearchPhaseResults<SearchPhaseResult> resultConsumer,
                     SearchPhaseController searchPhaseController,
                     AggregatedDfs aggregatedDfs,
                     SearchPhaseContext context) {
        this(resultConsumer, searchPhaseController, aggregatedDfs, context,
            (response, queryPhaseResults) -> new ExpandSearchPhase(context, response, queryPhaseResults));
    }

    FetchSearchPhase(SearchPhaseResults<SearchPhaseResult> resultConsumer,
                     SearchPhaseController searchPhaseController,
                     AggregatedDfs aggregatedDfs,
                     SearchPhaseContext context,
                     BiFunction<InternalSearchResponse, AtomicArray<SearchPhaseResult>, SearchPhase> nextPhaseFactory) {
        super("fetch");
        if (context.getNumShards() != resultConsumer.getNumShards()) {
            throw new IllegalStateException("number of shards must match the length of the query results but doesn't:"
                + context.getNumShards() + "!=" + resultConsumer.getNumShards());
        }
        this.fetchResults = new ArraySearchPhaseResults<>(resultConsumer.getNumShards());
        this.searchPhaseController = searchPhaseController;
        this.queryResults = resultConsumer.getAtomicArray();
        this.aggregatedDfs = aggregatedDfs;
        this.nextPhaseFactory =  nextPhaseFactory;
        this.context = context;
        this.logger = context.getLogger();
        this.resultConsumer = resultConsumer;
        this.progressListener = context.getTask().getProgressListener();
    }

    @Override
    public void run() {
        context.execute(new AbstractRunnable() {
            @Override
            protected void doRun() throws Exception {
                // we do the heavy lifting in this inner run method where we reduce aggs etc. that's why we fork this phase
                // off immediately instead of forking when we send back the response to the user since there we only need
                // to merge together the fetched results which is a linear operation.
                innerRun();
            }

            @Override
            public void onFailure(Exception e) {
                context.onPhaseFailure(FetchSearchPhase.this, "", e);
            }
        });
    }

    private void innerRun() throws Exception {
        final int numShards = context.getNumShards();
        final boolean isScrollSearch = context.getRequest().scroll() != null;
        final List<SearchPhaseResult> phaseResults = queryResults.asList();
        final SearchPhaseController.ReducedQueryPhase reducedQueryPhase = resultConsumer.reduce();
        final boolean queryAndFetchOptimization = queryResults.length() == 1;
        final Runnable finishPhase = ()
            -> moveToNextPhase(searchPhaseController, queryResults, reducedQueryPhase, queryAndFetchOptimization ?
            queryResults : fetchResults.getAtomicArray());
        if (queryAndFetchOptimization) {
            assert phaseResults.isEmpty() || phaseResults.get(0).fetchResult() != null : "phaseResults empty [" + phaseResults.isEmpty()
                + "], single result: " +  phaseResults.get(0).fetchResult();
            // query AND fetch optimization
            finishPhase.run();
        } else {
            ScoreDoc[] scoreDocs = reducedQueryPhase.sortedTopDocs.scoreDocs;
            final IntArrayList[] docIdsToLoad = searchPhaseController.fillDocIdsToLoad(numShards, scoreDocs);
            // no docs to fetch -- sidestep everything and return
            if (scoreDocs.length == 0) {
                // we have to release contexts here to free up resources
                phaseResults.stream()
                    .map(SearchPhaseResult::queryResult)
                    .forEach(this::releaseIrrelevantSearchContext);
                finishPhase.run();
            } else {
                final ScoreDoc[] lastEmittedDocPerShard = isScrollSearch ?
                    searchPhaseController.getLastEmittedDocPerShard(reducedQueryPhase, numShards)
                    : null;
                final CountedCollector<FetchSearchResult> counter = new CountedCollector<>(fetchResults,
                    docIdsToLoad.length, // we count down every shard in the result no matter if we got any results or not
                    finishPhase, context);
                for (int i = 0; i < docIdsToLoad.length; i++) {
                    IntArrayList entry = docIdsToLoad[i];
                    SearchPhaseResult queryResult = queryResults.get(i);
                    if (entry == null) { // no results for this shard ID
                        if (queryResult != null) {
                            // if we got some hits from this shard we have to release the context there
                            // we do this as we go since it will free up resources and passing on the request on the
                            // transport layer is cheap.
                            releaseIrrelevantSearchContext(queryResult.queryResult());
                            progressListener.notifyFetchResult(i);
                        }
                        // in any case we count down this result since we don't talk to this shard anymore
                        counter.countDown();
                    } else {
                        SearchShardTarget searchShardTarget = queryResult.getSearchShardTarget();
                        Transport.Connection connection = context.getConnection(searchShardTarget.getClusterAlias(),
                            searchShardTarget.getNodeId());
                        ShardFetchSearchRequest fetchSearchRequest = createFetchRequest(queryResult.queryResult().getContextId(), i, entry,
                            lastEmittedDocPerShard, searchShardTarget.getOriginalIndices(), queryResult.getShardSearchRequest(),
                            queryResult.getRescoreDocIds());
                        executeFetch(queryResult.getShardIndex(), searchShardTarget, counter, fetchSearchRequest, queryResult.queryResult(),
                            connection);
                    }
                }
            }
        }
    }

    protected ShardFetchSearchRequest createFetchRequest(ShardSearchContextId contextId, int index, IntArrayList entry,
                                                         ScoreDoc[] lastEmittedDocPerShard, OriginalIndices originalIndices,
                                                         ShardSearchRequest shardSearchRequest, RescoreDocIds rescoreDocIds) {
        final ScoreDoc lastEmittedDoc = (lastEmittedDocPerShard != null) ? lastEmittedDocPerShard[index] : null;
        return new ShardFetchSearchRequest(originalIndices, contextId, shardSearchRequest, entry, lastEmittedDoc,
            rescoreDocIds, aggregatedDfs);
    }

    private void executeFetch(final int shardIndex, final SearchShardTarget shardTarget,
                              final CountedCollector<FetchSearchResult> counter,
                              final ShardFetchSearchRequest fetchSearchRequest, final QuerySearchResult querySearchResult,
                              final Transport.Connection connection) {
        context.getSearchTransport().sendExecuteFetch(connection, fetchSearchRequest, context.getTask(),
            new SearchActionListener<FetchSearchResult>(shardTarget, shardIndex) {
                @Override
                public void innerOnResponse(FetchSearchResult result) {
                    try {
                        progressListener.notifyFetchResult(shardIndex);
                        counter.onResult(result);
                    } catch (Exception e) {
                        context.onPhaseFailure(FetchSearchPhase.this, "", e);
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    try {
                        logger.debug(
                            () -> new ParameterizedMessage("[{}] Failed to execute fetch phase", fetchSearchRequest.contextId()), e);
                        progressListener.notifyFetchFailure(shardIndex, shardTarget, e);
                        counter.onFailure(shardIndex, shardTarget, e);
                    } finally {
                        // the search context might not be cleared on the node where the fetch was executed for example
                        // because the action was rejected by the thread pool. in this case we need to send a dedicated
                        // request to clear the search context.
                        releaseIrrelevantSearchContext(querySearchResult);
                    }
                }
            });
    }

    /**
     * Releases shard targets that are not used in the docsIdsToLoad.
     */
    private void releaseIrrelevantSearchContext(QuerySearchResult queryResult) {
        // we only release search context that we did not fetch from, if we are not scrolling
        // or using a PIT and if it has at least one hit that didn't make it to the global topDocs
        if (queryResult.hasSearchContext()
                && context.getRequest().scroll() == null
                && (context.isPartOfPointInTime(queryResult.getContextId()) == false)) {
            try {
                SearchShardTarget searchShardTarget = queryResult.getSearchShardTarget();
                Transport.Connection connection = context.getConnection(searchShardTarget.getClusterAlias(), searchShardTarget.getNodeId());
                context.sendReleaseSearchContext(queryResult.getContextId(), connection, searchShardTarget.getOriginalIndices());
            } catch (Exception e) {
                context.getLogger().trace("failed to release context", e);
            }
        }
    }

    private void moveToNextPhase(SearchPhaseController searchPhaseController,
                                 AtomicArray<SearchPhaseResult> queryPhaseResults,
                                 SearchPhaseController.ReducedQueryPhase reducedQueryPhase,
                                 AtomicArray<? extends SearchPhaseResult> fetchResultsArr) {
        final InternalSearchResponse internalResponse = searchPhaseController.merge(context.getRequest().scroll() != null,
            reducedQueryPhase, fetchResultsArr.asList(), fetchResultsArr::get);
        context.executeNextPhase(this, nextPhaseFactory.apply(internalResponse, queryPhaseResults));
    }
}


text:
$script:dscModuleName = 'NetworkingDsc'
$script:dscResourceName = 'DSC_NetIPInterface'

function Invoke-TestSetup
{
    try
    {
        Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
    }

    $script:testEnvironment = Initialize-TestEnvironment `
        -DSCModuleName $script:dscModuleName `
        -DSCResourceName $script:dscResourceName `
        -ResourceType 'Mof' `
        -TestType 'Unit'

    Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1')
}

function Invoke-TestCleanup
{
    Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}

Invoke-TestSetup

# Begin Testing
try
{
    InModuleScope $script:dscResourceName {
        <#
            This is an array of parameters that will be used with pester test cases
            to test each individual parameter. The array contains a hash table
            representing each paramter to test. The properties of the hash table are
            - Name: the name of the parameter.
            - MockedValue: The value that the mock for Get-NetIPInterface will return for
              the parameter
            - TestValue: The value that will be used to change the setting to.
            - ParameterFilter: The parameter filter condition used to determine if the
              value has been successfully set in Set-TargetResource.
        #>
        $testParameterList = @(
            @{
                Name            = 'AdvertiseDefaultRoute'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $AdvertiseDefaultRoute -eq 'Disabled'
                }
            },
            @{
                Name            = 'Advertising'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Advertising -eq 'Disabled'
                }
            },
            @{
                Name            = 'AutomaticMetric'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $AutomaticMetric -eq 'Disabled'
                }
            },
            @{
                Name            = 'Dhcp'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Dhcp -eq 'Disabled'
                }
            },
            @{
                Name            = 'DirectedMacWolPattern'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $DirectedMacWolPattern -eq 'Disabled'
                }
            },
            @{
                Name            = 'EcnMarking'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $EcnMarking -eq 'Disabled'
                }
            },
            @{
                Name            = 'ForceArpNdWolPattern'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $ForceArpNdWolPattern -eq 'Disabled'
                }
            },
            @{
                Name            = 'Forwarding'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Forwarding -eq 'Disabled'
                }
            },
            @{
                Name            = 'IgnoreDefaultRoutes'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $IgnoreDefaultRoutes -eq 'Disabled'
                }
            },
            @{
                Name            = 'ManagedAddressConfiguration'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $ManagedAddressConfiguration -eq 'Disabled'
                }
            },
            @{
                Name            = 'NeighborUnreachabilityDetection'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $NeighborUnreachabilityDetection -eq 'Disabled'
                }
            },
            @{
                Name            = 'OtherStatefulConfiguration'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $OtherStatefulConfiguration -eq 'Disabled'
                }
            },
            @{
                Name            = 'RouterDiscovery'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $RouterDiscovery -eq 'Disabled'
                }
            },
            @{
                Name            = 'WeakHostReceive'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $WeakHostReceive -eq 'Disabled'
                }
            },
            @{
                Name            = 'WeakHostSend'
                MockedValue     = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled
                TestValue       = 'Disabled'
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $WeakHostSend -eq 'Disabled'
                }
            },
            @{
                Name            = 'NlMtu'
                MockedValue     = [System.Uint32] 1600
                TestValue       = [System.Uint32] 1500
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $NlMtuBytes -eq 1500
                }
            },
            @{
                Name            = 'InterfaceMetric'
                MockedValue     = [System.Uint32] 20
                TestValue       = [System.Uint32] 15
                ParameterFilter = {
                    $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $InterfaceMetric -eq 15
                }
            }
        )

        $script:netIPInterfaceExists = @{
            InterfaceAlias = 'Ethernet'
            AddressFamily  = 'IPv4'
            Verbose        = $true
        }

        $script:netIPInterfaceExists_ParameterFilter = {
            $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4'
        }

        $script:netIPInterfaceExists_Settings = @{
            InterfaceAlias = 'Ethernet'
            AddressFamily  = 'IPv4'
        }

        foreach ($parameter in $testParameterList)
        {
            $null = $script:netIPInterfaceExists_Settings.Add($parameter.Name, $parameter.MockedValue)
        }

        $script:netIPInterfaceMissing = @{
            InterfaceAlias = 'EthernetDoesNotExist'
            AddressFamily  = 'IPv4'
            Verbose        = $true
        }

        $script:netIPInterfaceMissing_ParameterFilter = {
            $InterfaceAlias -eq 'EthernetDoesNotExist' -and $AddressFamily -eq 'IPv4'
        }

        Describe 'DSC_NetIPInterface\Get-TargetResource' -Tag 'Get' {
            Context 'When called with alias and address family of an existing interface' {
                Mock `
                    -CommandName Get-NetworkIPInterface `
                    -ParameterFilter $script:netIPInterfaceExists_ParameterFilter `
                    -MockWith { $script:netIPInterfaceExists_Settings }

                It 'Should not throw an exception' {
                    {
                        $script:result = Get-TargetResource @script:netIPInterfaceExists
                    } | Should -Not -Throw
                }

                It 'Should return <MockedValue> for parameter <Name>' -TestCases $testParameterList {
                    param
                    (
                        $Name, $MockedValue, $TestValue, $ParameterFilter
                    )

                    $script:result[$Name] | Should -Be $MockedValue
                }
            }
        }

        Describe 'DSC_NetIPInterface\Test-TargetResource' -Tag 'Test' {
            Context 'When called with alias and address family of an existing interface and a mismatching value' {
                Mock `
                    -CommandName Get-NetworkIPInterface `
                    -ParameterFilter $script:netIPInterfaceExists_ParameterFilter `
                    -MockWith { $script:netIPInterfaceExists_Settings }

                It 'Should return $false when existing value for parameter <Name> is set to <TestValue> but should be <MockedValue>' -TestCases $testParameterList {
                    param
                    (
                        $Name, $MockedValue, $TestValue, $ParameterFilter
                    )

                    $comparisonParameter = @{
                        $Name = $TestValue
                    }

                    $script:result = Test-TargetResource @script:netIPInterfaceExists @comparisonParameter

                    $script:result | Should -BeFalse
                }
            }

            Context 'When called with alias and address family of an existing interface and no mismatching values' {
                Mock `
                    -CommandName Get-NetworkIPInterface `
                    -ParameterFilter $script:netIPInterfaceExists_ParameterFilter `
                    -MockWith { $script:netIPInterfaceExists_Settings }

                It 'Should return $true when existing value for parameter <Name> is set to <TestValue> and should be <TestValue>' -TestCases $testParameterList {
                    param
                    (
                        $Name, $MockedValue, $TestValue, $ParameterFilter
                    )

                    $comparisonParameter = @{
                        $Name = $MockedValue
                    }

                    $script:result = Test-TargetResource @script:netIPInterfaceExists @comparisonParameter

                    $script:result | Should -BeTrue
                }
            }
        }

        Describe 'DSC_NetIPInterface\Set-TargetResource' -Tag 'Set' {
            Context 'When called with alias and address family of an existing interface and a mismatching value' {
                Mock `
                    -CommandName Get-NetworkIPInterface `
                    -ParameterFilter $script:netIPInterfaceExists_ParameterFilter `
                    -MockWith { $script:netIPInterfaceExists_Settings }

                It 'Should set parameter <Name> to <TestValue>' -TestCases $testParameterList {
                    param
                    (
                        $Name, $MockedValue, $TestValue, $ParameterFilter
                    )

                    $comparisonParameter = @{
                        $Name = $TestValue
                    }

                    Mock `
                        -CommandName Set-NetIPInterface

                    Set-TargetResource @script:netIPInterfaceExists @comparisonParameter

                    Assert-MockCalled `
                        -CommandName Set-NetIPInterface `
                        -ParameterFilter $ParameterFilter `
                        -Exactly -Times 1
                }
            }

            Context 'When called with alias and address family of an existing interface and no mismatching values' {
                Mock `
                    -CommandName Get-NetworkIPInterface `
                    -ParameterFilter $script:netIPInterfaceExists_ParameterFilter `
                    -MockWith { $script:netIPInterfaceExists_Settings }

                It 'Should not call Set-NetIPInterface' {
                    $comparisonParameter = @{
                        $testParameterList[0].Name = $testParameterList[0].MockedValue
                    }

                    Mock `
                        -CommandName Set-NetIPInterface

                    Set-TargetResource @script:netIPInterfaceExists @comparisonParameter

                    Assert-MockCalled `
                        -CommandName Set-NetIPInterface `
                        -ParameterFilter $ParameterFilter `
                        -Exactly -Times 0
                }
            }
        }

        Describe 'DSC_NetIPInterface\Get-NetworkIPInterface' {
            Context 'When called with alias and address family of an interface that does not exist' {
                Mock `
                    -CommandName Get-NetIPInterface `
                    -ParameterFilter $script:netIPInterfaceMissing_ParameterFilter

                It 'Should throw expected exception' {
                    $errorRecord = Get-InvalidOperationRecord `
                        -Message ($script:localizedData.NetworkIPInterfaceDoesNotExistMessage -f $script:netIPInterfaceMissing.InterfaceAlias, $script:netIPInterfaceMissing.AddressFamily)

                    {
                        $script:result = Get-NetworkIPInterface @script:netIPInterfaceMissing
                    } | Should -Throw $errorRecord
                }

                It 'Should call the expected mocks' {
                    Assert-MockCalled `
                        -CommandName Get-NetIPInterface `
                        -ParameterFilter $script:netIPInterfaceMissing_ParameterFilter `
                        -Exactly -Times 1
                }
            }

            Context 'When called with alias and address family of an existing interface' {
                Mock `
                    -CommandName Get-NetIPInterface `
                    -ParameterFilter $script:netIPInterfaceExists_ParameterFilter `
                    -MockWith { $script:netIPInterfaceExists_Settings }

                It 'Should not throw exception' {
                    {
                        $script:result = Get-NetworkIPInterface @script:netIPInterfaceExists
                    } | Should -Not -Throw
                }

                It 'Should call the expected mocks' {
                    Assert-MockCalled `
                        -CommandName Get-NetIPInterface `
                        -ParameterFilter $script:netIPInterfaceExists_ParameterFilter `
                        -Exactly -Times 1
                }
            }
        }
    }
}
finally
{
    Invoke-TestCleanup
}

redpajama_set_name: RedPajamaGithub


text:
package io.lettuce.core.pubsub;

import java.nio.ByteBuffer;

import io.lettuce.core.codec.RedisCodec;
import io.lettuce.core.protocol.CommandArgs;

/**
 *
 * Command args for Pub/Sub connections. This implementation hides the first key as PubSub keys are not keys from the key-space.
 *
 * @author Mark Paluch
 * @since 4.2
 */
class PubSubCommandArgs<K, V> extends CommandArgs<K, V> {

    /**
     * @param codec Codec used to encode/decode keys and values, must not be {@code null}.
     */
    public PubSubCommandArgs(RedisCodec<K, V> codec) {
        super(codec);
    }

    /**
     *
     * @return always {@code null}.
     */
    @Override
    public ByteBuffer getFirstEncodedKey() {
        return null;
    }

}


text:
namespace mojo {

using payments::mojom::blink::PaymentAppManifest;
using payments::mojom::blink::PaymentAppManifestPtr;
using payments::mojom::blink::PaymentAppOption;
using payments::mojom::blink::PaymentAppOptionPtr;

template <>
struct TypeConverter<PaymentAppOptionPtr, blink::PaymentAppOption> {
  static PaymentAppOptionPtr Convert(const blink::PaymentAppOption& input) {
    PaymentAppOptionPtr output = PaymentAppOption::New();
    output->label = input.hasLabel() ? input.label() : WTF::emptyString();
    output->icon = input.hasIcon() ? input.icon() : WTF::String();
    output->id = input.hasId() ? input.id() : WTF::emptyString();
    output->enabled_methods = WTF::Vector<WTF::String>(input.enabledMethods());
    return output;
  }
};

template <>
struct TypeConverter<PaymentAppManifestPtr, blink::PaymentAppManifest> {
  static PaymentAppManifestPtr Convert(const blink::PaymentAppManifest& input) {
    PaymentAppManifestPtr output = PaymentAppManifest::New();
    output->label = input.hasLabel() ? input.label() : WTF::emptyString();
    output->icon = input.hasIcon() ? input.icon() : WTF::String();
    if (input.hasOptions()) {
      for (size_t i = 0; i < input.options().size(); ++i) {
        output->options.append(PaymentAppOption::From(input.options()[i]));
      }
    }
    return output;
  }
};

template <>
struct TypeConverter<blink::PaymentAppManifest, PaymentAppManifestPtr> {
  static blink::PaymentAppManifest Convert(const PaymentAppManifestPtr& input) {
    blink::PaymentAppManifest output;
    output.setLabel(input->label);
    output.setIcon(input->icon);
    blink::HeapVector<blink::PaymentAppOption> options;
    for (const auto& option : input->options) {
      options.append(mojo::ConvertTo<blink::PaymentAppOption>(option));
    }
    output.setOptions(options);
    return output;
  }
};

template <>
struct TypeConverter<blink::PaymentAppOption, PaymentAppOptionPtr> {
  static blink::PaymentAppOption Convert(const PaymentAppOptionPtr& input) {
    blink::PaymentAppOption output;
    output.setLabel(input->label);
    output.setIcon(input->icon);
    output.setId(input->id);
    Vector<WTF::String> enabledMethods;
    for (const auto& method : input->enabled_methods) {
      enabledMethods.append(method);
    }
    output.setEnabledMethods(enabledMethods);
    return output;
  }
};

}  // namespace mojo

namespace blink {

PaymentAppManager* PaymentAppManager::create(
    ScriptState* scriptState,
    ServiceWorkerRegistration* registration) {
  return new PaymentAppManager(scriptState, registration);
}

void PaymentAppManager::contextDestroyed() {
  m_manager.reset();
}

ScriptPromise PaymentAppManager::setManifest(
    ScriptState* scriptState,
    const PaymentAppManifest& manifest) {
  if (!m_manager) {
    return ScriptPromise::rejectWithDOMException(
        scriptState, DOMException::create(InvalidStateError,
                                          "Payment app manager unavailable."));
  }

  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();

  m_manager->SetManifest(
      m_registration->scope(),
      payments::mojom::blink::PaymentAppManifest::From(manifest),
      convertToBaseCallback(WTF::bind(&PaymentAppManager::onSetManifest,
                                      wrapPersistent(this),
                                      wrapPersistent(resolver))));

  return promise;
}

ScriptPromise PaymentAppManager::getManifest(ScriptState* scriptState) {
  if (!m_manager) {
    return ScriptPromise::rejectWithDOMException(
        scriptState, DOMException::create(InvalidStateError,
                                          "Payment app manager unavailable."));
  }

  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();

  m_manager->GetManifest(m_registration->scope(),
                         convertToBaseCallback(WTF::bind(
                             &PaymentAppManager::onGetManifest,
                             wrapPersistent(this), wrapPersistent(resolver))));

  return promise;
}

DEFINE_TRACE(PaymentAppManager) {
  visitor->trace(m_registration);
  ContextLifecycleObserver::trace(visitor);
}

PaymentAppManager::PaymentAppManager(ScriptState* scriptState,
                                     ServiceWorkerRegistration* registration)
    : ContextLifecycleObserver(scriptState->getExecutionContext()),
      m_registration(registration) {
  DCHECK(registration);
  Platform::current()->interfaceProvider()->getInterface(
      mojo::GetProxy(&m_manager));

  m_manager.set_connection_error_handler(convertToBaseCallback(WTF::bind(
      &PaymentAppManager::onServiceConnectionError, wrapWeakPersistent(this))));
}

void PaymentAppManager::onSetManifest(
    ScriptPromiseResolver* resolver,
    payments::mojom::blink::PaymentAppManifestError error) {
  DCHECK(resolver);
  switch (error) {
    case payments::mojom::blink::PaymentAppManifestError::NONE:
      resolver->resolve();
      break;
    case payments::mojom::blink::PaymentAppManifestError::NOT_IMPLEMENTED:
      resolver->reject(
          DOMException::create(NotSupportedError, "Not implemented yet."));
      break;
    case payments::mojom::blink::PaymentAppManifestError::NO_ACTIVE_WORKER:
      resolver->reject(
          DOMException::create(InvalidStateError, "No active service worker."));
      break;
    case payments::mojom::blink::PaymentAppManifestError::
        MANIFEST_STORAGE_OPERATION_FAILED:
      resolver->reject(DOMException::create(
          InvalidStateError, "Storing manifest data is failed."));
      break;
  }
}

void PaymentAppManager::onGetManifest(
    ScriptPromiseResolver* resolver,
    payments::mojom::blink::PaymentAppManifestPtr manifest,
    payments::mojom::blink::PaymentAppManifestError error) {
  DCHECK(resolver);
  switch (error) {
    case payments::mojom::blink::PaymentAppManifestError::NONE:
      resolver->resolve(
          mojo::ConvertTo<PaymentAppManifest>(std::move(manifest)));
      break;
    case payments::mojom::blink::PaymentAppManifestError::NOT_IMPLEMENTED:
      resolver->reject(
          DOMException::create(NotSupportedError, "Not implemented yet."));
      break;
    case payments::mojom::blink::PaymentAppManifestError::NO_ACTIVE_WORKER:
    case payments::mojom::blink::PaymentAppManifestError::
        MANIFEST_STORAGE_OPERATION_FAILED:
      resolver->reject(DOMException::create(
          AbortError,
          "No payment app manifest associated with the service worker."));
      break;
  }
}

void PaymentAppManager::onServiceConnectionError() {
  if (!Platform::current()) {
    return;
  }

  m_manager.reset();
}

}  // namespace blink


text:
#pragma once

/** \brief current AMDiS version */
#ifndef AMDIS_VERSION
#define AMDIS_VERSION  "AMDiS: Version 2.0.0"
#endif

//#include <boost/config.hpp>

#define CACHE_LINE 16

// if AMDIS_FIXED_SIZE == 1 use static arrays
#ifndef AMDIS_FIXED_SIZE
#define AMDIS_FIXED_SIZE 0
//  #define DOW 2
//  #define DIM 2
#endif

#if defined(__clang__)					// Clang/LLVM.
#include "config/Config_clang.hpp"

#elif defined(__ICC) || defined(__INTEL_COMPILER)	// Intel ICC/ICPC.
#include "config/Config_intel.hpp"

#elif defined(__GNUC__) || defined(__GNUG__)		// GNU GCC/G++.
#include "config/Config_gcc.hpp"

#elif defined(__HP_cc) || defined(__HP_aCC)
error:
not supported compiler

#elif defined(__IBMC__) || defined(__IBMCPP__)
error:
not supported compiler

#elif defined(_MSC_VER)					// Microsoft Visual Studio.
#include "config/Config_msc.hpp"

#elif defined(__PGI)					// Portland Group PGCC/PGCPP.
error:
not supported compiler
//   #include "Config_pgi.h"

#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
error:
not supported compiler
#endif

#include "config/Config_defaults.hpp"

typedef unsigned short small_t;   // only allow small matrices

// some workarounds for mtl (since the namespace has changed)
#define MTL_VEC mtl::vector
#define MTL_MAT mtl::matrix


text:
<title>Vorbisfile - function - ov_test</title>
<link rel=stylesheet href="style.css" type="text/css">

Vorbisfile documentation

vorbisfile version 1.3.2 - 20101101

ov_test

declared in "vorbis/vorbisfile.h";

This partially opens a vorbis file to test for Vorbis-ness.  It loads
the headers for the first chain and tests for seekability (but does not seek).
Use ov_test_open() to finish opening the file
or ov_clear to close/free it.

 WARNING for Windows developers:  Do not use ov_test()
in Windows applications; Windows linking places restrictions on
passing <tt>FILE *</tt> handles successfully, and ov_test() runs afoul
of these restrictions [a] in exactly the same
way as ov_open().  See the ov_test_callbacks() page  for
details on using ov_test_callbacks() instead.

int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);

Parameters

f

File pointer to an already opened file
or pipe (it need not be seekable--though this obviously restricts what
can be done with the bitstream).

vf

A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisfile
functions. Once this has been called, the same <tt>OggVorbis_File</tt>
struct should be passed to all the libvorbisfile functions.

initial

Typically set to NULL.  This parameter is useful if some data has already been
read from the file and the stream is not seekable. It is used in conjunction with <tt>ibytes</tt>.  In this case, <tt>initial</tt>
should be a pointer to a buffer containing the data read.

ibytes

Typically set to 0.  This parameter is useful if some data has already been
read from the file and the stream is not seekable. In this case, <tt>ibytes</tt>
should contain the length (in bytes) of the buffer.  Used together with <tt>initial</tt>

Return Values

0 for success

less than zero for failure:

OV_EREAD - A read from media returned an error.

OV_ENOTVORBIS - Bitstream contains no Vorbis data.

OV_EVERSION - Vorbis version mismatch.

OV_EBADHEADER - Invalid Vorbis bitstream header.

OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.

Notes

All the notes from ov_open() apply to ov_test().

copyright © 2000-2010 Xiph.Org

Ogg Vorbis

Vorbisfile documentation

vorbisfile version 1.3.2 - 20101101


text:
package org.waveprotocol.wave.client.wavepanel.view;

/**
 * View of a participant.
 *
 */
public interface IntrinsicParticipantView {
  String getId();

  void setAvatar(String url);
  void setName(String name);
}


text:
<?php

namespace s9e\TextFormatter\Configurator\Items\AttributeFilters;
use s9e\TextFormatter\Configurator\Items\AttributeFilter;
class Ipv6Filter extends AttributeFilter
{
	public function __construct()
	{
		parent::__construct('s9e\\TextFormatter\\Parser\\BuiltInFilters::filterIpv6');
		$this->setJS('BuiltInFilters.filterIpv6');
	}
}


text:
package com.hazelcast.map.impl.operation;

import com.hazelcast.map.impl.MapDataSerializerHook;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.spi.impl.operationservice.MutatingOperation;

public class ReplaceOperation extends BasePutOperation implements MutatingOperation {

    private boolean successful;

    public ReplaceOperation(String name, Data dataKey, Data value) {
        super(name, dataKey, value);
    }

    public ReplaceOperation() {
    }

    @Override
    protected void runInternal() {
        Object oldValue = recordStore.replace(dataKey, dataValue);
        this.oldValue = mapServiceContext.toData(oldValue);
        successful = oldValue != null;
    }

    @Override
    public boolean shouldBackup() {
        return successful && recordStore.getRecord(dataKey) != null;
    }

    @Override
    protected void afterRunInternal() {
        if (successful) {
            super.afterRunInternal();
        }
    }

    @Override
    public Object getResponse() {
        return oldValue;
    }

    @Override
    public int getClassId() {
        return MapDataSerializerHook.REPLACE;
    }
}


text:
BlackRed
========

BlackRed is a dynamic blacklisting library using `Redis <http://redis.io/>`__ as a fast and reliable
storage backend.

.. image:: https://coveralls.io/repos/edelbluth/blackred/badge.svg?branch=master
   :target: https://coveralls.io/r/edelbluth/blackred?branch=master
.. image:: https://travis-ci.org/edelbluth/blackred.svg?branch=master
   :target: https://travis-ci.org/edelbluth/blackred
.. image:: https://readthedocs.org/projects/blackred/badge/?version=latest
   :target: https://blackred.readthedocs.org/index.html
.. image:: https://img.shields.io/pypi/v/BlackRed.svg
   :target: https://pypi.python.org/pypi/BlackRed
.. image:: https://img.shields.io/pypi/status/BlackRed.svg
   :target: https://pypi.python.org/pypi/BlackRed
.. image:: https://img.shields.io/pypi/dd/BlackRed.svg
   :target: https://pypi.python.org/pypi/BlackRed
.. image:: https://img.shields.io/github/license/edelbluth/blackred.svg
   :target: https://github.com/edelbluth/blackred
.. image:: https://img.shields.io/badge/juergen-rocks-000033.svg?style=flat
   :target: https://juergen.rocks/

How does it work?
-----------------

Example: A user tries to log on a system and fails because of bad credentials or an inactivated account. This failure
can be recorded with BlackRed. After three failures within a certain time the account gets locked for an extended
period of time. This limits brute force attacks. All time periods are configurable.

In a desktop application you would record the username in question with BlackRed. In a web environment, the requester's
IP address would be the perfect.

In the redis database, two lists are kept: A watchlist that records the failures, and the blacklist that contains
blocked items.

Requirements
------------

BlackRed runs only under Python 3.3, 3.4 and 3.5 There's no support for Python 2.
PyPy 3 is supported only in BlackRed 0.3.x and below.

The only thing BlackRed needs is the `redis package <https://pypi.python.org/pypi/redis>`__ >= 2.10.

Jump Start
----------

Installation can be done with ``pip install blackred``. Usage is as easy, here an example for a simple user login:

.. code-block:: python

   import blackred

   def login(username, password, request_ip):
       br = blackred.BlackRed()
       if br.is_blocked(request_ip):
           return False
       if not authenticate(username, password):
           br.log_fail(request_ip)
           return False
       return True

More examples: :doc:`Example Usage <doc/example-usage>`.

Usage
-----

.. toctree::
   :maxdepth: 2
   :glob:

   doc/configuration
   doc/example-usage

API Documentation
-----------------

.. toctree::
   :maxdepth: 2
   :glob:

   api/blackred

Links
-----

- Author: Juergen Edelbluth, `https://juergen.rocks/ <https://juergen.rocks/>`_,
  `@JuergenRocks <https://twitter.com/JuergenRocks>`_
- Build Status: `https://travis-ci.org/edelbluth/blackred <https://travis-ci.org/edelbluth/blackred>`_
- Project Homepage: `https://github.com/edelbluth/blackred <https://github.com/edelbluth/blackred>`_
- PyPi Page: `https://pypi.python.org/pypi/blackred <https://pypi.python.org/pypi/blackred>`_
- German Description (for 0.2 version): `https://juergen.rocks/art/mit-blackred-benutzer-logins-absichern.html
  <https://juergen.rocks/art/mit-blackred-benutzer-logins-absichern.html>`_
- Documentation (this one): `https://blackred.readthedocs.org/index.html <https://blackred.readthedocs.org/index.html>`_

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
/*!
 * Piwik - Web Analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

/**
 * jQueryUI widget for Live visitors widget
 */

(function ($) {
    $.widget('piwik.liveWidget', {

        /**
         * Default settings for widgetPreview
         */
        options:{
            // Maximum numbers of rows to display in widget
            maxRows: 10,
            // minimal time in microseconds to wait between updates
            interval: 3000,
            // maximum time to wait between requests
            maxInterval: 300000,
            // url params to use for data request
            dataUrlParams: null,
            // callback triggered on a successful update (content of widget changed)
            onUpdate: null,
            // speed for fade animation
            fadeInSpeed: 'slow'
        },

        /**
         * current updateInterval used
         */
        currentInterval: null,

        /**
         * identifies if content has updated (eg new visits/views)
         */
        updated: false,

        /**
         * window timeout interval
         */
        updateInterval: null,

        /**
         * identifies if the liveWidget ist started or not
         */
        isStarted: true,

        /**
         * Update the widget
         *
         * @return void
         */
        _update: function () {

            this.updated = false;

            var that = this;

            var ajaxRequest = new ajaxHelper();
            ajaxRequest.addParams(this.options.dataUrlParams, 'GET');
            ajaxRequest.setFormat('html');
            ajaxRequest.setCallback(function (r) {
                that._parseResponse(r);

                // add default interval to last interval if not updated or reset to default if so
                if (!that.updated) {
                    that.currentInterval += that.options.interval;
                } else {
                    that.currentInterval = that.options.interval;
                    if (that.options.onUpdate) that.options.onUpdate();
                }

                // check new interval doesn't reach the defined maximum
                if (that.options.maxInterval < that.currentInterval) {
                    that.currentInterval = that.options.maxInterval;
                }

                if (that.isStarted) {
                    window.clearTimeout(that.updateInterval);
                    if ($(that.element).closest('body').length) {
                        that.updateInterval = window.setTimeout(function() { that._update() }, that.currentInterval);
                    }
                }
            });
            ajaxRequest.send(false);
        },

        /**
         * Parses the given response and updates the widget if newer content is available
         *
         * @return void
         */
        _parseResponse: function (data) {
            if (!data || !data.length) {
                this.updated = false;
                return;
            }

            var items = $('li', $(data));
            for (var i = items.length; i--;) {
                this._parseItem(items[i]);
            }
        },

        /**
         * Parses the given item and updates or adds an entry to the list
         *
         * @param item to parse
         * @return void
         */
        _parseItem: function (item) {
            var visitId = $(item).attr('id');
            if ($('#' + visitId, this.element).length) {
                if ($('#' + visitId, this.element).html() != $(item).html()) {
                    this.updated = true;
                }
                $('#' + visitId, this.element).remove();
                $(this.element).prepend(item);
            } else {
                this.updated = true;
                $(item).hide();
                $(this.element).prepend(item);
                $(item).fadeIn(this.options.fadeInSpeed);
            }
            // remove rows if there are more than the maximum
            $('li:gt(' + (this.options.maxRows - 1) + ')', this.element).remove();
        },

        /**
         * Constructor
         *
         * @return void
         */
        _create: function () {

            if (!this.options.dataUrlParams) {
                console && console.error('liveWidget error: dataUrlParams needs to be defined in settings.');
                return;
            }

            this.currentInterval = this.options.interval;

            var self = this;

            this.updateInterval = window.setTimeout(function() { self._update(); }, this.currentInterval);
        },

        /**
         * Stops requests if widget is destroyed
         */
        _destroy: function () {

            this.stop();
        },

        /**
         * Triggers an update for the widget
         *
         * @return void
         */
        update: function () {
            this._update();
        },

        /**
         * Starts the automatic update cycle
         *
         * @return void
         */
        start: function () {
            this.isStarted = true;
            this.currentInterval = 0;
            this._update();
        },

        /**
         * Stops the automatic update cycle
         *
         * @return void
         */
        stop: function () {
            this.isStarted = false;
            window.clearTimeout(this.updateInterval);
        },

        /**
         * Set the interval for refresh
         *
         * @param {int} interval  new interval for refresh
         * @return void
         */
        setInterval: function (interval) {
            this.currentInterval = interval;
        }
    });
})(jQuery);

var pauseImage = "plugins/Live/templates/images/pause.gif";
var pauseDisabledImage = "plugins/Live/templates/images/pause_disabled.gif";
var playImage = "plugins/Live/templates/images/play.gif";
var playDisabledImage = "plugins/Live/templates/images/play_disabled.gif";
function onClickPause() {
    $('#pauseImage').attr('src', pauseImage);
    $('#playImage').attr('src', playDisabledImage);
    return $('#visitsLive').liveWidget('stop');
}
function onClickPlay() {
    $('#playImage').attr('src', playImage);
    $('#pauseImage').attr('src', pauseDisabledImage);
    return $('#visitsLive').liveWidget('start');
}


text:
====
pypc
====

|Build Status| |Wheel Status|

The Python3 Package Creator.

Pypc is a standard project generator for Python packages.

How it Works
============

Pypc is similar to yoeman in that it is a tool for generating project scaffolding. The pypc project aspires to integrate with the Python Packaging Authority `pip` tool to provide users with a standard, sane approach to creating python packages (via a command such as `pip create <package>`. Currently, pypc works similarly to git and will populate your current directory with the appropriate project files.

Installation
============

    $ pip install pypc

Usage
=====

Pypc helps you create the basic structure of your python
package. It uses the conventions and file structure outlined in
https://packaging.python.org/en/latest/distributing.html. Advanced options
exist for additionally automatically setting up virtualenv for your project,
pip install dependencies and linters, such as pyflakes and pep8, auto-generating
a pip freeze as requirements.txt, and creating command line entry points for your package.

The most basic example is `pypc <package-name>` which will populate your current working directory with
the correct project files. E.g:

    $ pypc project && ls

    CHANGES  docs/  examples/  LICENSE  MANIFEST.in  project/  README.md  setup.py  tox.in

Pypc also offers a -m or --minimal flag for purists who wish to generate only the minimal requirements. This
only creates a README and setup.py and does not require network access
(after pypc is installed).

    # Minimal install

    $ pypc -m project && ls

    project/  MANIFEST.in  README.rst  setup.py setup.cfg

In both cases, a project/ subdirectory is populated with an __init__.py.

Finally, pypc provides a --strict or -s mode which not only scaffolds your
project directory but additionally installs and activates
virtualenv and linters within your environment. Strict mode may be combined
with minimal mode:

    $ pypc -sm project

Options
=======

    usage: pypc [-h] [-v] [-m] [-s] [--venv VENV] [--path PATH] [--author AUTHOR]
                [--email EMAIL] [-V VERSION] [--desc DESC] [--url URL]
                [--rm README] [--fs FS]
                pkgname

If you only want to create a package with a setup.py (no virtual env,
etc), use the -m or --minimal flag.

Note: -v outputs the version of pypc whereas -V or --version is used to
 specify the initial version of the package you are creating. This is
 slightly confusion, and improvements are welcome.

Library
=======
Pypc can be imported and used as library.

    >>> from pypc.create import Package
    >>> p = Package("pkgname", path="~/optional") # defaults to os.getcwd()
    >>> p.new(**{'readme': 'README.md'}) # see pypc.settings.DEFAULTS for a list of default options (key,vals)

Philosopy
=========
* KISS. Small and simple enough (i.e. Flask/webpy, not django) that it can be integrated into pip,
* Defaults. a default modus of operandi which works offline,
* PEP 20. "There should be one-- and preferably only one --obvious way to do it." In this respect, the general file structure should remain static and accept overrides/overloading of templates and if specific modules/packages (like flask) require specific (additional) file structure, a builder can import/bootstrap using pypc (as it would pip)

Standards
=========
Resources about the standards and walkthroughs:

* http://guide.python-distribute.org/creation.html
* http://www.scotttorborg.com/python-packaging/minimal.html
* http://stackoverflow.com/questions/9411494/how-do-i-create-a-pip-installable-project
* http://docs.python-guide.org/en/latest/writing/structure/
* http://www.kennethreitz.org/essays/repository-structure-and-python
* http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html
* http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/

Alternatives
============
* https://github.com/audreyr/cookiecutter
* https://github.com/seanfisk/python-project-template - Git based, clone repo (requires altering git history)

Questions for you
=================
1) Does the file structure pypc generates break any conventions?
2) Is the code for pypc readable/accessible?
3) Feature suggestions? (would love to auto-init venv)

Disclaimer
==========
Pypc is a pre-alpha proof of concept. It's slow as it installs pyflakes, pep8, virtualenv sets up a virtualenv, and then generates a freeze list of requirements).
Right now there is little to no test-coverage; being it is a proof of concept, I'll try to continue as TDD.

Discussion
==========
Join the conversation! Other design considerations and details can be found on the pypa mailing list: https://groups.google.com/forum/#!searchin/pypa-dev/mek/pypa-dev/eaku1xvUVHU/Kbj_17sP23kJ

.. |Build Status| image:: https://travis-ci.org/mekarpeles/pypc.png

.. |Wheel Status| image:: https://pypip.in/wheel/pypc/badge.svg
    :target: https://pypi.python.org/pypi/pypc/
    :alt: Wheel Status


text:
<?php

/*
 * @file
 *
 * Theme

 $engines = array(
    'default' => array(
        'engine'      => 'Pyramid\Component\Templating\TwigEngine',
        'loader'      => 'Twig_Loader_Filesystem',
        'loaderArgs'  => array(),
        'environment' => 'Twig_Environment',
        'envArgs'     => array(),
    )
 );
 */

namespace Pyramid\Component\Templating;

class Theme {

    /*
     * 模板引擎存放
     *
     * @var array
     */
    protected static $engines = array();

    /**
     * 配置信息
     *
     * @var array()
     */
    protected static $configuration = array();

    /*
     * 获取engine实例
     */
    public static function getEngine($target = 'default') {
        if (!isset(self::$engines[$target])) {
            self::$engines[$target] = self::initEngine($target);
        }

        return self::$engines[$target];
    }

    /*
     * 初始化engine实例
     */
    public static function initEngine($target) {
        if (empty(self::$engines)) {
            self::parseEnginesInfo();
        }
        if (!empty(self::$configuration[$target]['loader'])) {
            $classLoader = self::$configuration[$target]['loader'];
        } else {
            $classLoader  = 'Twig_Loader_Filesystem';
        }
        if (!empty(self::$configuration[$target]['environment'])) {
            $classEnv = self::$configuration[$target]['environment'];
        } else {
            $classEnv  = 'Twig_Environment';
        }
        if (!empty(self::$configuration[$target]['engine'])) {
            $classEngine = self::$configuration[$target]['engine'];
        } else {
            $classEngine  = 'Pyramid\Component\Templating\TwigEngine';
        }
        $loader = new $classLoader(self::$configuration[$target]['loaderArgs']);
        $env    = new $classEnv($loader, self::$configuration[$target]['envArgs']);
        $engine = new $classEngine($env);

        return $engine;
    }

    /*
     * 处理engines配置
     */
    public static function parseEnginesInfo() {
        global $engines;
        $es = is_array($engines) ? $engines : array();
        $es += array('default'=>array('loaderArgs'=>array(),'envArgs'=>array()));
        self::$configuration = $es;
    }

}


text:
@import Foundation;
@import UIKit;

//! Project version number for OBAKit.
FOUNDATION_EXPORT double OBAKitVersionNumber;

//! Project version string for OBAKit.
FOUNDATION_EXPORT const unsigned char OBAKitVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <OBAKit/PublicHeader.h>

#import <OBAKit/OBAAgencyV2.h>
#import <OBAKit/OBAAgencyWithCoverageV2.h>
#import <OBAKit/OBAAlarm.h>
#import <OBAKit/OBAAnimation.h>
#import <OBAKit/OBAApplicationConfiguration.h>
#import <OBAKit/OBAApplication.h>
#import <OBAKit/OBAArrivalAndDepartureConvertible.h>
#import <OBAKit/OBAArrivalAndDepartureInstanceRef.h>
#import <OBAKit/OBAArrivalAndDepartureV2.h>
#import <OBAKit/OBAArrivalAndDepartureSectionBuilder.h>
#import <OBAKit/OBAArrivalsAndDeparturesForStopV2.h>
#import <OBAKit/OBAAutoLabel.h>
#import <OBAKit/OBABookmarkGroup.h>
#import <OBAKit/OBABookmarkV2.h>
#import <OBAKit/OBACanvasView.h>
#import <OBAKit/OBAClassicDepartureView.h>
#import <OBAKit/OBACommon.h>
#import <OBAKit/OBAConsoleLogger.h>
#import <OBAKit/OBACoordinateBounds.h>
#import <OBAKit/OBAClassicDepartureCell.h>
#import <OBAKit/OBADataSourceConfig.h>
#import <OBAKit/OBADateHelpers.h>
#import <OBAKit/OBADeepLinkRouter.h>
#import <OBAKit/OBADepartureCellHelpers.h>
#import <OBAKit/OBADepartureStatus.h>
#import <OBAKit/OBADepartureTimeLabel.h>
#import <OBAKit/OBAEmailHelper.h>
#import <OBAKit/OBAEntryWithReferencesV2.h>
#import <OBAKit/OBAErrorMessages.h>
#import <OBAKit/OBAExtendedNavBarView.h>
#import <OBAKit/OBAFrequencyV2.h>
#import <OBAKit/OBAHasReferencesV2.h>
#import <OBAKit/OBAHasServiceAlerts.h>
#import <OBAKit/OBAImageHelpers.h>
#import <OBAKit/OBAJsonDataSource.h>
#import <OBAKit/OBAJsonDigester.h>
#import <OBAKit/OBAListWithRangeAndReferencesV2.h>
#import <OBAKit/OBALocationManager.h>
#import <OBAKit/OBALogging.h>
#import <OBAKit/OBAMacros.h>
#import <OBAKit/OBAMapDataLoader.h>
#import <OBAKit/OBAMapHelpers.h>
#import <OBAKit/OBAMapRegionManager.h>
#import <OBAKit/OBAModelDAO.h>
#import <OBAKit/OBAModelFactory.h>
#import <OBAKit/OBAModelPersistenceLayer.h>
#import <OBAKit/OBAModelService.h>
#import <OBAKit/OBAModelServiceRequest.h>
#import <OBAKit/OBAOccupancyStatus.h>
#import <OBAKit/OBAPlaceholderView.h>
#import <OBAKit/OBAPlacemark.h>
#import <OBAKit/OBAReachability.h>
#import <OBAKit/OBAReferencesV2.h>
#import <OBAKit/OBARegionBoundsV2.h>
#import <OBAKit/OBARegionChangeRequest.h>
#import <OBAKit/OBARegionHelper.h>
#import <OBAKit/OBARegionV2.h>
#import <OBAKit/OBAReportProblemWithStopV2.h>
#import <OBAKit/OBAReportProblemWithTripV2.h>
#import <OBAKit/OBARouteFilter.h>
#import <OBAKit/OBARouteType.h>
#import <OBAKit/OBARouteV2.h>
#import <OBAKit/OBASearchResult.h>
#import <OBAKit/OBAServiceAlertsModel.h>
#import <OBAKit/OBASituationConsequenceV2.h>
#import <OBAKit/OBASituationV2.h>
#import <OBAKit/OBASphericalGeometryLibrary.h>
#import <OBAKit/OBAStackedMarqueeLabels.h>
#import <OBAKit/OBAStopAccessEventV2.h>
#import <OBAKit/OBAStopIconFactory.h>
#import <OBAKit/OBAStopPreferencesV2.h>
#import <OBAKit/OBAStopV2.h>
#import <OBAKit/OBAStopsForRouteV2.h>
#import <OBAKit/OBAStrings.h>
#import <OBAKit/OBATheme.h>
#import <OBAKit/OBATripContinuationMapAnnotation.h>
#import <OBAKit/OBATripDeepLink.h>
#import <OBAKit/OBATripDetailsV2.h>
#import <OBAKit/OBATripInstanceRef.h>
#import <OBAKit/OBATripScheduleV2.h>
#import <OBAKit/OBATripStatusV2.h>
#import <OBAKit/OBATripStopTimeMapAnnotation.h>
#import <OBAKit/OBATripStopTimeV2.h>
#import <OBAKit/OBATripV2.h>
#import <OBAKit/OBAUIBuilder.h>
#import <OBAKit/OBAUpcomingDeparture.h>
#import <OBAKit/OBAURLHelpers.h>
#import <OBAKit/OBAUser.h>
#import <OBAKit/OBAValue1ContentsView.h>
#import <OBAKit/OBAVehicleMapAnnotation.h>
#import <OBAKit/OBAVibrantBlurContainerView.h>
#import <OBAKit/OBAVehicleStatusV2.h>
#import <OBAKit/OBAWalkingDirections.h>

// Navigation
#import <OBAKit/OBASearchType.h>
#import <OBAKit/OBAAlarmNavigationTarget.h>
#import <OBAKit/OBADeepLinkNavigationTarget.h>
#import <OBAKit/OBAGenericNavigationTarget.h>
#import <OBAKit/OBANavigationTarget.h>
#import <OBAKit/OBANavigationTargetAnnotation.h>
#import <OBAKit/OBANavigationTargetAware.h>
#import <OBAKit/OBAStopSearchNavigationTarget.h>
#import <OBAKit/OBAVehicleIDNavigationTarget.h>

// Categories
#import <OBAKit/NSArray+OBAAdditions.h>
#import <OBAKit/NSCoder+OBAAdditions.h>
#import <OBAKit/NSDate+DateTools.h>
#import <OBAKit/NSDictionary+OBAAdditions.h>
#import <OBAKit/NSObject+OBADescription.h>
#import <OBAKit/NSString+OBAAdditions.h>
#import <OBAKit/NSURLQueryItem+OBAAdditions.h>
#import <OBAKit/UIImage+OBAAdditions.h>
#import <OBAKit/UILabel+OBAAdditions.h>
#import <OBAKit/UIStackView+OBAAdditions.h>
#import <OBAKit/UIView+OBAAdditions.h>

// 3rd Party Components
#import <OBAKit/UIScrollView+EmptyDataSet.h>
#import <OBAKit/FBShimmering.h>
#import <OBAKit/FBShimmeringLayer.h>
#import <OBAKit/FBShimmeringView.h>
#import <OBAKit/CLLocationManager+AnyPromise.h>
#import <OBAKit/MKMapSnapshotter+AnyPromise.h>

// MVVM
#import <OBAKit/OBABaseRow.h>
#import <OBAKit/OBABaseTableCell.h>
#import <OBAKit/OBABookmarkedRouteRow.h>
#import <OBAKit/OBABookmarkedRouteCell.h>
#import <OBAKit/OBAButtonBarRow.h>
#import <OBAKit/OBAButtonRow.h>
#import <OBAKit/OBAStaticTableViewController.h>
#import <OBAKit/OBATableRow.h>
#import <OBAKit/OBATableCell.h>
#import <OBAKit/OBATableSection.h>
#import <OBAKit/OBATableViewCell.h>
#import <OBAKit/OBAViewModelRegistry.h>


text:
from matchingtools.core import (
    Tensor,
    Operator,
    OperatorSum,
    TensorBuilder,
    FieldBuilder,
    D,
    D_op,
    Op,
    OpSum,
    number_op,
    power_op,
    tensor_op,
    flavor_tensor_op,
    kdelta,
    generic,
    epsUpDot,
    epsDown,
    epsDownDot,
    sigma4bar,
    sigma4,
    boson,
    fermion,
)
from matchingtools.integration import (
    RealScalar,
    ComplexScalar,
    RealVector,
    ComplexVector,
    VectorLikeFermion,
    MajoranaFermion,
    integrate,
)
from matchingtools.transformations import (
    collect_numbers,
    collect_powers,
    collect_numbers_and_powers,
    apply_rule,
    apply_rules,
    collect_by_tensors,
    collect,
)
from matchingtools.output import Writer

__all__ = [
    "Tensor",
    "Operator",
    "OperatorSum",
    "TensorBuilder",
    "FieldBuilder",
    "D",
    "D_op",
    "Op",
    "OpSum",
    "number_op",
    "power_op",
    "tensor_op",
    "flavor_tensor_op",
    "kdelta",
    "generic",
    "epsUpDot",
    "epsDown",
    "epsDownDot",
    "sigma4bar",
    "sigma4",
    "boson",
    "fermion",
    "RealScalar",
    "ComplexScalar",
    "RealVector",
    "ComplexVector",
    "VectorLikeFermion",
    "MajoranaFermion",
    "integrate",
    "collect_numbers",
    "collect_powers",
    "collect_numbers_and_powers",
    "apply_rule",
    "apply_rules",
    "collect_by_tensors",
    "collect",
    "Writer",
]


text:
from win32com.client import GetObject
import win32com.test.util

import unittest

class Simple(win32com.test.util.TestCase):
    def testit(self):
        cses = GetObject("WinMgMts:").InstancesOf("Win32_Process")
        vals = []
        for cs in cses:
            val = cs.Properties_("Caption").Value
            vals.append(val)
        self.failIf(len(vals)<5, "We only found %d processes!" % len(vals))

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


text:
var fs = require('fs');
var shell = require('shelljs');
var grunt = require('grunt');
var spawn = require('child_process').spawn;

module.exports = {

  init: function() {
    shell.exec('npm install');
  },

  getVersion: function(){
    var package = JSON.parse(fs.readFileSync('package.json', 'UTF-8'));
    var match = package.version.match(/^([^\-]*)(-snapshot)?$/);
    var semver = match[1].split('.');
    var hash = shell.exec('git rev-parse --short HEAD', {silent: true}).output.replace('\n', '');

    var fullVersion = (match[1] + (match[2] ? '-' + hash : ''));
    var numVersion = semver[0] + '.' + semver[1] + '.' + semver[2];
    var version = {
      number: numVersion,
      full: fullVersion,
      major: semver[0],
      minor: semver[1],
      dot: semver[2],
      codename: package.codename,
      cdn: package.cdnVersion
    };

    return version;
  },

  startKarma: function(config, singleRun, done){
    var browsers = grunt.option('browsers');
    var reporters = grunt.option('reporters');
    var noColor = grunt.option('no-colors');
    var p = spawn('node', ['node_modules/karma/bin/karma', 'start', config,
      singleRun ? '--single-run=true' : '',
      reporters ? '--reporters=' + reporters : '',
      browsers ? '--browsers=' + browsers : '',
      noColor ? '--no-colors' : ''
    ]);
    p.stdout.pipe(process.stdout);
    p.stderr.pipe(process.stderr);
    p.on('exit', function(code){
      if(code !== 0) grunt.fail.warn("Karma test(s) failed. Exit code: " + code);
      done();
    });
  },

  wrap: function(src, name){
    src.unshift('src/' + name + '.prefix');
    src.push('src/' + name + '.suffix');
    return src;
  },

  addStyle: function(src, styles, minify){
    styles = styles.map(processCSS.bind(this)).join('\n');
    src += styles;
    return src;

    function processCSS(file){
      var css = fs.readFileSync(file).toString();
      if(minify){
        css = css
          .replace(/\r?\n/g, '')
          .replace(/\/\*.*?\*\//g, '')
          .replace(/:\s+/g, ':')
          .replace(/\s*\{\s*/g, '{')
          .replace(/\s*\}\s*/g, '}')
          .replace(/\s*\,\s*/g, ',')
          .replace(/\s*\;\s*/g, ';');
      }
      //escape for js
      css = css
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/\r?\n/g, '\\n');
      return "angular.element(document).find('head').append('<style type=\"text/css\">" + css + "</style>');";
    }
  },

  process: function(src, NG_VERSION, strict){
    var processed = src
      .replace(/"NG_VERSION_FULL"/g, NG_VERSION.full)
      .replace(/"NG_VERSION_MAJOR"/, NG_VERSION.major)
      .replace(/"NG_VERSION_MINOR"/, NG_VERSION.minor)
      .replace(/"NG_VERSION_DOT"/, NG_VERSION.dot)
      .replace(/"NG_VERSION_CDN"/, NG_VERSION.cdn)
      .replace(/"NG_VERSION_CODENAME"/, NG_VERSION.codename);
    if (strict !== false) processed = this.singleStrict(processed, '\n\n', true);
    return processed;
  },

  build: function(config, fn){
    var files = grunt.file.expand(config.src);
    var styles = config.styles;
    //concat
    var src = files.map(function(filepath){
      return grunt.file.read(filepath);
    }).join(grunt.util.normalizelf('\n'));
    //process
    var processed = this.process(src, grunt.config('NG_VERSION'), config.strict);
    if (styles) processed = this.addStyle(processed, styles.css, styles.minify);
    //write
    grunt.file.write(config.dest, processed);
    grunt.log.ok('File ' + config.dest + ' created.');
    fn();
  },

  singleStrict: function(src, insert){
    return src
      .replace(/\s*("|')use strict("|');\s*/g, insert) // remove all file-specific strict mode flags
      .replace(/(\(function\([^)]*\)\s*\{)/, "$1'use strict';"); // add single strict mode flag
  },

  sourceMap: function(mapFile, fileContents) {
    // use the following once Chrome beta or stable supports the //# pragma
    // var sourceMapLine = '//# sourceMappingURL=' + mapFile + '\n';
    var sourceMapLine = '/*\n//@ sourceMappingURL=' + mapFile + '\n*/\n';
    return fileContents + sourceMapLine;
  },

  min: function(file, done) {
    var minFile = file.replace(/\.js$/, '.min.js');
    var mapFile = minFile + '.map';
    var mapFileName = mapFile.match(/[^\/]+$/)[0];
    shell.exec(
        'java ' +
            this.java32flags() + ' ' +
            '-jar components/closure-compiler/compiler.jar ' +
            '--compilation_level SIMPLE_OPTIMIZATIONS ' +
            '--language_in ECMASCRIPT5_STRICT ' +
            '--source_map_format=V3 ' +
            '--create_source_map ' + mapFile + ' ' +
            '--js ' + file + ' ' +
            '--js_output_file ' + minFile,
      function(code) {
        if (code !== 0) grunt.fail.warn('Error minifying ' + file);

        // closure creates the source map relative to build/ folder, we need to strip those references
        grunt.file.write(mapFile, grunt.file.read(mapFile).replace('"file":"build/', '"file":"').
                                                           replace('"sources":["build/','"sources":["'));

        // move add use strict into the closure + add source map pragma
        grunt.file.write(minFile, this.sourceMap(mapFileName, this.singleStrict(grunt.file.read(minFile), '\n')));
        grunt.log.ok(file + ' minified into ' + minFile);
        done();
    }.bind(this));
  },

  //returns the 32-bit mode force flags for java compiler if supported, this makes the build much faster
  java32flags: function(){
    if (process.platform === "win32") return '';
    if (shell.exec('java -version -d32 2>&1', {silent: true}).code !== 0) return '';
    return ' -d32 -client';
  },

  //csp connect middleware
  csp: function(){
    return function(req, res, next){
      res.setHeader("X-WebKit-CSP", "default-src 'self';");
      res.setHeader("X-Content-Security-Policy", "default-src 'self'");
      next();
    };
  },

  //rewrite connect middleware
  rewrite: function(){
    return function(req, res, next){
      var REWRITE = /\/(guide|api|cookbook|misc|tutorial).*$/,
          IGNORED = /(\.(css|js|png|jpg)$|partials\/.*\.html$)/,
          match;

      if (!IGNORED.test(req.url) && (match = req.url.match(REWRITE))) {
        console.log('rewriting', req.url);
        req.url = req.url.replace(match[0], '/index.html');
      }
      next();
    };
  }
};


text:
'use strict';

angular.module('courses').directive('upload',
    function() {
        return {
            scope: {
                file:'='
            },
            link: function(scope, element) {

                /* jshint ignore:start */
                $(element).on('change', function(changeEvent) {

                    console.log(changeEvent);
                    var files = changeEvent.target.files;
                    console.log(files.length);
                    if (files.length) {
                        var r = new FileReader();
                        r.onload = function(e) {

                            var contents = e.target.result;

                            //console.log(contents);
                            var lines = contents.split('\r');
                            console.log(lines.length);
                            //
                            for (var i=1; i<lines.length; i++) {

                                console.log(lines[i]);
                            }

                        };

                        r.readAsText(files[0]);
                    }
                });
                /* jshint ignore:end */
            }
        };
    }
);


text:
var config = require('../config'); // DB Config
var express = require('express');
var router = express.Router();
var request = require('request');
var dbURL = config.db.user+':'+config.db.pass+'@'+config.db.host+':'+config.db.port+'/'+config.db.db;
var collections = ["listings", "users"];
var db = require("mongojs").connect(dbURL, collections);

var mongoose = require('mongoose'),
    passport = require('passport'),
    Message = require('../lib/db/message-model'),
    User = require('../lib/db/user-model'),
    Listing = require('../lib/db/listing-model');

/* Main Account Page. */
router.get('/', function(req, res) {
  res.render('admin/index', {
    user: req.user,
    admin: new AdminCheck(req.user)
  })
});

/* Bulk Import Page. */
router.get('/bulk', function(req, res) {
  res.render('admin/bulk', {
    bodyClasses: 'page-wide',
    user: req.user,
    admin: new AdminCheck(req.user)
  })
});

module.exports = router;

var y2g = function(){}

/*  ROLES FUNCTIONS
    Roles are strings with the various role names
    So you can have multiple roles in one user such
    as 'listings users'.  This function checks for
    access to specific sections based on those roles
*/
function AdminCheck(user) {
  if (user) {
    this.access = checkRoles(user, ['admin', 'manager', 'listings', 'users', 'messages'])
    this.admin = checkRoles(user, ['admin'])
    this.manager = checkRoles(user, ['admin', 'manager'])
    this.listings = checkRoles(user, ['admin', 'manager', 'listings'])
    this.users = checkRoles(user, ['admin', 'manager', 'users'])
    this.messages = checkRoles(user, ['admin', 'manager', 'messages'])
  } else {
    return false
  }
}
function checkRoles(user, roles) {
  if (user.role) {
    if (roles.some(function(v) { return user.role.indexOf(v) >= 0; })) {
        return true
    } else {
      return false
    }
  } else {
    return false
  }
}


text:
package com.munepom.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.nio.file.Paths;

public interface ObjectCopyUtil {

	default Object shallowCopy(Object obj) {
		try {
			Class<?> cls = obj.getClass();
			Object clone = cls.newInstance();

			Field[] fields = cls.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				field.setAccessible(true);
				if (!Modifier.isFinal(field.getModifiers())) {
					field.set(clone, field.get(obj));
				}
			}

			while (true) {
				cls = cls.getSuperclass();
				if (Object.class.equals(cls)) {
					break;
				}
				Field[] sFields = cls.getDeclaredFields();
				for (int i = 0; i < sFields.length; i++) {
					Field field = sFields[i];
					field.setAccessible(true);
					if (!Modifier.isFinal(field.getModifiers())) {
						field.set(clone, field.get(obj));
					}
				}
			}
			return clone;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	default Object deepCopy(Object obj) {
		try {
			Class<?> cls = obj.getClass();
			Object clone = cls.newInstance();

			Field[] fields = cls.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				field.setAccessible(true);
				if (!Modifier.isFinal(field.getModifiers())) {
					if (field.getType().isPrimitive()) {
						field.set(clone, field.get(obj));
					} else {
						field.set(clone, deepCopyObject(field.get(obj)));
					}
				}
			}

			while (true) {
				cls = cls.getSuperclass();
				if (Object.class.equals(cls)) {
					break;
				}
				Field[] sFields = cls.getDeclaredFields();
				for (int i = 0; i < sFields.length; i++) {
					Field field = sFields[i];
					if (!Modifier.isFinal(field.getModifiers())) {
						field.setAccessible(true);
						if (field.getType().isPrimitive()) {
							field.set(clone, field.get(obj));
						} else {
							field.set(clone, deepCopyObject(field.get(obj)));
						}
					}
				}
			}
			return clone;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	default Object deepCopyObject(Object obj) {
		Object ret = null;

		try (
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos =  new ObjectOutputStream(baos);
		){
			if( obj instanceof Path ){
				oos.writeObject(((Path) obj).toString());
			}
			else {
				oos.writeObject(obj);
			}
			try ( ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())) ) {
				ret = ois.readObject();
				if( obj instanceof Path ){
					ret = Paths.get((String) ret);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ret;
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Neagenea Lich. 5 (1854)

#### Original name
Ramalina inanis Mont.

### Remarks
null


text:
Named Graphs Management

      <button type="button" class="btn btn-success btn-large" ng-click="newVersionGroup();">Add Graph Set</button>

Named Graph Sets

          Identifier
          Label
          Description
          URI
          Created
          Versions

          {{vg.identifier}}
          {{vg.label}}
          {{vg.description}}
          {{vg.uri}}
          {{vg.created | formatDate}}

{{vgg}}

          <button type="button" class="btn btn-success btn-large" ng-click="new(null);">Add new graph</button>

User Graphs

              Action
              Label
              URI
              Triples
              Created
              Modified
              Issued
              Public Access
              Read Access
              Write Access

                <button type="button" class="btn btn-default btn-xs" ng-confirm-click="delete(namedgraph.name)" ng-confirm-message="Are you sure you want to delete this graph?"></button>
                <button type="button" class="btn btn-default btn-xs" ng-click="edit(namedgraph.name);"></button>
                <button ng-show="namedgraph.graph.issued==''" type="button" class="btn btn-default btn-xs" ng-confirm-click="issue(namedgraph.name);"  ng-confirm-message="The graph will be issued now..."></button>

              {{namedgraph.graph.label}}
              {{namedgraph.name}}
              {{namedgraph.graph.triples}}
              {{namedgraph.graph.created | formatDate}}
              {{namedgraph.graph.modified | formatDate}}
              {{namedgraph.graph.issued | formatDate}}
              {{accessModes[namedgraph.publicAccess]}}

{{user}}

{{user}}

                <button type="button" class="btn btn-link reset" ng-click="refreshAccessibleGraphs()">

                </button>

            Accessible Graphs

                URI
                Label
                Description
                Created
                Modified
                Owner
                Access

                {{namedgraph.name}}
                {{namedgraph.graph.label}}
                {{namedgraph.graph.description}}
                {{namedgraph.graph.created}}
                {{namedgraph.graph.modified}}
                {{namedgraph.owner}}
                {{namedgraph.access}}

                <button type="button" class="btn btn-link reset" ng-click="refreshAllGraphs()">

                </button>

            All Graphs

                Action
                URI
                Label
                Description
                Created
                Modified
                Owner
                Public access
                Read access
                Write access

                    <button type="button" class="btn btn-default btn-xs" ng-click="deleteForeign(namedgraph.name)"></button>
                    <button type="button" class="btn btn-default btn-xs" data-toggle="modal" data-target="#modalGraph" ng-click="editAdmin(namedgraph.name);"></button>

                {{namedgraph.name}}
                {{namedgraph.graph.label}}
                {{namedgraph.graph.description}}
                {{namedgraph.graph.created}}
                {{namedgraph.graph.modified}}
                {{namedgraph.owner}}
                {{accessModes[namedgraph.publicAccess]}}

{{user}}

{{user}}

      <button type="button" class="btn btn-success btn-large" ng-click="newGroup();">Add new graph group</button>

              <button type="button" class="btn btn-link reset" ng-click="refreshGraphGroups()">

              </button>

          Graph Groups

              Action
              URI
              Label
              Description
              Created
              Modified
              Graphs

                  <button type="button" class="btn btn-default btn-xs" ng-click="deleteGroup('gg.name')"></button>
                  <button type="button" class="btn btn-default btn-xs" data-toggle="modal" data-target="#modalGroup" ng-click="editGroup('gg.name');"></button>

              {{gg.name}}
              {{gg.label}}
              {{gg.description}}
              {{gg.created}}
              {{gg.modified}}

{{graph}}


text:
import {AppController} from "../Controllers/AppController";
import {WindowDrawer} from "./WindowDrawer";
import {MapController} from "../Controllers/MapController";
import {MarkersService} from "../Services/MarkersService";
import {CategoriesService} from "../Services/CategoriesService";
import {GeoCodeService} from "../Services/GeoCodeService";
import {TagsService} from "../Services/TagsService";
declare var GOOGLE_MAP_API_KEY:number;
declare var google:any;

//import {CommentsView} from "../Views/CommentsView";
declare var $:JQueryStatic|any;

export class ActionBinder {
    static firstBind:boolean = true;

    static bindActions(container: Object) {
        if(this.firstBind) {
            AppController.instances[0].addClickCallback((mapController:MapController,e)=>{
                if(mapController.mode==1) { // add marker
                    mapController.setMode(0);
                    $('#map').addClass('inactive');
                    AppController.instances[0].map.setZoom(18);
                    AppController.instances[0].map.setCenter(new google.maps.LatLng(e.latLng.lat(), e.latLng.lng()));
                    MarkersService.reserveMarkerId([(markerId)=>{
                        mapController.putMarker({
                            'latitude':e.latLng.lat(),
                            'longitude':e.latLng.lng(),
                            'title':'',
                            'id':markerId
                        });

                        GeoCodeService.getGeoCodeData(e.latLng.lat(),e.latLng.lng(),GOOGLE_MAP_API_KEY,[(GeoCodeData) => {
                            CategoriesService.getCategories([(CategoriesData) => {
                                WindowDrawer.drawCreateMarkerWindow({
                                    'id':markerId,
                                    'latitude':e.latLng.lat(),
                                    'longitude':e.latLng.lng()
                                }, GeoCodeData, CategoriesData);
                            }]);
                        }]);
                    }]);
                }
            });
            $('#show-my-bookmarked-markers').click((event)=>{
                $('#map').removeClass('inactive');
                MarkersService.getBookmarkedMarkers([(MarkersData)=>{
                    WindowDrawer.drawMarkersListWindow('Избранные метки',MarkersData,'favourites');
                    ActionBinder.pushState('#favourites');
                }]);
            });

            $('#show-my-markers').click((event)=>{
                $('#map').removeClass('inactive');
                MarkersService.getMyMarkers([(MarkersData)=>{
                    WindowDrawer.drawMarkersListWindow('Мои метки',MarkersData,'my-markers');
                    ActionBinder.pushState('#my-markers');
                }]);
            });

            $('#show-search').click((event)=>{
                $('#map').removeClass('inactive');
                CategoriesService.getCategories([(CategoriesData) => {
                    TagsService.getPopularTags([(TagsData) => {
                        WindowDrawer.drawSearchWindow(CategoriesData,TagsData);
                    }]);
                }]);
            });

            $('#show-my-comments').click((event)=>{
                $('#map').removeClass('inactive');
                MarkersService.getCommentedMarkers([(MarkersData)=>{
                    WindowDrawer.drawMarkersListWindow('Мои Комментарии',MarkersData,'my-comments');
                    ActionBinder.pushState('#my-comments');
                }]);
            });

            $('[data-click-id]').click(function (event) {
                var $this = $(this);
                $('#'+$this.data('click-id')).click();
            });
        }
        this.firstBind = false;
    }

    static pushState(state:string) {
        $('#header-menu [data-base-href]').each(function () {
            var $this = $(this);
            console.log(($this.data('base-href')+state.substr(1)));
            $this.attr('href',($this.data('base-href')+state.substr(1)));
        });
        if (history.pushState) {
            history.pushState(null, null, state);
        } else {
            location.hash = state;
        }
    }
}


text:
import importlib
from itertools import imap
import multiprocessing.pool
import os
from sklearn.externals.joblib import Parallel, delayed

DEFAULT_POOL_TYPE = "multicore"
DEFAULT_CLUSTER_TYPE = "ipython"

class SinglecorePool(object):
  """A fall-back worker pool that uses a single core of a single machine."""

  def map(self, func, iterable, progress=None):
    """Apply a function to a list using a single local core."""
    if progress is None:
      return map(func, iterable)
    p = progress(len(iterable)).start()
    p.update(0)
    results = imap(func, iterable)
    out = list()
    for i, r in enumerate(results):
      p.update(i+1)
      out.append(r)
    p.finish()
    return out

class MulticorePool(object):
  """A worker pool that uses multiple cores on a single machine."""

  def __init__(self, processes=None):
    self.processes = processes

  def map(self, func, iterable, progress=None):
    """Apply a function to a list using multiple local cores."""
    # TODO: Add iterable interface for Parallel, to support progress meter.
    return Parallel(n_jobs=(self.processes or -1), pre_dispatch=1)(
        map(delayed(func), iterable))

def MakePool(name=None, **kw):
  """Return a new instance of the given worker pool.

  :param str name: Type of requested pool.
  :param int processes: Number of local cores to use for multicore pool.
     The default is read from `GLIMPSE_MULTICORE_PROCS` environment variable.
  :param str cluster_type: Name of cluster sub-package (e.g., "ipython").
  :param dict cluster_args: Keyword arguments for cluster constructor (default
     is given by evaluating as a python expression the `GLIMPSE_CLUSTER_ARGS`
     environment variable).

  Valid entries for `name` include:

  "s" or "singlecore"
    One core of the local machine are used.
  "m" or "multicore"
    Multiple cores of the local machine are used.
  "c" or "cluster"
    A group of remote machines are used.

  If `name` is unset, the default is read from the `GLIMPSE_POOL` environment
  variable, or else the `DEFAULT_POOL_TYPE` global variable.

  .. seealso::
     :func:`GetClusterPackage` for information about on `cluster_type` argument.

  """
  if name == None:
    name = os.environ.get('GLIMPSE_POOL', DEFAULT_POOL_TYPE)
  else:
    name = name.lower()
  if name in ("s", "singlecore", "singlecore_pool", "singlecorepool"):
    return SinglecorePool()
  if name in ("m", "multicore", "multicore_pool", "multicorepool"):
    if 'processes' not in kw:
      procs = os.environ.get('GLIMPSE_MULTICORE_PROCS')
      if procs is not None:
        kw['processes'] = int(procs)
    return MulticorePool(processes = kw.get('processes'))
  if name in ("c", "cluster"):
    pkg = GetClusterPackage(cluster_type=kw.get('cluster_type'))
    cluster_args = kw.get('cluster_args')
    if cluster_args is None:
      cluster_args = os.environ.get('GLIMPSE_CLUSTER_ARGS')
      if cluster_args is not None:
        cluster_args = eval(cluster_args)
    return pkg.MakePool(**(cluster_args or {}))
  raise ValueError("Invalid pool type: %s" % name)

def GetClusterPackage(cluster_type = None):
  """Choose a cluster package by name.

  :param str cluster_type: Type of cluster to create (e.g., `ipython`). The
     default is read from the `GLIMPSE_CLUSTER` environment variable, or the
     `DEFAULT_CLUSTER_TYPE` if unset.

  If `cluster_type` is "ipython", for example, then this method returns
  :mod:`glimpse.pools.ipythoncluster`. The returned module is guaranteed to
  contain a `MakePool()` function.

  """
  import os
  if cluster_type == None:
    cluster_type = os.environ.get('GLIMPSE_CLUSTER', DEFAULT_CLUSTER_TYPE)
  cluster_mod = importlib.import_module(".%scluster" % cluster_type,
      __package__)
  return cluster_mod


text:
/*
 * host/syscall_replayer.h
 * by WN @ Jun. 28, 2010
 *
 * syscall replayer helper in host
 */

#ifndef HOST_SYSCALL_REPLAYER_H
#define HOST_SYSCALL_REPLAYER_H

#include <common/defs.h>
#include <xasm/marks.h>

extern void
syscall_read_cycle(void);

#endif

// vim:ts=4:sw=4


text:
var $mod$158 = core.VW.Ecma2015.Utils.module(require('../create/local'));
var $mod$159 = core.VW.Ecma2015.Utils.module(require('../create/utc'));
var $mod$160 = core.VW.Ecma2015.Utils.module(require('../create/valid'));
var $mod$161 = core.VW.Ecma2015.Utils.module(require('./constructor'));
var $mod$162 = core.VW.Ecma2015.Utils.module(require('./min-max'));
var $mod$163 = core.VW.Ecma2015.Utils.module(require('./now'));
var $mod$164 = core.VW.Ecma2015.Utils.module(require('./prototype'));
function createUnix(input) {
    return $mod$158.createLocal(input * 1000);
}
function createInZone() {
    return $mod$158.createLocal.apply(null, arguments).parseZone();
}
exports.now = $mod$163.now;
exports.min = $mod$162.min;
exports.max = $mod$162.max;
exports.isMoment = $mod$161.isMoment;
exports.createUTC = $mod$159.createUTC;
exports.createUnix = createUnix;
exports.createLocal = $mod$158.createLocal;
exports.createInZone = createInZone;
exports.createInvalid = $mod$160.createInvalid;
exports.momentPrototype = $mod$164.default;


text:
Contributions are encouraged, while it must be noted, this project has a planned path and you should seek to contact the authors before undergoing any large development.  All contributions will be placed under the same license, contributers must agree to that license.

The following is expected from any pull requests.

1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork,
   and configure the remotes:

   ```bash
   # clone your fork
   git clone https://github.com/<your-username>/react-boilerplate.git
   # change directory to the repository folder
   cd react-boilerplate
   # set the official react-boilerplate repo to a remote branch called "upstream"
   git remote add upstream https://github.com/hutchgrant/react-boilerplate.git
   ```

2. If you cloned a while ago, make sure to update with the latest changes from upstream branch:

   ```bash
   git checkout master
   git pull upstream master
   ```

3. Create a new branch for your changes/fixes

   ```bash
   git checkout -b <topic-branch-name>
   ```

4. Locally merge (or rebase) the upstream development branch into your topic branch:

   ```bash
   git pull [--rebase] upstream master
   ```

6. Push your topic branch up to your fork:

   ```bash
   git push origin <topic-branch-name>
   ```

7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
    with a clear title and description against the `master` branch.


text:
package com.intellij.designer.designSurface.feedbacks;

import javax.swing.*;
import java.awt.*;

/**
 * @author Alexander Lobas
 */
public class RectangleFeedback extends JComponent {
  private final Color myColor;
  protected final int myLine;

  public RectangleFeedback(Color color, int line) {
    myColor = color;
    myLine = line;
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(myColor);

    paintFeedback(g);
  }

  protected void paintFeedback(Graphics g) {
    Dimension size = getSize();
    for (int i = 0; i < myLine; i++) {
      g.drawRect(i, i, size.width - i - i - 1, size.height - i - i - 1);
    }
  }
}


text:
layout: page
title: Seattle Police Officer 7377 Megan M. Marocco-Spearman
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/7377/
---

**Age as of Feb. 24, 2016:** 38


text:
#include "configargs.h"

#define GCCPLUGIN_VERSION_MAJOR   4
#define GCCPLUGIN_VERSION_MINOR   7
#define GCCPLUGIN_VERSION_PATCHLEVEL   1
#define GCCPLUGIN_VERSION  (GCCPLUGIN_VERSION_MAJOR*1000 + GCCPLUGIN_VERSION_MINOR)

static char basever[] = "4.7.1";
static char datestamp[] = "20120614";
static char devphase[] = "";
static char revision[] = "";

/* FIXME plugins: We should make the version information more precise.
   One way to do is to add a checksum. */

static struct plugin_gcc_version gcc_version = {basever, datestamp,
						devphase, revision,
						configuration_arguments};


text:
package com.nirima.jenkins.plugins.docker;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectImageCmd;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

/**
 * @author Slawomir Jaranowski
 */
@RunWith(Parameterized.class)
public class DockerImagePullStrategyTest {

    private final String imageName;
    private final DockerImagePullStrategy pullStrategy;
    private final boolean shouldPull;
    private final boolean existedImage;

    @Parameterized.Parameters(name = "existing image: ''{0}'', image to pull: ''{1}'', strategy: ''{2}''")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {false, "repo/name:latest", DockerImagePullStrategy.PULL_LATEST, true},
                {true, "repo/name:latest", DockerImagePullStrategy.PULL_LATEST, true},
                {false, "repo/name:1.0", DockerImagePullStrategy.PULL_LATEST, true},
                {true, "repo/name:1.0", DockerImagePullStrategy.PULL_LATEST, false},

                {false, "repo/name:latest", DockerImagePullStrategy.PULL_ALWAYS, true},
                {true, "repo/name:latest", DockerImagePullStrategy.PULL_ALWAYS, true},
                {false, "repo/name:1.0", DockerImagePullStrategy.PULL_ALWAYS, true},
                {true, "repo/name:1.0", DockerImagePullStrategy.PULL_ALWAYS, true},

                {false, "repo/name:latest", DockerImagePullStrategy.PULL_NEVER, false},
                {true, "repo/name:latest", DockerImagePullStrategy.PULL_NEVER, false},
                {false, "repo/name:1.0", DockerImagePullStrategy.PULL_NEVER, false},
                {true, "repo/name:1.0", DockerImagePullStrategy.PULL_NEVER, false},
        });
    }

    @Test
    public void shouldPullImageTest() {
        DockerClient dockerClient = mockDockerClient();
        assertEquals(shouldPull, pullStrategy.shouldPullImage(dockerClient, imageName));
    }

    public DockerImagePullStrategyTest(boolean existedImage, String imageName, DockerImagePullStrategy pullStrategy, boolean shouldPull) {
        this.existedImage =existedImage;
        this.imageName = imageName;
        this.pullStrategy = pullStrategy;
        this.shouldPull = shouldPull;
    }

    private DockerClient mockDockerClient() {
        InspectImageCmd cmd = mock(InspectImageCmd.class);
        if (existedImage)
            when(cmd.exec()).thenReturn(mock(InspectImageResponse.class));
        else
            when(cmd.exec()).thenThrow(new NotFoundException("not found"));
        DockerClient dockerClient = mock(DockerClient.class);
        when(dockerClient.inspectImageCmd(imageName)).thenReturn(cmd);

        return dockerClient;
    }
}