text:
package com.siyeh.ig.performance;

import com.intellij.codeInsight.Nullability;
import com.intellij.codeInsight.PsiEquivalenceUtil;
import com.intellij.codeInspection.dataFlow.ContractReturnValue;
import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil;
import com.intellij.codeInspection.dataFlow.NullabilityUtil;
import com.intellij.codeInspection.dataFlow.StandardMethodContract;
import com.intellij.codeInspection.util.InspectionMessage;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.ControlFlowUtils;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.TypeUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.PropertyKey;

import java.util.List;

import static com.intellij.util.ObjectUtils.tryCast;

public final class ObjectAllocationInLoopInspection extends BaseInspection {
  enum Kind {
    NEW_OPERATOR("object.allocation.in.loop.new.descriptor"),
    METHOD_CALL("object.allocation.in.loop.problem.call.descriptor"),
    METHOD_REFERENCE("object.allocation.in.loop.problem.methodref.descriptor"),
    CAPTURING_LAMBDA("object.allocation.in.loop.problem.lambda.descriptor"),
    STRING_CONCAT("object.allocation.in.loop.problem.string.concat"),
    ARRAY_INITIALIZER("object.allocation.in.loop.problem.array.initializer.descriptor");

    private final @PropertyKey(resourceBundle = InspectionGadgetsBundle.BUNDLE) String myMessage;

    Kind(@PropertyKey(resourceBundle = InspectionGadgetsBundle.BUNDLE) String message) {
      myMessage = message;
    }

    @Override
    public @InspectionMessage String toString() {
      return InspectionGadgetsBundle.message(myMessage);
    }
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    Kind kind = (Kind)infos[0];
    return kind.toString();
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new ObjectAllocationInLoopsVisitor();
  }

  private static class ObjectAllocationInLoopsVisitor extends BaseInspectionVisitor {
    @Override
    public void visitMethodCallExpression(PsiMethodCallExpression call) {
      super.visitMethodCallExpression(call);
      PsiMethod method = call.resolveMethod();
      if (method != null) {
        List<StandardMethodContract> contracts = JavaMethodContractUtil.getMethodContracts(method);
        ContractReturnValue value = JavaMethodContractUtil.getNonFailingReturnValue(contracts);
        if (ContractReturnValue.returnNew().equals(value) && isPerformedRepeatedlyInLoop(call)) {
          registerMethodCallError(call, Kind.METHOD_CALL);
        }
      }
    }

    @Override
    public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) {
      if (!(expression.getParent() instanceof PsiNewExpression) &&
          !(expression.getParent() instanceof PsiArrayInitializerExpression) &&
          isPerformedRepeatedlyInLoop(expression)) {
        registerError(expression, Kind.ARRAY_INITIALIZER);
      }
    }

    @Override
    public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
      super.visitMethodReferenceExpression(expression);
      if (!PsiMethodReferenceUtil.isStaticallyReferenced(expression) &&
          isPerformedRepeatedlyInLoop(expression)) {
        registerError(expression, Kind.METHOD_REFERENCE);
      }
    }

    @Override
    public void visitLambdaExpression(PsiLambdaExpression lambda) {
      super.visitLambdaExpression(lambda);
      if (isPerformedRepeatedlyInLoop(lambda) && LambdaUtil.isCapturingLambda(lambda)) {
        registerError(lambda.getParameterList(), Kind.CAPTURING_LAMBDA);
      }
    }

    @Override
    public void visitNewExpression(@NotNull PsiNewExpression expression) {
      super.visitNewExpression(expression);
      if (isPerformedRepeatedlyInLoop(expression)) {
        registerNewExpressionError(expression, expression.isArrayCreation() ? Kind.ARRAY_INITIALIZER : Kind.NEW_OPERATOR);
      }
    }

    @Override
    public void visitPolyadicExpression(PsiPolyadicExpression expression) {
      IElementType type = expression.getOperationTokenType();
      if (JavaTokenType.PLUS.equals(type) && TypeUtils.isJavaLangString(expression.getType()) &&
          !PsiUtil.isConstantExpression(expression) && isPerformedRepeatedlyInLoop(expression)) {
        registerError(expression, Kind.STRING_CONCAT);
      }
      super.visitPolyadicExpression(expression);
    }

    private static boolean isPerformedRepeatedlyInLoop(@NotNull PsiExpression expression) {
      if (!ControlFlowUtils.isInLoop(expression)) return false;
      if (ControlFlowUtils.isInExitStatement(expression)) return false;
      final PsiStatement newExpressionStatement = PsiTreeUtil.getParentOfType(expression, PsiStatement.class);
      if (newExpressionStatement == null) return false;
      final PsiStatement parentStatement = PsiTreeUtil.getParentOfType(newExpressionStatement, PsiStatement.class);
      if (!ControlFlowUtils.statementMayCompleteNormally(parentStatement)) return false;
      return !isAllocatedOnlyOnce(expression);
    }

    private static boolean isAllocatedOnlyOnce(PsiExpression expression) {
      final PsiAssignmentExpression assignment =
        PsiTreeUtil.getParentOfType(expression, PsiAssignmentExpression.class, true, PsiStatement.class);
      if (assignment == null) return false;
      final PsiReferenceExpression assignedRef = tryCast(assignment.getLExpression(), PsiReferenceExpression.class);
      if (assignedRef == null) return false;
      // to support cases like if(foo == null) foo = new Foo(new Bar());
      if (assignment.getRExpression() != expression &&
          NullabilityUtil.getExpressionNullability(assignment.getRExpression()) != Nullability.NOT_NULL) {
        return false;
      }
      final PsiIfStatement ifStatement = PsiTreeUtil.getParentOfType(assignment, PsiIfStatement.class);
      if (ifStatement == null) return false;
      boolean equals;
      if (PsiTreeUtil.isAncestor(ifStatement.getThenBranch(), assignment, true)) {
        equals = true;
      }
      else if (PsiTreeUtil.isAncestor(ifStatement.getElseBranch(), assignment, true)) {
        equals = false;
      }
      else {
        return false;
      }
      final PsiExpression condition = ifStatement.getCondition();
      PsiReferenceExpression nullCheckedRef = ExpressionUtils.getReferenceExpressionFromNullComparison(condition, equals);
      return nullCheckedRef != null && PsiEquivalenceUtil.areElementsEquivalent(nullCheckedRef, assignedRef);
    }
  }
}


text:
package org.apache.camel.component.properties;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;

public class PropertiesComponentDefaultFunctionsTest extends ContextTestSupport {

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    public void testFunction() throws Exception {
        System.setProperty("FOO", "mock:foo");

        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .to("{{sys:FOO}}")
                        .transform().constant("{{env:JAVA_HOME}}")
                        .to("mock:bar");
            }
        });
        context.start();

        String body = System.getenv("JAVA_HOME");

        getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");
        getMockEndpoint("mock:bar").expectedBodiesReceived(body);

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();

        System.getProperties().remove("FOO");
    }

    public void testFunctionGetOrElse() throws Exception {
        System.setProperty("FOO2", "mock:foo");

        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .to("{{sys:FOO2}}")
                        .to("{{env:BAR2:mock:bar}}");
            }
        });
        context.start();

        getMockEndpoint("mock:foo").expectedMessageCount(1);
        getMockEndpoint("mock:bar").expectedMessageCount(1);

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();

        System.getProperties().remove("FOO2");
    }

}

redpajama_set_name: RedPajamaGithub


text:
Collection of re-usuable front end components.

## Author
[Mark Hesketh](http://www.markhesketh.co.uk)

## License
[MIT](https://raw.githubusercontent.com/heskethm/front-end/master/LICENSE)


text:
<meta>
	<info author="xXMADEXx" name="NG FPS Script" type="script" version="1.0" />
	<script src="draw_c.lua" type="client" />
</meta>


text:
from os import environ
from jnius import autoclass

ANDROID_VERSION = autoclass('android.os.Build$VERSION')
SDK_INT = ANDROID_VERSION.SDK_INT

if 'PYTHON_SERVICE_ARGUMENT' in environ:
    PythonService = autoclass('org.renpy.android.PythonService')
    activity = PythonService.mService
else:
    PythonActivity = autoclass('org.renpy.android.PythonActivity')
    activity = PythonActivity.mActivity


text:
__author__ = 'Neil Butcher'

from PyQt4 import QtGui

class CommandChangeEvent(QtGui.QUndoCommand):
    def __init__(self, event, key, value):
        super(CommandChangeEvent, self).__init__('Changed the ' + key + ' of ' + event.name)
        self.event = event
        self.key = key
        self.value = value
        if key == 'name':
            self.startingValue = event.name
        elif key == 'title':
            self.startingValue = event.title
        elif key == 'description':
            self.startingValue = event.description
        elif key == 'notes':
            self.startingValue = event.notes
        elif key == 'time':
            self.startingValue = event.time
        elif key == 'date':
            self.startingValue = event.date

    def redo(self):
        if self.key == 'name':
            self.event.name = self.value
        elif self.key == 'title':
            self.event.title = self.value
        elif self.key == 'description':
            self.event.description = self.value
        elif self.key == 'notes':
            self.event.notes = self.value
        elif self.key == 'time':
            self.event.time = self.value
        elif self.key == 'date':
            self.event.date = self.value

    def undo(self):
        if self.key == 'name':
            self.event.name = self.startingValue
        elif self.key == 'title':
            self.event.title = self.startingValue
        elif self.key == 'description':
            self.event.description = self.startingValue
        elif self.key == 'notes':
            self.event.notes = self.startingValue
        elif self.key == 'time':
            self.event.time = self.startingValue
        elif self.key == 'date':
            self.event.date = self.startingValue


text:
`Home <index.html>`_ SaltStack-Formulas Project Introduction

========================================
Quick Deploy on AWS with CloudFormations
========================================

.. contents::
    :backlinks: none
    :local:

AWS Client Setup
================

If you already have pip and a supported version of Python, you can install the
AWS CLI with the following command:

.. code-block:: bash

   $ pip install awscli --upgrade --user

You can then verify that the AWS CLI installed correctly by running aws --version.

.. code-block:: bash

   $ aws --version

Connecting to Amazon Cloud
==========================

Get the Access Keys
-------------------

Access keys consist of an access key ID and secret access key, which are used
to sign programmatic requests that you make to AWS. If you don't have access
keys, you can create them from the AWS Management Console. We recommend that
you use IAM access keys instead of AWS account root user access keys. IAM lets
you securely control access to AWS services and resources in your AWS account.

For general use, the aws configure command is the fastest way to set up your
AWS CLI installation.

.. code-block:: bash

   $ aws configure
   AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
   AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   Default region name [None]: us-west-2
   Default output format [None]: json

Launching the CFN Stack
=======================

After successful login you can test the credentials.

.. code-block:: bash

   aws create-stack --stack-name

--------------

.. include:: navigation.txt


text:
//
//  SDLLifecycleConfigurationUpdate.h
//  SmartDeviceLink-iOS
//
//  Created by Kujtim Shala on 06.09.17.
//  Copyright © 2017 smartdevicelink. All rights reserved.
//

#import <Foundation/Foundation.h>

@class SDLTTSChunk;

NS_ASSUME_NONNULL_BEGIN

/**
 *  Configuration update options for SDLManager. This class can be used to update the lifecycle configuration in
 *  cases the language of the head unit changes or does not match the app language.
 */
@interface SDLLifecycleConfigurationUpdate : NSObject

/**
 *  The full name of the app to that the configuration should be updated to.
 */
@property (copy, nonatomic, nullable) NSString *appName;

/**
 *  An abbrevited application name that will be used on the app launching screen if the full one would be truncated.
 */
@property (copy, nonatomic, nullable) NSString *shortAppName;

/**
 *  A Text to Speech String for voice recognition of the mobile application name.
 */
@property (copy, nonatomic, nullable) NSArray<SDLTTSChunk *> *ttsName;

/**
 *  Additional voice recognition commands. May not interfere with any other app name or global commands.
 */
@property (copy, nonatomic, nullable) NSArray<NSString *> *voiceRecognitionCommandNames;

/**
 *  Initializes and returns a newly allocated lifecycle configuration update object with the specified app data.
 *  This is a convenience initializer for -init.
 *  @param appName The full name of the app to that the configuration should be updated to.
 *  @param shortAppName An abbrevited application name that will be used on the app launching screen if the full one would be truncated.
 *  @param ttsName A Text to Speech String for voice recognition of the mobile application name.
 *  @param voiceRecognitionCommandNames Additional voice recognition commands. May not interfere with any other app name or global commands.
 */
- (instancetype)initWithAppName:(nullable NSString *)appName shortAppName:(nullable NSString *)shortAppName ttsName:(nullable NSArray<SDLTTSChunk *> *)ttsName voiceRecognitionCommandNames:(nullable NSArray<NSString *> *)voiceRecognitionCommandNames;

@end

NS_ASSUME_NONNULL_END


text:
package com.alibaba.fastjson.serializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigInteger;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.util.TypeUtils;

/**
 * @author wenshao[szujobs@hotmail.com]
 */
public class BigIntegerCodec implements ObjectSerializer, ObjectDeserializer {

    public final static BigIntegerCodec instance = new BigIntegerCodec();

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;

        if (object == null) {
            out.writeNull(SerializerFeature.WriteNullNumberAsZero);
            return;
        }

        BigInteger val = (BigInteger) object;
        out.write(val.toString());
    }

    @SuppressWarnings("unchecked")
    public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
        return (T) deserialze(parser);
    }

    @SuppressWarnings("unchecked")
    public static <T> T deserialze(DefaultJSONParser parser) {
        final JSONLexer lexer = parser.lexer;
        if (lexer.token() == JSONToken.LITERAL_INT) {
            String val = lexer.numberString();
            lexer.nextToken(JSONToken.COMMA);
            return (T) new BigInteger(val);
        }

        Object value = parser.parse();
        return value == null //
            ? null //
            : (T) TypeUtils.castToBigInteger(value);
    }

    public int getFastMatchToken() {
        return JSONToken.LITERAL_INT;
    }
}


text:
'use strict';

var gulp           = require('gulp');
var mainBowerFiles = require('main-bower-files');
var sass           = require('gulp-sass');
var prefix         = require('gulp-autoprefixer');
var concat         = require('gulp-concat');
var streamqueue    = require('streamqueue');
var minifyCSS      = require('gulp-minify-css');
var filter         = require('gulp-filter');

var path           = require('../../paths.js');
var error          = require('../../error-handler.js');

gulp.task('build-css', function() {
	return streamqueue({ objectMode: true },

		// Select all bower styles.

		gulp.src(mainBowerFiles({

			paths: {
				bowerDirectory: path.to.bower.source,
				bowerrc: path.to.bower.config,
				bowerJson: path.to.bower.manifest
			}

		}), {
			base: path.to.bower.source
		})
		.pipe(filter('**/*.css')),

		// Select all source styles.

		gulp.src(path.to.sass.main)
		.pipe(sass())
		.on('error', error.handler)
		.pipe(prefix('last 2 versions', { cascade: true }))
		.on('error', error.handler))

	// Then concatenate and minify.

	.pipe(concat(path.to.main.css.file))
	.pipe(minifyCSS())
	.pipe(gulp.dest(path.to.destination));
});


text:
package com.twu.biblioteca.unit.view;

import com.twu.biblioteca.THelper;
import com.twu.biblioteca.view.MenuView;
import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
/**
 * Created by michalhuzevka on 5/03/15.
 */
public class MenuViewTest {
    @Test
    public void should_DisplayCorrectly_If_UserIsLoggedInAsCustomer() {
        MenuView view = new MenuView(THelper.sampleUser());
        assertTrue(view.output().contains("C to Check out an item"));
        assertTrue(view.output().contains("R to Return an item"));
        assertTrue(view.output().contains("U to view User details"));
        assertFalse(view.output().contains("L to Login"));
    }

    @Test
    public void should_DisplayCorrectly_If_UserIsNotLoggedin() {
        MenuView view = new MenuView(null);
        assertFalse(view.output().contains("C to Check out an item"));
        assertFalse(view.output().contains("R to Return an item"));
        assertFalse(view.output().contains("U to view User details"));
        assertTrue(view.output().contains("L to Login"));
    }

    @Test
    public void should_DisplayCorrectly_If_UserIsLoggedInAsLibrarian() {
        MenuView view = new MenuView(THelper.sampleLibrarian());
        assertTrue(view.output().contains("B to list borrowed Books"));
        assertTrue(view.output().contains("M to list borrowed Movies"));
        assertFalse(view.output().contains("U to view User details"));
        assertFalse(view.output().contains("C to Check out an item"));
        assertFalse(view.output().contains("R to Return an item"));
        assertFalse(view.output().contains("L to Login"));
    }

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diaporthe gilliesiana Speg.

### Remarks
null


text:
/**
 * 3 Syntax basics
 * http://doc.rust-lang.org/tutorial.html#syntax-basics
 *
 * @license MIT license <http://www.opensource.org/licenses/mit-license.php>
 */
fn main() {
	/*
	 * The let keyword introduces a local variable.
	 * Variables are immutable by default.
	 * To introduce a local variable that you can re-assign later, use let mut instead.
	 */
	let hi = "hi";
	let mut count = 0;

	while count < 10 {
		println!("{}, count: {}", hi, count);
		count += 1;
	}

	/*
	 * Although Rust can almost always infer the types of local variables,
	 * you can specify a variable's type by following it in the let with a colon, then the type name.
	 * Static items, on the other hand, always require a type annotation.
	 */
	static MONSTER_FACTOR: f64 = 57.8;
	let monster_size = MONSTER_FACTOR * 10.0;
	println!("{}", monster_size);
	let monster_size = 50;
	println!("{}", monster_size);

	/*
	 * 3.4 Syntax extensions
	 * http://doc.rust-lang.org/tutorial.html#syntax-extensions
	 */
	// {} will print the "default format" of a type
	println!("{} is {}", "the answer", 43);

	// // {:?} will conveniently print any type
	println!("what is this thing: {:?}", monster_size);
}


text:
<?php

namespace Ogilo\Admin\Models;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    public function articles()
    {
    	return $this->hasMany('Ogilo\Admin\Models\Article');
    }
    public function links()
    {
    	return $this->hasMany('Ogilo\Admin\Models\Link');
    }

	public function admins()
	{
		return $this->belongsToMany('Ogilo\Admin\Models\Admin');
	}

    public function isSelected($menu_id)
    {
        return ($menu_id == $this->id);
    }
}


text:
package org.apache.maven.model.building;

import org.apache.maven.model.Model;
import org.apache.maven.model.composition.DefaultDependencyManagementImporter;
import org.apache.maven.model.composition.DependencyManagementImporter;
import org.apache.maven.model.inheritance.DefaultInheritanceAssembler;
import org.apache.maven.model.inheritance.InheritanceAssembler;
import org.apache.maven.model.interpolation.ModelInterpolator;
import org.apache.maven.model.interpolation.StringVisitorModelInterpolator;
import org.apache.maven.model.io.DefaultModelReader;
import org.apache.maven.model.io.ModelReader;
import org.apache.maven.model.locator.DefaultModelLocator;
import org.apache.maven.model.locator.ModelLocator;
import org.apache.maven.model.management.DefaultDependencyManagementInjector;
import org.apache.maven.model.management.DefaultPluginManagementInjector;
import org.apache.maven.model.management.DependencyManagementInjector;
import org.apache.maven.model.management.PluginManagementInjector;
import org.apache.maven.model.normalization.DefaultModelNormalizer;
import org.apache.maven.model.normalization.ModelNormalizer;
import org.apache.maven.model.path.DefaultModelPathTranslator;
import org.apache.maven.model.path.DefaultModelUrlNormalizer;
import org.apache.maven.model.path.DefaultPathTranslator;
import org.apache.maven.model.path.DefaultUrlNormalizer;
import org.apache.maven.model.path.ModelPathTranslator;
import org.apache.maven.model.path.ModelUrlNormalizer;
import org.apache.maven.model.path.PathTranslator;
import org.apache.maven.model.path.UrlNormalizer;
import org.apache.maven.model.plugin.DefaultPluginConfigurationExpander;
import org.apache.maven.model.plugin.DefaultReportConfigurationExpander;
import org.apache.maven.model.plugin.DefaultReportingConverter;
import org.apache.maven.model.plugin.LifecycleBindingsInjector;
import org.apache.maven.model.plugin.PluginConfigurationExpander;
import org.apache.maven.model.plugin.ReportConfigurationExpander;
import org.apache.maven.model.plugin.ReportingConverter;
import org.apache.maven.model.profile.DefaultProfileInjector;
import org.apache.maven.model.profile.DefaultProfileSelector;
import org.apache.maven.model.profile.ProfileInjector;
import org.apache.maven.model.profile.ProfileSelector;
import org.apache.maven.model.profile.activation.FileProfileActivator;
import org.apache.maven.model.profile.activation.JdkVersionProfileActivator;
import org.apache.maven.model.profile.activation.OperatingSystemProfileActivator;
import org.apache.maven.model.profile.activation.ProfileActivator;
import org.apache.maven.model.profile.activation.PropertyProfileActivator;
import org.apache.maven.model.superpom.DefaultSuperPomProvider;
import org.apache.maven.model.superpom.SuperPomProvider;
import org.apache.maven.model.validation.DefaultModelValidator;
import org.apache.maven.model.validation.ModelValidator;

/**
 * A factory to create model builder instances when no dependency injection is available. Note: This class is
 * only meant as a utility for developers that want to employ the model builder outside of the Maven build system, Maven
 * plugins should always acquire model builder instances via dependency injection. Developers might want to subclass
 * this factory to provide custom implementations for some of the components used by the model builder.
 *
 * @author Benjamin Bentmann
 */
public class DefaultModelBuilderFactory
{

    protected ModelProcessor newModelProcessor()
    {
        DefaultModelProcessor processor = new DefaultModelProcessor();
        processor.setModelLocator( newModelLocator() );
        processor.setModelReader( newModelReader() );
        return processor;
    }

    protected ModelLocator newModelLocator()
    {
        return new DefaultModelLocator();
    }

    protected ModelReader newModelReader()
    {
        DefaultModelReader reader = new DefaultModelReader();
        reader.setTransformer( newModelSourceTransformer() );
        return reader;
    }

    protected ProfileSelector newProfileSelector()
    {
        DefaultProfileSelector profileSelector = new DefaultProfileSelector();

        for ( ProfileActivator activator : newProfileActivators() )
        {
            profileSelector.addProfileActivator( activator );
        }

        return profileSelector;
    }

    protected ProfileActivator[] newProfileActivators()
    {
        return new ProfileActivator[] { new JdkVersionProfileActivator(), new OperatingSystemProfileActivator(),
            new PropertyProfileActivator(), new FileProfileActivator().setPathTranslator( newPathTranslator() ) };
    }

    protected UrlNormalizer newUrlNormalizer()
    {
        return new DefaultUrlNormalizer();
    }

    protected PathTranslator newPathTranslator()
    {
        return new DefaultPathTranslator();
    }

    protected ModelInterpolator newModelInterpolator()
    {
        UrlNormalizer normalizer = newUrlNormalizer();
        PathTranslator pathTranslator = newPathTranslator();
        return new StringVisitorModelInterpolator().setPathTranslator( pathTranslator ).setUrlNormalizer( normalizer );
    }

    protected ModelValidator newModelValidator()
    {
        return new DefaultModelValidator();
    }

    protected ModelNormalizer newModelNormalizer()
    {
        return new DefaultModelNormalizer();
    }

    protected ModelPathTranslator newModelPathTranslator()
    {
        return new DefaultModelPathTranslator().setPathTranslator( newPathTranslator() );
    }

    protected ModelUrlNormalizer newModelUrlNormalizer()
    {
        return new DefaultModelUrlNormalizer().setUrlNormalizer( newUrlNormalizer() );
    }

    protected InheritanceAssembler newInheritanceAssembler()
    {
        return new DefaultInheritanceAssembler();
    }

    protected ProfileInjector newProfileInjector()
    {
        return new DefaultProfileInjector();
    }

    protected SuperPomProvider newSuperPomProvider()
    {
        return new DefaultSuperPomProvider().setModelProcessor( newModelProcessor() );
    }

    protected DependencyManagementImporter newDependencyManagementImporter()
    {
        return new DefaultDependencyManagementImporter();
    }

    protected DependencyManagementInjector newDependencyManagementInjector()
    {
        return new DefaultDependencyManagementInjector();
    }

    protected LifecycleBindingsInjector newLifecycleBindingsInjector()
    {
        return new StubLifecycleBindingsInjector();
    }

    protected PluginManagementInjector newPluginManagementInjector()
    {
        return new DefaultPluginManagementInjector();
    }

    protected PluginConfigurationExpander newPluginConfigurationExpander()
    {
        return new DefaultPluginConfigurationExpander();
    }

    protected ReportConfigurationExpander newReportConfigurationExpander()
    {
        return new DefaultReportConfigurationExpander();
    }

    protected ReportingConverter newReportingConverter()
    {
        return new DefaultReportingConverter();
    }

    private ModelSourceTransformer newModelSourceTransformer()
    {
        return new DefaultModelSourceTransformer();
    }

    /**
     * Creates a new model builder instance.
     *
     * @return The new model builder instance, never {@code null}.
     */
    public DefaultModelBuilder newInstance()
    {
        DefaultModelBuilder modelBuilder = new DefaultModelBuilder();

        modelBuilder.setModelProcessor( newModelProcessor() );
        modelBuilder.setModelValidator( newModelValidator() );
        modelBuilder.setModelNormalizer( newModelNormalizer() );
        modelBuilder.setModelPathTranslator( newModelPathTranslator() );
        modelBuilder.setModelUrlNormalizer( newModelUrlNormalizer() );
        modelBuilder.setModelInterpolator( newModelInterpolator() );
        modelBuilder.setInheritanceAssembler( newInheritanceAssembler() );
        modelBuilder.setProfileInjector( newProfileInjector() );
        modelBuilder.setProfileSelector( newProfileSelector() );
        modelBuilder.setSuperPomProvider( newSuperPomProvider() );
        modelBuilder.setDependencyManagementImporter( newDependencyManagementImporter() );
        modelBuilder.setDependencyManagementInjector( newDependencyManagementInjector() );
        modelBuilder.setLifecycleBindingsInjector( newLifecycleBindingsInjector() );
        modelBuilder.setPluginManagementInjector( newPluginManagementInjector() );
        modelBuilder.setPluginConfigurationExpander( newPluginConfigurationExpander() );
        modelBuilder.setReportConfigurationExpander( newReportConfigurationExpander() );
        modelBuilder.setReportingConverter( newReportingConverter() );

        return modelBuilder;
    }

    private static class StubLifecycleBindingsInjector
        implements LifecycleBindingsInjector
    {

        @Override
        public void injectLifecycleBindings( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
        {
        }

    }

}


text:
package com.advancedpwr.record.methods;

import com.advancedpwr.record.AccessPath;

public class ArrayBuilderFactory implements MethodWriterFactory
{
	/* (non-Javadoc)
	 * @see com.advancedpwr.record.methods.Factory#accept(java.lang.Class)
	 */
	public boolean accept( Class inClass )
	{
		return inClass.isArray();
	}

	/* (non-Javadoc)
	 * @see com.advancedpwr.record.methods.Factory#createMethodBuilder(com.advancedpwr.record.AccessPath)
	 */
	public BuildMethodWriter createMethodBuilder( AccessPath inPath )
	{
		return new ArrayBuilder();
	}
}


text:
/*--
 ** RespondTo Method. (c) 2016 Jose Pablo Granados
 ** Released under the MIT license
--*/

var respond = (function(options){

    var breakpoints = { mobile: 767, tablet: 1023, desktop: 1279 },
        breakpoint,
        query,
        wrongParam = false,
        errorMsg = 'Invalid parameter, check respondTo docs';

    function to(options){

        if(typeof(options) === 'string'){

            breakpoint = breakpoints[options];

            switch(options){
                case 'mobile':
                    query = '(max-width: '+ breakpoint +'px)';
                break;
                case 'tablet':
                    query = '(min-width: '+ breakpoints['mobile'] +'px) and (max-width: '+ breakpoints[options] +'px)';
                break;
                case 'desktop':
                    query = '(min-width: '+ breakpoints['tablet'] +'px)';
                break;
                default:
                    wrongParam = true;
                break;
            }

        }else if(typeof(options) === 'number' && options % 1 === 0){
            query = '(min-width: '+ options +'px)';
        }else{
            wrongParam = true;
        }

        if(window.matchMedia !== undefined && !wrongParam){
            return window.matchMedia(query).matches;
        }else{
            console.warn(errorMsg);
            return false;
        }
    }

    return {
        to: to
    }

})();


text:
package org.apache.cloudstack.api.command.admin.domain;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.DomainResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.region.RegionService;

import com.cloud.domain.Domain;
import com.cloud.event.EventTypes;
import com.cloud.user.Account;

@APICommand(name = "deleteDomain", description = "Deletes a specified domain", responseObject = SuccessResponse.class,
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class DeleteDomainCmd extends BaseAsyncCmd {
    public static final Logger s_logger = Logger.getLogger(DeleteDomainCmd.class.getName());
    private static final String s_name = "deletedomainresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DomainResponse.class, required = true, description = "ID of domain to delete")
    private Long id;

    @Parameter(name = ApiConstants.CLEANUP,
               type = CommandType.BOOLEAN,
               description = "true if all domain resources (child domains, accounts) have to be cleaned up, false otherwise")
    private Boolean cleanup;

    @Inject
    RegionService _regionService;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Long getId() {
        return id;
    }

    public Boolean getCleanup() {
        return cleanup;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        Domain domain = _entityMgr.findById(Domain.class, getId());
        if (domain != null) {
            return domain.getAccountId();
        }

        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_DOMAIN_DELETE;
    }

    @Override
    public String getEventDescription() {
        return "deleting domain: " + getId();
    }

    @Override
    public void execute() {
        CallContext.current().setEventDetails("Domain Id: " + getId());
        boolean result = _regionService.deleteDomain(this);
        if (result) {
            SuccessResponse response = new SuccessResponse(getCommandName());
            this.setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete domain");
        }
    }
}


text:
Making Birthdays and Holidays Simple and Affordable

<form id="registrationForm" class="form-signin" onsubmit="register(); return false;">
	Email address
	<input type="email" id="registrationInputEmail" name="email" class="form-control" placeholder="Email address" required autofocus>
	Password
	<input type="password" id="registrationInputPassword" name="password" class="form-control" placeholder="Password" required>
	<input type="password" id="registrationInputPassword" name="password2" class="form-control" placeholder="Confirm Password" required>
	<button id="register-button" class="btn btn-lg btn-success btn-block" type="submit">Register</button>
	<button id="login-redirect-button" class="btn btn-lg btn-success btn-block" onclick="showLogin()">Log in</button>
</form>


text:
using System;

using ClosedXML.Excel;

namespace ClosedXML_Examples.Styles
{
    public class StyleBorder : IXLExample
    {
        public void Create(String filePath)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Style Border");

            var co = 2;
            var ro = 1;

            ws.Cell(++ro, co).Value = "BottomBorder = Thick; BottomBorderColor = Red";
            ws.Cell(ro, co).Style.Border.BottomBorder = XLBorderStyleValues.Thick;
            ws.Cell(ro, co).Style.Border.BottomBorderColor = XLColor.Red;

            ws.Cell(++ro, co).Value = "LeftBorder = Thick; LeftBorderColor = Blue";
            ws.Cell(ro, co).Style.Border.LeftBorder = XLBorderStyleValues.Thick;
            ws.Cell(ro, co).Style.Border.LeftBorderColor = XLColor.Blue;

            ws.Cell(++ro, co).Value = "TopBorder = Thick; TopBorderColor = Yellow";
            ws.Cell(ro, co).Style.Border.TopBorder = XLBorderStyleValues.Thick;
            ws.Cell(ro, co).Style.Border.TopBorderColor = XLColor.Yellow;

            ws.Cell(++ro, co).Value = "RightBorder = Thick; RightBorderColor = Black";
            ws.Cell(ro, co).Style.Border.RightBorder = XLBorderStyleValues.Thick;
            ws.Cell(ro, co).Style.Border.RightBorderColor = XLColor.Black;

            ws.Cell(++ro, co).Value = "DiagonalBorder = Thin; DiagonalBorderColor = Red; DiagonalUp = true";
            ws.Cell(ro, co).Style.Border.DiagonalBorder = XLBorderStyleValues.Thin;
            ws.Cell(ro, co).Style.Border.DiagonalBorderColor = XLColor.Red;
            ws.Cell(ro, co).Style.Border.DiagonalUp = true;

            ws.Cell(++ro, co).Value = "DiagonalBorder = Thin; DiagonalBorderColor = Red; DiagonalDown = true";
            ws.Cell(ro, co).Style.Border.DiagonalBorder = XLBorderStyleValues.Thin;
            ws.Cell(ro, co).Style.Border.DiagonalBorderColor = XLColor.Red;
            ws.Cell(ro, co).Style.Border.DiagonalDown = true;

            ws.Cell(++ro, co).Value = "DiagonalBorder = Thin; DiagonalBorderColor = Red; DiagonalUp = true; DiagonalDown = true";
            ws.Cell(ro, co).Style.Border.DiagonalBorder = XLBorderStyleValues.Thin;
            ws.Cell(ro, co).Style.Border.DiagonalBorderColor = XLColor.Red;
            ws.Cell(ro, co).Style.Border.DiagonalUp = true;
            ws.Cell(ro, co).Style.Border.DiagonalDown = true;

            workbook.SaveAs(filePath);
        }
    }
}


text:
<?php

namespace Knplabs\MenuBundle;

interface ProviderInterface
{
    function getMenu($name);
}


text:
# Buttons

The MDC Button component is a spec-aligned button component adhering to the
[Material Design button requirements](https://material.io/guidelines/components/buttons.html).
It works without JavaScript with basic functionality for all states.
If you initiate the JavaScript object for a button, then it will be enhanced with ripple effects. (Not yet implemented)

## Design & API Documentation

    Material Design guidelines: Buttons

    Demo

## Installation

```
npm install --save @material/button
```

## Usage

### Flat

```html
<button class="mdc-button">
  Flat button
</button>
```

### Colored

```html
<button class="mdc-button mdc-button--accent">
  Colored button
</button>
```

### Raised

```html
<button class="mdc-button mdc-button--raised">
  Raised button
</button>
```

### Disabled

```html
<button class="mdc-button mdc-button--raised" disabled>
  Raised disabled button
</button>
```

### Adding ripples to buttons

To add the ink ripple effect to a button, attach a [ripple](../mdc-ripple) instance to the
button element.

```js
mdc.ripple.MDCRipple.attachTo(document.querySelector('.mdc-button'));
```

You can also do this declaratively when using the [material-components-web](../material-components-web) package.

```html
<button class="mdc-button" data-mdc-auto-init="MDCRipple">
  Flat button
</button>
```

Buttons are fully aware of ripple styles, so no DOM or CSS changes are required to use them.

## Classes

### Block

The block class is `mdc-button`. This defines the top-level button element.

### Element

The button component has no inner elements.

### Modifier

The provided modifiers are:

| Class                 | Description                                             |
| --------------------- | ------------------------------------------------------- |
| `mdc-button--dense`   | Compresses the button text to make it slightly smaller. |
| `mdc-button--raised`  | Elevates the button and creates a colored background.   |
| `mdc-button--compact` | Reduces the amount of horizontal padding in the button. |
| `mdc-button--primary` | Colors the button with the primary color.               |
| `mdc-button--accent`  | Colors the button with the accent color.                |


text:
/**
 * Created by Casper on 05/03/2016.
 */
import {Pipe} from "angular2/core";
import {PipeTransform} from "angular2/core";
import {Rank} from "../components/Rank";

@Pipe({
    name: 'tierDisplay'
})

export class TierDisplayPipe implements PipeTransform {

    TIERS = [
        'Unranked',
        'Prospect I',
        'Prospect II',
        'Prospect III',
        'Prospect Elite',
        'Challenger I',
        'Challenger II',
        'Challenger III',
        'Challenger Elite',
        'Rising Star',
        'Shooting Star',
        'All-Star',
        'Superstar',
        'Champion',
        'Super Champion',
        'Grand Champion'
    ]

    transform(rank: Rank) {
        return this.TIERS[rank.tier];
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `IterMut` struct in crate `core`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, IterMut">

    <title>core::result::IterMut - Rust</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

core::<wbr>result

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Struct core::<wbr>result::<wbr>IterMut<wbr>Stable
            [-] [+]
        [src]

pub struct IterMut<'a, T: 'a> {
    // some fields omitted
}

An iterator over a mutable reference to the Ok variant of a Result.

Trait Implementations

impl<'a, T> Iterator for IterMut<'a, T>

type Item = &'a mut T

fn next(&mut self) -> Option<&'a mut T>

fn size_hint(&self) -> (usize, Option<usize>)

impl<'a, T> DoubleEndedIterator for IterMut<'a, T>

fn next_back(&mut self) -> Option<&'a mut T>

impl<'a, T> ExactSizeIterator for IterMut<'a, T>

fn len(&self) -> usize

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.exec.local;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.GoogleLogger;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ForbiddenActionInputException;
import com.google.devtools.build.lib.actions.ResourceManager;
import com.google.devtools.build.lib.actions.ResourceManager.ResourceHandle;
import com.google.devtools.build.lib.actions.ResourceManager.ResourcePriority;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnMetrics;
import com.google.devtools.build.lib.actions.SpawnResult;
import com.google.devtools.build.lib.actions.SpawnResult.Status;
import com.google.devtools.build.lib.actions.Spawns;
import com.google.devtools.build.lib.actions.cache.VirtualActionInput;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.exec.BinTools;
import com.google.devtools.build.lib.exec.RunfilesTreeUpdater;
import com.google.devtools.build.lib.exec.SpawnExecutingEvent;
import com.google.devtools.build.lib.exec.SpawnRunner;
import com.google.devtools.build.lib.exec.SpawnSchedulingEvent;
import com.google.devtools.build.lib.profiler.Profiler;
import com.google.devtools.build.lib.profiler.ProfilerTask;
import com.google.devtools.build.lib.profiler.SilentCloseable;
import com.google.devtools.build.lib.runtime.ProcessWrapper;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.Spawn.Code;
import com.google.devtools.build.lib.shell.ExecutionStatistics;
import com.google.devtools.build.lib.shell.Subprocess;
import com.google.devtools.build.lib.shell.SubprocessBuilder;
import com.google.devtools.build.lib.shell.TerminationStatus;
import com.google.devtools.build.lib.util.NetUtil;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.io.FileOutErr;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.XattrProvider;
import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.annotations.FormatString;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.annotation.Nullable;

/**
 * A class that runs local commands. Each request follows state transitions from "parsing" to
 * completion.
 */
@ThreadSafe
public class LocalSpawnRunner implements SpawnRunner {
  private static final Joiner SPACE_JOINER = Joiner.on(' ');
  private static final String UNHANDLED_EXCEPTION_MSG = "Unhandled exception running a local spawn";
  private static final int LOCAL_EXEC_ERROR = -1;

  private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();

  private final Path execRoot;
  private final ResourceManager resourceManager;

  private final String hostName;

  private final LocalExecutionOptions localExecutionOptions;
  private final XattrProvider xattrProvider;

  @Nullable private final ProcessWrapper processWrapper;

  private final LocalEnvProvider localEnvProvider;
  private final BinTools binTools;

  private final RunfilesTreeUpdater runfilesTreeUpdater;

  public LocalSpawnRunner(
      Path execRoot,
      LocalExecutionOptions localExecutionOptions,
      ResourceManager resourceManager,
      LocalEnvProvider localEnvProvider,
      BinTools binTools,
      ProcessWrapper processWrapper,
      XattrProvider xattrProvider,
      RunfilesTreeUpdater runfilesTreeUpdater) {
    this.execRoot = execRoot;
    this.processWrapper = processWrapper;
    this.localExecutionOptions = Preconditions.checkNotNull(localExecutionOptions);
    this.xattrProvider = xattrProvider;
    this.hostName = NetUtil.getCachedShortHostName();
    this.resourceManager = resourceManager;
    this.localEnvProvider = localEnvProvider;
    this.binTools = binTools;
    this.runfilesTreeUpdater = runfilesTreeUpdater;
  }

  @Override
  public String getName() {
    return "local";
  }

  @Override
  public SpawnResult exec(Spawn spawn, SpawnExecutionContext context)
      throws IOException, InterruptedException, ExecException, ForbiddenActionInputException {

    SpawnMetrics.Builder spawnMetrics = SpawnMetrics.Builder.forLocalExec();
    Stopwatch totalTimeStopwatch = Stopwatch.createStarted();
    Stopwatch setupTimeStopwatch = Stopwatch.createStarted();
    runfilesTreeUpdater.updateRunfilesDirectory(
        execRoot,
        spawn.getRunfilesSupplier(),
        binTools,
        spawn.getEnvironment(),
        context.getFileOutErr(),
        xattrProvider);
    spawnMetrics.addSetupTime(setupTimeStopwatch.elapsed());

    try (SilentCloseable c =
        Profiler.instance()
            .profile(ProfilerTask.LOCAL_EXECUTION, spawn.getResourceOwner().getMnemonic())) {
      ActionExecutionMetadata owner = spawn.getResourceOwner();
      context.report(SpawnSchedulingEvent.create(getName()));

      Stopwatch queueStopwatch = Stopwatch.createStarted();
      try (ResourceHandle handle =
          resourceManager.acquireResources(
              owner,
              spawn.getLocalResources(),
              context.speculating()
                  ? ResourcePriority.DYNAMIC_STANDALONE
                  : ResourcePriority.LOCAL)) {
        spawnMetrics.setQueueTime(queueStopwatch.elapsed());
        context.report(SpawnExecutingEvent.create(getName()));
        if (!localExecutionOptions.localLockfreeOutput) {
          // Without local-lockfree, we grab the lock before running the action, so we can't
          // check for failures while taking the lock.
          context.lockOutputFiles(0, "", context.getFileOutErr());
        }
        return new SubprocessHandler(spawn, context, spawnMetrics, totalTimeStopwatch).run();
      }
    }
  }

  @Override
  public boolean canExec(Spawn spawn) {
    return true;
  }

  @Override
  public boolean handlesCaching() {
    return false;
  }

  protected Path createActionTemp(Path execRoot) throws IOException {
    return execRoot.getRelative(
        java.nio.file.Files.createTempDirectory(
                java.nio.file.Paths.get(execRoot.getPathString()), "local-spawn-runner.")
            .getFileName()
            .toString());
  }

  private final class SubprocessHandler {
    private final Spawn spawn;
    private final SpawnExecutionContext context;
    private final SpawnMetrics.Builder spawnMetrics;
    private final Stopwatch totalTimeStopwatch;

    private final long creationTime = System.currentTimeMillis();
    private long stateStartTime = creationTime;
    private State currentState = State.INITIALIZING;
    private final Map<State, Long> stateTimes = new EnumMap<>(State.class);

    /**
     * If true, the local subprocess has already started, which means we need to clean up the output
     * tree once we get interrupted.
     */
    private boolean needCleanup = false;

    private final int id;

    public SubprocessHandler(
        Spawn spawn,
        SpawnExecutionContext context,
        SpawnMetrics.Builder spawnMetrics,
        Stopwatch totalTimeStopwatch) {
      Preconditions.checkArgument(!spawn.getArguments().isEmpty());
      this.spawn = spawn;
      this.totalTimeStopwatch = totalTimeStopwatch;
      this.context = context;
      this.spawnMetrics = spawnMetrics;
      this.id = context.getId();
      setState(State.PARSING);
    }

    public SpawnResult run()
        throws InterruptedException, IOException, ForbiddenActionInputException {
      if (localExecutionOptions.localRetriesOnCrash == 0) {
        return runOnce();
      } else {
        int attempts = 0;
        while (true) {
          // Assume that any exceptions from runOnce() come from the Java side of things, not the
          // subprocess, so let them bubble up on first occurrence. In particular, we need this to
          // be true for InterruptedException to ensure that the dynamic scheduler can stop us
          // quickly.
          Stopwatch rertyStopwatch = Stopwatch.createStarted();
          SpawnResult result = runOnce();
          if (attempts == localExecutionOptions.localRetriesOnCrash
              || !TerminationStatus.crashed(result.exitCode())) {
            return result;
          }
          stepLog(
              SEVERE,
              "Retrying crashed subprocess due to exit code %s (attempt %s)",
              result.exitCode(),
              attempts);
          Thread.sleep(attempts * 1000);
          spawnMetrics.addRetryTime(result.exitCode(), rertyStopwatch.elapsed());
          attempts++;
        }
      }
    }

    private SpawnResult runOnce()
        throws InterruptedException, IOException, ForbiddenActionInputException {
      try {
        return start();
      } catch (InterruptedException | InterruptedIOException e) {
        maybeCleanupOnInterrupt();
        // Logging the exception causes a lot of noise in builds using the dynamic scheduler, and
        // the information is not very interesting, so avoid that.
        stepLog(SEVERE, "Interrupted (and cleanup finished)");
        throw e;
      } catch (Error e) {
        stepLog(SEVERE, e, UNHANDLED_EXCEPTION_MSG);
        throw e;
      } catch (ForbiddenActionInputException e) {
        stepLog(WARNING, e, "Bad input file");
        throw e;
      } catch (IOException e) {
        stepLog(SEVERE, e, "Local I/O error");
        throw e;
      } catch (RuntimeException e) {
        stepLog(SEVERE, e, UNHANDLED_EXCEPTION_MSG);
        throw new RuntimeException(UNHANDLED_EXCEPTION_MSG, e);
      }
    }

    @FormatMethod
    private void stepLog(Level level, @FormatString String fmt, Object... args) {
      stepLog(level, /*cause=*/ null, fmt, args);
    }

    @FormatMethod
    private void stepLog(
        Level level, @Nullable Throwable cause, @FormatString String fmt, Object... args) {
      String msg = String.format(fmt, args);
      String toLog = String.format("%s (#%d %s)", msg, id, desc());
      logger.at(level).withCause(cause).log("%s", toLog);
    }

    private String desc() {
      String progressMessage = spawn.getResourceOwner().getProgressMessage();
      return progressMessage != null
          ? progressMessage
          : "ActionType=" + spawn.getResourceOwner().getMnemonic();
    }

    private void setState(State newState) {
      long now = System.currentTimeMillis();
      long stepDelta = now - stateStartTime;
      stateStartTime = now;

      Long stateTimeBoxed = stateTimes.get(currentState);
      long stateTime = (stateTimeBoxed == null) ? 0 : stateTimeBoxed;
      stateTimes.put(currentState, stateTime + stepDelta);

      currentState = newState;
    }

    private String debugCmdString() {
      String cmd = SPACE_JOINER.join(spawn.getArguments());
      if (cmd.length() > 500) {
        // Shrink argstr by replacing middle of string with "...".
        return cmd.substring(0, 250) + "..." + cmd.substring(cmd.length() - 250);
      }
      return cmd;
    }

    /** Parse the request and run it locally. */
    private SpawnResult start()
        throws InterruptedException, IOException, ForbiddenActionInputException {
      logger.atInfo().log("starting local subprocess #%d, argv: %s", id, debugCmdString());

      SpawnResult.Builder spawnResultBuilder =
          new SpawnResult.Builder().setRunnerName(getName()).setExecutorHostname(hostName);

      FileOutErr outErr = context.getFileOutErr();
      String actionType = spawn.getResourceOwner().getMnemonic();
      if (localExecutionOptions.allowedLocalAction != null
          && !localExecutionOptions
              .allowedLocalAction
              .regexPattern()
              .matcher(actionType)
              .matches()) {
        setState(State.PERMANENT_ERROR);
        outErr
            .getErrorStream()
            .write(
                ("Action type "
                        + actionType
                        + " is not allowed to run locally due to regex filter: "
                        + localExecutionOptions.allowedLocalAction.regexPattern()
                        + "\n")
                    .getBytes(UTF_8));
        spawnMetrics.setTotalTime(totalTimeStopwatch.elapsed());
        return spawnResultBuilder
            .setStatus(Status.EXECUTION_DENIED)
            .setExitCode(LOCAL_EXEC_ERROR)
            .setFailureDetail(
                makeFailureDetail(LOCAL_EXEC_ERROR, Status.EXECUTION_DENIED, actionType))
            .setSpawnMetrics(spawnMetrics.build())
            .build();
      }

      if (Spawns.shouldPrefetchInputsForLocalExecution(spawn)) {
        stepLog(INFO, "prefetching inputs for local execution");
        setState(State.PREFETCHING_LOCAL_INPUTS);
        context.prefetchInputsAndWait();
      }

      spawnMetrics.setInputFiles(spawn.getInputFiles().memoizedFlattenAndGetSize());
      Stopwatch setupTimeStopwatch = Stopwatch.createStarted();
      for (ActionInput input : spawn.getInputFiles().toList()) {
        if (input instanceof VirtualActionInput) {
          VirtualActionInput virtualActionInput = (VirtualActionInput) input;
          Path outputPath = execRoot.getRelative(virtualActionInput.getExecPath());
          if (outputPath.exists()) {
            outputPath.delete();
          }
          outputPath.getParentDirectory().createDirectoryAndParents();
          try (OutputStream outputStream = outputPath.getOutputStream()) {
            virtualActionInput.writeTo(outputStream);
          }
          // Some of the virtual inputs are tools run as part of the execution, hence we need to set
          // executable flag.
          outputPath.setExecutable(true);
        }
      }

      stepLog(INFO, "running locally");
      setState(State.LOCAL_ACTION_RUNNING);

      Path tmpDir = createActionTemp(execRoot);
      Path statisticsPath = null;
      try {
        Path commandTmpDir = tmpDir.getRelative("work");
        commandTmpDir.createDirectory();
        ImmutableMap<String, String> environment =
            localEnvProvider.rewriteLocalEnv(
                spawn.getEnvironment(), binTools, commandTmpDir.getPathString());

        SubprocessBuilder subprocessBuilder = new SubprocessBuilder();
        subprocessBuilder.setWorkingDirectory(execRoot.getPathFile());
        subprocessBuilder.setStdout(outErr.getOutputPath().getPathFile());
        subprocessBuilder.setStderr(outErr.getErrorPath().getPathFile());
        subprocessBuilder.setEnv(environment);
        ImmutableList<String> args;
        if (processWrapper != null) {
          // If the process wrapper is enabled, we use its timeout feature, which first interrupts
          // the subprocess and only kills it after a grace period so that the subprocess can output
          // a stack trace, test log or similar, which is incredibly helpful for debugging.
          ProcessWrapper.CommandLineBuilder commandLineBuilder =
              processWrapper
                  .commandLineBuilder(spawn.getArguments())
                  .addExecutionInfo(spawn.getExecutionInfo())
                  .setTimeout(context.getTimeout());
          if (localExecutionOptions.collectLocalExecutionStatistics) {
            statisticsPath = tmpDir.getRelative("stats.out");
            commandLineBuilder.setStatisticsPath(statisticsPath);
          }
          args = ImmutableList.copyOf(commandLineBuilder.build());
        } else {
          subprocessBuilder.setTimeoutMillis(context.getTimeout().toMillis());
          args = spawn.getArguments();
        }
        // SubprocessBuilder does not accept relative paths for the first argument, even though
        // Command does. We sometimes get relative paths here, so we need to handle it.
        File argv0 = new File(args.get(0));
        if (!argv0.isAbsolute() && argv0.getParent() != null) {
          List<String> newArgs = new ArrayList<>(args);
          newArgs.set(0, new File(execRoot.getPathFile(), newArgs.get(0)).getAbsolutePath());
          args = ImmutableList.copyOf(newArgs);
        }
        subprocessBuilder.setArgv(args);
        spawnMetrics.addSetupTime(setupTimeStopwatch.elapsed());

        Stopwatch executionStopwatch = Stopwatch.createStarted();
        TerminationStatus terminationStatus;
        try (SilentCloseable c =
            Profiler.instance()
                .profile(ProfilerTask.PROCESS_TIME, spawn.getResourceOwner().getMnemonic())) {
          needCleanup = true;
          Subprocess subprocess = subprocessBuilder.start();
          try {
            subprocess.getOutputStream().close();
            subprocess.waitFor();
            terminationStatus =
                new TerminationStatus(subprocess.exitValue(), subprocess.timedout());
          } catch (InterruptedException | IOException e) {
            subprocess.destroyAndWait();
            throw e;
          }
          if (Thread.interrupted()) {
            stepLog(SEVERE, "Interrupted but didn't throw; status %s", terminationStatus);
            throw new InterruptedException();
          }
        } catch (InterruptedIOException e) {
          throw new InterruptedException(e.getMessage());
        } catch (IOException e) {
          String msg = e.getMessage() == null ? e.getClass().getName() : e.getMessage();
          setState(State.PERMANENT_ERROR);
          outErr
              .getErrorStream()
              .write(
                  ("Action failed to execute: java.io.IOException: " + msg + "\n").getBytes(UTF_8));
          outErr.getErrorStream().flush();
          spawnMetrics.setTotalTime(totalTimeStopwatch.elapsed());
          return spawnResultBuilder
              .setStatus(Status.EXECUTION_FAILED)
              .setExitCode(LOCAL_EXEC_ERROR)
              .setFailureDetail(
                  makeFailureDetail(LOCAL_EXEC_ERROR, Status.EXECUTION_FAILED, actionType))
              .setSpawnMetrics(spawnMetrics.build())
              .build();
        }
        setState(State.SUCCESS);
        // TODO(b/62588075): Calculate wall time inside commands instead?
        Duration wallTime = executionStopwatch.elapsed();
        spawnMetrics.setExecutionWallTime(wallTime);

        boolean wasTimeout =
            terminationStatus.timedOut()
                || (processWrapper != null && wasTimeout(context.getTimeout(), wallTime));
        int exitCode =
            wasTimeout ? SpawnResult.POSIX_TIMEOUT_EXIT_CODE : terminationStatus.getRawExitCode();
        Status status =
            wasTimeout ? Status.TIMEOUT : (exitCode == 0 ? Status.SUCCESS : Status.NON_ZERO_EXIT);
        if (exitCode != 0 && localExecutionOptions.localLockfreeOutput && context.speculating()) {
          // We already "have" the lock, but this also checks if we should ignore failures.
          context.lockOutputFiles(exitCode, "", outErr);
        }
        spawnResultBuilder.setStatus(status).setExitCode(exitCode).setWallTime(wallTime);
        if (status != Status.SUCCESS) {
          spawnResultBuilder.setFailureDetail(makeFailureDetail(exitCode, status, actionType));
        }
        if (statisticsPath != null) {
          ExecutionStatistics.getResourceUsage(statisticsPath)
              .ifPresent(
                  resourceUsage -> {
                    spawnResultBuilder.setUserTime(resourceUsage.getUserExecutionTime());
                    spawnResultBuilder.setSystemTime(resourceUsage.getSystemExecutionTime());
                    spawnResultBuilder.setNumBlockOutputOperations(
                        resourceUsage.getBlockOutputOperations());
                    spawnResultBuilder.setNumBlockInputOperations(
                        resourceUsage.getBlockInputOperations());
                    spawnResultBuilder.setNumInvoluntaryContextSwitches(
                        resourceUsage.getInvoluntaryContextSwitches());
                    // The memory usage of the largest child process. For Darwin maxrss returns size
                    // in bytes.
                    if (OS.getCurrent() == OS.DARWIN) {
                      spawnResultBuilder.setMemoryInKb(
                          resourceUsage.getMaximumResidentSetSize() / 1000);
                    } else {
                      spawnResultBuilder.setMemoryInKb(resourceUsage.getMaximumResidentSetSize());
                    }
                  });
        }
        spawnMetrics.setTotalTime(totalTimeStopwatch.elapsed());
        spawnResultBuilder.setSpawnMetrics(spawnMetrics.build());
        return spawnResultBuilder.build();
      } finally {
        // Delete the temp directory tree, so the next action that this thread executes will get a
        // fresh, empty temp directory.
        // File deletion tends to be slow on Windows, so deleting this tree may take several
        // seconds. Delete it after having measured the wallTime.
        try {
          tmpDir.deleteTree();
        } catch (IOException ignored) {
          // We can't handle this exception in any meaningful way, nor should we, but let's log it.
          stepLog(
              WARNING,
              "failed to delete temp directory '%s'; this might indicate that the action "
                  + "created subprocesses that didn't terminate and hold files open in that "
                  + "directory",
              tmpDir);
        }
      }
    }

    private boolean wasTimeout(Duration timeout, Duration wallTime) {
      return !timeout.isZero() && wallTime.compareTo(timeout) > 0;
    }

    /**
     * Clean up any known side-effects that the running spawn may have had on the output tree.
     *
     * <p>This is supposed to leave the output tree as it was right after {@link
     * com.google.devtools.build.lib.skyframe.SkyframeActionExecutor} created the output directories
     * for the spawn, which means that any outputs have to be deleted but any top-level directory
     * for tree artifacts has to be kept behind (and empty).
     */
    private void maybeCleanupOnInterrupt() {
      if (!localExecutionOptions.localLockfreeOutput) {
        // If we don't allow lockfree executions of local subprocesses, there is no need to clean up
        // anything: we would have already locked the output tree upfront, so we "own" it.
        return;
      }
      if (!needCleanup) {
        // If the subprocess has not yet started, there is no need to worry about checking on-disk
        // state.
        return;
      }

      for (ActionInput output : spawn.getOutputFiles()) {
        Path path = context.getPathResolver().toPath(output);
        try {
          if (path.exists()) {
            stepLog(INFO, "Clearing output %s after interrupt", path);
            if (output instanceof Artifact && ((Artifact) output).isTreeArtifact()) {
              path.deleteTreesBelow();
            } else {
              path.deleteTree();
            }
          }
        } catch (IOException e) {
          stepLog(SEVERE, e, "Cannot delete local output %s after interrupt", path);
        }
      }
    }
  }

  private static FailureDetail makeFailureDetail(int exitCode, Status status, String actionType) {
    FailureDetails.Spawn.Builder spawnFailure = FailureDetails.Spawn.newBuilder();
    switch (status) {
      case SUCCESS:
        throw new AssertionError("makeFailureDetail() called with Status == SUCCESS");
      case NON_ZERO_EXIT:
        spawnFailure.setCode(Code.NON_ZERO_EXIT).setSpawnExitCode(exitCode);
        break;
      case TIMEOUT:
        spawnFailure.setCode(Code.TIMEOUT);
        break;
      case OUT_OF_MEMORY:
        spawnFailure.setCode(Code.OUT_OF_MEMORY);
        break;
      case EXECUTION_FAILED:
        spawnFailure.setCode(Code.EXECUTION_FAILED);
        break;
      case EXECUTION_FAILED_CATASTROPHICALLY:
        spawnFailure.setCode(Code.EXECUTION_FAILED).setCatastrophic(true);
        break;
      case EXECUTION_DENIED:
        spawnFailure.setCode(Code.EXECUTION_DENIED);
        break;
      case EXECUTION_DENIED_CATASTROPHICALLY:
        spawnFailure.setCode(Code.EXECUTION_DENIED).setCatastrophic(true);
        break;
      case REMOTE_CACHE_FAILED:
        spawnFailure.setCode(Code.REMOTE_CACHE_FAILED);
        break;
    }
    return FailureDetail.newBuilder()
        .setMessage("local spawn failed for " + actionType)
        .setSpawn(spawnFailure)
        .build();
  }

  private enum State {
    INITIALIZING,
    PARSING,
    PREFETCHING_LOCAL_INPUTS,
    LOCAL_ACTION_RUNNING,
    PERMANENT_ERROR,
    SUCCESS;
  }
}