text:
<?php
/**
 * Nofuzz\Http\Client
 *
 * Generic HTTP Client that has some quick helper funcs for quick GET,POST,PUT etc.
 *
 * GET Example:
 *
 *    if ($httpClient->get('http://<domain>/<path>')) {
 *      $responseBody = $httpClient->getResponse()->getBody();
 *    } else {
 *      // error
 *    }
 *
 * @package   Nofuzz
 */
#################################################################################################################################

namespace Nofuzz\Http;

class Client // extends ... implements ...
{
  protected $guzzleClient = null;
  protected $cookieJar = null;

  protected $timeoutConnect = 3;
  protected $timeoutReceive = 10;
  protected $httpRequest = null;
  protected $httpResponse = null;
  protected $retries = 1;

  protected $timeStart = 0;
  protected $timeHeaders = 0;
  protected $timeResponse = 0;

  protected $opts = [];

  protected $lastErrorStr = '';

  /**
   * Constructor
   *
   * @param array $opts             Guzzle compatible parameters array
   */
  public function __construct(array $opts=[])
  {
    $this->guzzleClient = null;
    $this->setRequestOptions($opts);
  }

  /**
   * Create the internal GuzzleHttp\Client
   *
   * @param  array  $opts [description]
   * @return object
   */
  protected function createClient(array $opts=[])
  {
    if ( !$this->guzzleClient ) {
      $this->guzzleClient = new \GuzzleHttp\Client();
      $this->cookieJar = new \GuzzleHttp\Cookie\CookieJar();
    }

    return $this->guzzleClient;
  }

  /**
   * Creates & returns a GuzzleHttp\Request
   *
   * @param  string $method     [description]
   * @param  string $url        [description]
   * @param  mixed  $body       [description]
   * @param  array  $headers    [description]
   * @return object
   */
  public function createRequest(string $method, string $url, $body=null, array $headers=[])
  {
    # Merge Default Headers with user provided headers
    $headers = array_merge(
      [
         'Accept'          => '*/*',
         'Accept-Encoding' => 'gzip, deflate'
      ],
      $headers
    );

    # Create the httpRequest
    $this->httpRequest = new \GuzzleHttp\Psr7\Request( $method, $url, $headers, $body );

    return $this->httpRequest;
  }

  /**
   * Send a GuzzleHttp\Request
   *
   * @param  \GuzzleHttp\Psr7\Request $request
   * @param  array                    $opts     Guzzle Send Options
   * @return \GuzzleHttp\Response
   */
  public function sendRequest(\GuzzleHttp\Psr7\Request $request, array $opts=[])
  {
    # Set params
    $retriesLeft = $this->retries;
    $this->lastErrorStr = '';

    # Retry loop
    while ( $retriesLeft>0 )
    {
      # Decrease retry count
      $retriesLeft--;

      $this->timeStart = 0;
      $this->timeHeaders = 0;
      $this->timeResponse = 0;

      try {
        # Make sure we have a GuzzleHttp\Client
        $this->createClient($this->opts);
        $this->timeStart = microtime(true);

        # Request Options
        $opts = array_merge(
          [
            'http_errors' => true,                               // Exceptions on 4xx response codes
            'connect_timeout' => $this->getTimeoutConnect(),     // Connect Timeout (seconds)
            'timeout'  => $this->getTimeoutReceive(),            // Receive Timeout (seconds)
            'verify' => false                                    // Disable SSL verification (handle self generated SSL certs)
          ]
          ,$this->getRequestOptions()
        );

        $sendOpts = array_merge([
           'on_headers' => function (\GuzzleHttp\Psr7\Response $response) {
             $this->timeHeaders = microtime(true)-$this->timeStart;
           },
           'synchronous'      => true,
           'cookies'          => $this->cookieJar,
           'debug'            => false
           // 'on_headers' => function ( \Psr\Http\Message\ResponseInterface $response ) {
           //   error_log( print_r($response->getHeaders(), true) );
           // },
           // 'on_stats' => function ( \GuzzleHttp\TransferStats $status ) {
           //   error_log( $status->getTransferTime().' - '.print_r($status->getHandlerStats(),true) );
           // }
         ],$opts
        );

        # Send the Request
        $this->httpResponse = $this->guzzleClient->send($request, $sendOpts);

        # Successful response, break the loop
        $retriesLeft = 0;

      } catch (\GuzzleHttp\Exception\ConnectException  $e) {
        # Network errors
        #
        # Note: For "Host not found", "DNS failure", "Network errors" etc.
        #       we might not have a Response Object!

        # Set error String
        $this->lastErrorStr = $e->getMessage();

        # Get the Response Object from the Exception
        if ( $e->hasResponse() ) {
          $this->httpResponse = $e->getResponse();
        }

        # No point in retrying
        $retriesLeft = 0;

      } catch (\GuzzleHttp\Exception\BadResponseException $e) {
        # 4xx (ClientException)
        # 5xx (ServerException)
        #
        # Note:  We have a response object available, meaning the target service responded
        #        so no retry needed (and it exists so no SDR reporting)

        # Set error String
        $this->lastErrorStr = $e->getMessage();

        # Get the Response Object from the Exception
        if ( $e->hasResponse() ) {
          $this->httpResponse = $e->getResponse();
        }

        # Break the while loop (no retries for this error)
        $retriesLeft = 0;

      } catch (\GuzzleHttp\Exception\RequestException $e) {
        # Also Catches
        #   TooManyRedirectsException

        # Set error String
        $this->lastErrorStr = $e->getMessage();

        # Get the Response Object from the Exception
        if ( $e->hasResponse() ) {
          $this->httpResponse = $e->getResponse();
        }

        # Should we do a retry?
        if ($retriesLeft>0) {
          $_sec = 0.1; // 0.1 seconds = 100 ms
          usleep($_sec * 1000000);
          unset($_sec);
        }

      } catch (\Exception $e) {
        # General exception
        #

        # Set error String
        $this->lastErrorStr = $e->getMessage();

        # Break the while loop (no retries for this error)
        $retriesLeft = 0;

      } finally {
        $this->timeResponse = microtime(true) - $this->timeStart;

      }

    } // while

    return $this->httpResponse;
  }

  /**
   * Send a GET request
   *
   * @param  string $uri                The uri to call in the service
   * @param  array $headers             The http headers
   * @return bool                       True for success
   */
  public function get(string $uri, array $headers=[])
  {
    $this->sendRequest($this->createRequest('GET',$uri), $headers);

    return !is_null($this->getResponse());
  }

  /**
   * Send a POST request
   *
   * @param  string $uri                The uri to call in the service
   * @param  string $body               The body to send
   * @param  array $headers             The http headers
   * @return bool                       True for success
   */
  public function post(string $uri, string $body='', array $headers=[])
  {
    $this->sendRequest($this->createRequest('POST',$uri,$body), $headers);

    return !is_null($this->getResponse());
  }

  /**
   * Send a PUT request
   *
   * @param  string $uri                The uri to call in the service
   * @param  string $body               The body to send
   * @param  array $headers             The http headers
   * @return bool                       True for success
   */
  public function put(string $uri, string $body='', array $headers=[])
  {
    $this->sendRequest($this->createRequest('PUT',$uri,$body), $headers);

    return !is_null($this->getResponse());
  }

  /**
   * Send a DELETE request
   *
   * @param  string $uri                The uri to call in the service
   * @param  array $headers             The http headers
   * @return bool                       True for success
   */
  public function delete(string $uri, array $headers=[])
  {
    $this->sendRequest($this->createRequest('DELETE',$uri), $headers);

    return !is_null($this->getResponse());
  }

  /**
   * Send a PATCH request
   *
   * @param  string $uri                The uri to call in the service
   * @param  array $headers             The http headers
   * @return bool                       True for success
   */
  public function patch(string $uri, array $headers=[])
  {
    $this->sendRequest($this->createRequest('PATCH',$uri), $headers);

    return !is_null($this->getResponse());
  }

  /**
   * Send a HEAD request
   *
   * @param  string $uri                The uri to call in the service
   * @param  array $headers             The http headers
   * @return bool                       True for success
   */
  public function head(string $uri, array $headers=[])
  {
    $this->sendRequest($this->createRequest('HEAD',$uri), $headers);

    return !is_null($this->getResponse());
  }

  /**
   * Send a custom HTTP request
   *
   * @param  string $uri                The uri to call in the service
   * @param  array $headers             The http headers
   * @return bool                       True for success
   */
  public function custom(string $method, string $uri, string $body='', array $headers=[])
  {
    $this->sendRequest($this->createRequest($method,$uri), $headers);

    return !is_null($this->getResponse());
  }

  public function getLastErrorStr(): string
  {
    return $this->lastErrorStr;
  }
  /**
   * Get Timeout for Connect
   *
   * @return float
   */
  function getTimeoutConnect(): float
  {
    return $this->timeoutConnect;
  }

  /**
   * Set Connect Timeout
   *
   * @param   float $timeout          The timeout in seconds
   * @return  self
   */
  function setTimeoutConnect(float $timeout)
  {
    $this->timeoutConnect = $timeout;
    return $this;
  }

  /**
   * Get Timeout for Receive
   *
   * @return float
   */
  function getTimeoutReceive(): float
  {
    return $this->timeoutReceive;
  }

  /**
   * Set Receive Timeout
   *
   * @param   float $timeout          The timeout in seconds
   * @return  self
   */
  function setTimeoutReceive(float $timeout)
  {
    $this->timeoutReceive = $timeout;
    return $this;
  }

  /**
   * Get Retries count
   *
   * @return int
   */
  function getRetires(): int
  {
    return $this->retires;
  }

  /**
   * Set Retires count
   *
   * @param   int $retires          The number of times to retry a failed request
   * @return  self
   */
  function setRetries(int $retries)
  {
    $this->retires = $retries;
    return $this;
  }

  /**
   * Get last Request Object or null
   *
   * @param   float $timeout          The timeout in seconds
   * @return  null | \Guzzle\Psr7\HttpResquest
   */
  public function getRequest()
  {
    return $this->httpRequest;
  }

  /**
   * Get last Response Object or null
   *
   * @return  null | \Guzzle\Psr7\HttpResponse
   */
  public function getResponse()
  {
    return $this->httpResponse;
  }

  /**
   * Get TTFB (Time to First Byte) in seconds
   *
   * @return float
   */
  public function getHeadersTime(): float
  {
    return $this->timeHeaders;
  }

  /**
   * Get Response Time in seconds
   *
   * @return float
   */
  public function getResponseTime(): float
  {
    return $this->timeResponse;
  }

  /**
   * Get Opts
   *
   * @return array
   */
  public function getRequestOptions(): array
  {
    return $this->opts;
  }

  /**
   * Set Request Options
   *
   * @return self
   */
  public function setRequestOptions(array $opts)
  {
    $this->opts = $opts;

    return $this;
  }

}


text:
using System;

namespace Azure.AI.FormRecognizer.DocumentAnalysis
{
    /// <summary> An object representing a form field with distinct field label (key) and field value (may be empty). </summary>
    public partial class DocumentKeyValuePair
    {
        /// <summary> Initializes a new instance of DocumentKeyValuePair. </summary>
        /// <param name="key"> Field label of the key-value pair. </param>
        /// <param name="confidence"> Confidence of correctly extracting the key-value pair. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
        internal DocumentKeyValuePair(DocumentKeyValueElement key, float confidence)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            Key = key;
            Confidence = confidence;
        }

        /// <summary> Initializes a new instance of DocumentKeyValuePair. </summary>
        /// <param name="key"> Field label of the key-value pair. </param>
        /// <param name="value"> Field value of the key-value pair. </param>
        /// <param name="confidence"> Confidence of correctly extracting the key-value pair. </param>
        internal DocumentKeyValuePair(DocumentKeyValueElement key, DocumentKeyValueElement value, float confidence)
        {
            Key = key;
            Value = value;
            Confidence = confidence;
        }

        /// <summary> Field label of the key-value pair. </summary>
        public DocumentKeyValueElement Key { get; }
        /// <summary> Field value of the key-value pair. </summary>
        public DocumentKeyValueElement Value { get; }
        /// <summary> Confidence of correctly extracting the key-value pair. </summary>
        public float Confidence { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<component name="libraryTable">
  <library name="SBT: javax.servlet:javax.servlet-api:3.0.1:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/javax.servlet/javax.servlet-api/jars/javax.servlet-api-3.0.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$USER_HOME$/.ivy2/cache/javax.servlet/javax.servlet-api/docs/javax.servlet-api-3.0.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/javax.servlet/javax.servlet-api/srcs/javax.servlet-api-3.0.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
namespace MassTransit.Transports
{
    using System;
    using System.Threading.Tasks;

    public interface ISendTransportProvider
    {
        Task<ISendTransport> GetSendTransport(Uri address);

        Uri NormalizeAddress(Uri address);
    }
}


text:
@interface WXMWIssueEditorAssignUser ()

@end

@implementation WXMWIssueEditorAssignUser

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Reveal the loading indicator.
    _loadingLabel.hidden = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    // Get the list of contributors from user defaults.
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *contribs = [defaults objectForKey:@"current_repo_contributors"];

    // Make buttons for users.
    [self makeUserButtons:contribs];
}

// Make a butotn for each user that can be assigned as a contributor.
- (void)makeUserButtons:(NSArray *)allowedContributors
{
    // Distance from the top of the canvas.
    NSUInteger fromTop = 0;

    // Get the currently selected assignee (there may not be one).
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *selectedUser = [defaults objectForKey:@"current_issue_assignee"];

    // Create button for each available user.
    for (id user in allowedContributors) {
        [self createUserButton:user fromTop:fromTop selectedUser:selectedUser];
        fromTop += 50;;
    }

    // Create one additional label to let the user non-assign the issue.
    [self createUserButton:@"no assignee" fromTop:fromTop selectedUser:selectedUser];

    // Hide loading indicator.
    _loadingLabel.hidden = YES;
}

// Create a button for a user.
- (void)createUserButton:(NSString *)user fromTop:(CGFloat)fromTop selectedUser:(NSString *)selectedUser
{
    // Create the button and set its title/content with the username.
    CGRect rect = CGRectMake(30, fromTop, 250, 35);
    UIButton *labelLabel = [[UIButton alloc] initWithFrame:rect];
    [labelLabel setTitle:user forState:UIControlStateNormal];
    labelLabel.titleLabel.font = [UIFont systemFontOfSize:14.0];

    // Set a default background and text color.
    NSString *bgColorString = @"F1F1F1";
    NSString *textColorString = @"333333";

    // Alter colors if the user is the currently selected one.
    if ([user isEqualToString:selectedUser]) {
        bgColorString = @"2EAD59";
        textColorString = @"F1F1F1";
    }

    // If no selected user exists, give 'no assignee' button the style of the selected item.
    if (!selectedUser || [selectedUser isEqualToString:@""]) {
        if ([user isEqualToString:@"no assignee"]) {
            bgColorString = @"2EAD59";
            textColorString = @"F1F1F1";
        }
    }

    // Set some display properties for the button.
    [labelLabel setTitleColor:[Utils hexColor:textColorString] forState:UIControlStateNormal];
    [labelLabel setBackgroundColor: [Utils hexColor:bgColorString]];
    labelLabel.layer.cornerRadius = 2;
    labelLabel.layer.masksToBounds = YES;

    // Append to the user-list holder.
    [_userHolder addSubview:labelLabel];

    // Add click event to the button.
    [labelLabel addTarget:self action:@selector(addUserAsAssignee:) forControlEvents:UIControlEventTouchUpInside];

}

// Assign the user to the issue.
- (IBAction)addUserAsAssignee:(id)sender
{
    NSString *user = [sender currentTitle];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    // Represent no user with nil.
    if ([user isEqualToString:@"no assignee"]) {
        user = nil;
    }

    // Remember the current user selection.
    [defaults setObject:user forKey:@"current_issue_assignee"];
    [defaults synchronize];

    // Dismiss the current view.
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// User is cancelling.  Dismiss the current view.
- (IBAction)cancelAssignUser:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<artifactId>lyza-webservice</artifactId>
	<packaging>jar</packaging>
	<name>Lyza : Web Services</name>

	<parent>
		<groupId>com.griddelta</groupId>
		<artifactId>lyza-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<scm>
		<connection>scm:git:git@github.com:boneill42/lyza.git</connection>
		<developerConnection>scm:git:git@github.com:boneill42/lyza.git</developerConnection>
		<url>git@github.com:boneill42/lyza.git</url>
	</scm>

	<developers>
		<developer>
			<id>boneill42</id>
			<name>Brian O'Neill</name>
			<email>bone@alumni.brown.edu</email>
		</developer>
	</developers>

	<dependencies>
		<dependency>
			<groupId>com.griddelta</groupId>
			<artifactId>lyza-spark</artifactId>
			<exclusions>
				<exclusion>
					<artifactId>log4j</artifactId>
					<groupId>log4j</groupId>
				</exclusion>
				<exclusion>
					<artifactId>slf4j-log4j12</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
				<exclusion>
					<artifactId>metrics-core</artifactId>
					<groupId>com.codahale.metrics</groupId>
				</exclusion>
				<exclusion>
					<artifactId>hadoop-yarn-client</artifactId>
					<groupId>org.apache.hadoop</groupId>
				</exclusion>
				<exclusion>
					<artifactId>hadoop-yarn-server-common</artifactId>
					<groupId>org.apache.hadoop</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.1</version>
		</dependency>
		<dependency>
			<groupId>io.dropwizard</groupId>
			<artifactId>dropwizard-core</artifactId>
			<version>0.8.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>io.dropwizard</groupId>
			<artifactId>dropwizard-assets</artifactId>
			<version>0.8.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>18.0</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
		<resources>
			<resource>
				<filtering>true</filtering>
				<directory>${basedir}/src/main/resources</directory>
			</resource>
		</resources>
	</build>
</project>


text:
set -e

# Show explicitly which commands are currently running.
set -x

MEMORY_SIZE=$1
SHM_SIZE=$2
DOCKER_SHA=$3

ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE:-$0}")"; pwd)
SUPPRESS_OUTPUT=$ROOT_DIR/../suppress_output

if [ "$MEMORY_SIZE" == "" ]; then
    MEMORY_SIZE="20G"
fi
if [ "$SHM_SIZE" == "" ]; then
    SHM_SIZE="20G"
fi
if [ "$DOCKER_SHA" == "" ]; then
    echo "Building application docker."
    docker build -q --no-cache -t ray-project/base-deps docker/base-deps

    # Add Ray source
    git rev-parse HEAD > ./docker/tune_test/git-rev
    git archive -o ./docker/tune_test/ray.tar $(git rev-parse HEAD)
    DOCKER_SHA=$(docker build --no-cache -q -t ray-project/tune_test docker/tune_test)
fi

echo "Using Docker image" $DOCKER_SHA

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    pytest /ray/python/ray/tune/tests/test_cluster.py

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    pytest /ray/python/ray/tune/tests/test_actor_reuse.py

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/tune_mnist_ray.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/pbt_example.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/hyperband_example.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/async_hyperband_example.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/tune_mnist_ray_hyperband.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/tune_mnist_async_hyperband.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/logging_example.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/bayesopt_example.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/hyperopt_example.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} -e SIGOPT_KEY $DOCKER_SHA \
    python /ray/python/ray/tune/examples/sigopt_example.py \
    --smoke-test

# Runs only on Python3
# docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
#     python3 /ray/python/ray/tune/examples/nevergrad_example.py \
#     --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/tune_mnist_keras.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/mnist_pytorch.py --smoke-test --no-cuda

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/mnist_pytorch_trainable.py \
    --smoke-test --no-cuda

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/genetic_example.py \
    --smoke-test

$SUPPRESS_OUTPUT docker run --rm --shm-size=${SHM_SIZE} --memory=${MEMORY_SIZE} $DOCKER_SHA \
    python /ray/python/ray/tune/examples/skopt_example.py \
    --smoke-test


text:
<?php

/**
 * BaseStory
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property string $slug
 * @property clob $body
 *
 * @method string getSlug() Returns the current record's "slug" value
 * @method clob   getBody() Returns the current record's "body" value
 * @method Story  setSlug() Sets the current record's "slug" value
 * @method Story  setBody() Sets the current record's "body" value
 *
 * @package    ##PROJECT_NAME##
 * @subpackage model
 * @author     ##AUTHOR_NAME##
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseStory extends sfDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('story');
        $this->hasColumn('slug', 'string', 50, array(
             'type' => 'string',
             'length' => 50,
             ));
        $this->hasColumn('body', 'clob', null, array(
             'type' => 'clob',
             'notnull' => true,
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $i18n0 = new Doctrine_Template_I18n(array(
             'fields' =>
             array(
              0 => 'body',
             ),
             ));
        $solr0 = new Doctrine_Template_Solr(array(
             'fields' =>
             array(
              0 => 'body',
             ),
             ));
        $this->actAs($i18n0);
        $this->actAs($solr0);
    }
}


text:
package com.thoughtworks.go.config;

import com.rits.cloning.Cloner;
import com.thoughtworks.go.config.commands.EntityConfigUpdateCommand;
import com.thoughtworks.go.config.exceptions.*;
import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry;
import com.thoughtworks.go.config.remote.ConfigOrigin;
import com.thoughtworks.go.config.remote.PartialConfig;
import com.thoughtworks.go.domain.GoConfigRevision;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.util.ServerVersion;
import com.thoughtworks.go.serverhealth.HealthStateScope;
import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.serverhealth.ServerHealthState;
import com.thoughtworks.go.service.ConfigRepository;
import com.thoughtworks.go.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import static com.thoughtworks.go.util.ExceptionUtils.bomb;
import static java.lang.String.format;

/**
 * This class find the location of cruise-config.xml and turn that into stream
 * and passing it into MagicLoader or MagicWriter.
 */
@Component
public class GoFileConfigDataSource {
    private static final Logger LOGGER = Logger.getLogger(GoFileConfigDataSource.class);
    private final Charset UTF_8 = Charset.forName("UTF-8");
    private final CachedGoPartials cachedGoPartials;

    private ReloadStrategy reloadStrategy = new ReloadIfModified();
    private final MagicalGoConfigXmlWriter magicalGoConfigXmlWriter;
    private final MagicalGoConfigXmlLoader magicalGoConfigXmlLoader;
    private final ConfigRepository configRepository;
    private SystemEnvironment systemEnvironment;
    private GoConfigMigration upgrader;
    private final TimeProvider timeProvider;
    private ServerVersion serverVersion;
    private Cloner cloner = new Cloner();
    public static final String FILESYSTEM = "Filesystem";
    private ServerHealthService serverHealthService;

    /* Will only upgrade cruise config file on application startup. */
    @Autowired
    public GoFileConfigDataSource(GoConfigMigration upgrader, ConfigRepository configRepository, SystemEnvironment systemEnvironment, TimeProvider timeProvider, ConfigCache configCache,
                                  ServerVersion serverVersion, ConfigElementImplementationRegistry configElementImplementationRegistry,
                                  ServerHealthService serverHealthService, CachedGoPartials cachedGoPartials) {
        this(upgrader, configRepository, systemEnvironment, timeProvider, serverVersion,
                new MagicalGoConfigXmlLoader(configCache, configElementImplementationRegistry),
                new MagicalGoConfigXmlWriter(configCache, configElementImplementationRegistry), serverHealthService, cachedGoPartials);
    }

    GoFileConfigDataSource(GoConfigMigration upgrader, ConfigRepository configRepository, SystemEnvironment systemEnvironment, TimeProvider timeProvider,
                           ServerVersion serverVersion, MagicalGoConfigXmlLoader magicalGoConfigXmlLoader, MagicalGoConfigXmlWriter magicalGoConfigXmlWriter,
                           ServerHealthService serverHealthService, CachedGoPartials cachedGoPartials) {
        this.configRepository = configRepository;
        this.systemEnvironment = systemEnvironment;
        this.upgrader = upgrader;
        this.timeProvider = timeProvider;
        this.serverVersion = serverVersion;
        this.magicalGoConfigXmlLoader = magicalGoConfigXmlLoader;
        this.magicalGoConfigXmlWriter = magicalGoConfigXmlWriter;
        this.serverHealthService = serverHealthService;
        this.cachedGoPartials = cachedGoPartials;
    }

    public GoFileConfigDataSource reloadEveryTime() {
        this.reloadStrategy = new AlwaysReload();
        return this;
    }

    public GoFileConfigDataSource reloadIfModified() {
        this.reloadStrategy = new ReloadIfModified();
        return this;
    }

    public File fileLocation() {
        return new File(systemEnvironment.getCruiseConfigFile());
    }

    public GoConfigHolder load() throws Exception {
        File configFile = fileLocation();

        ReloadStrategy.ReloadTestResult result = reloadStrategy.requiresReload(configFile);
        if (!result.requiresReload) {
            reloadStrategy.hasLatest(result);
            return null;
        }
        synchronized (this) {
            result = reloadStrategy.requiresReload(configFile);
            if (!result.requiresReload) {
                reloadStrategy.hasLatest(result);
                return null;
            }

            reloadStrategy.performingReload(result);

            LOGGER.info("Config file changed at " + result.modifiedTime);
            LOGGER.info("Reloading config file: " + configFile);

            encryptPasswords(configFile);
            LOGGER.debug("Detected change in config file.");
            return forceLoad(configFile);
        }
    }

    private void encryptPasswords(File configFile) throws Exception {
        String currentContent = FileUtils.readFileToString(configFile);
        GoConfigHolder configHolder = magicalGoConfigXmlLoader.loadConfigHolder(currentContent);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        magicalGoConfigXmlWriter.write(configHolder.configForEdit, stream, true);
        String postEncryptContent = new String(stream.toByteArray());
        if (!currentContent.equals(postEncryptContent)) {
            LOGGER.debug("[Encrypt] Writing config to file");
            FileUtils.writeStringToFile(configFile, postEncryptContent);
        }
    }

    synchronized GoConfigHolder forceLoad(File configFile) throws Exception {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Reloading config file: " + configFile.getAbsolutePath());
        }
        GoConfigHolder holder;
        try {
            try {
                List<PartialConfig> lastKnownPartials = cloner.deepClone(cachedGoPartials.lastKnownPartials());
                holder = internalLoad(FileUtils.readFileToString(configFile), new ConfigModifyingUser(FILESYSTEM), lastKnownPartials);
            } catch (GoConfigInvalidException e) {
                if (cachedGoPartials.lastValidPartials().isEmpty()) {
                    throw e;
                } else {
                    List<PartialConfig> lastValidPartials = cloner.deepClone(cachedGoPartials.lastValidPartials());
                    holder = internalLoad(FileUtils.readFileToString(configFile), new ConfigModifyingUser(FILESYSTEM), lastValidPartials);
                }
            }
            return holder;
        } catch (Exception e) {
            LOGGER.error("Unable to load config file: " + configFile.getAbsolutePath() + " " + e.getMessage(), e);
            if (configFile.exists()) {
                LOGGER.warn("--- " + configFile.getAbsolutePath() + " ---");
                LOGGER.warn(FileUtil.readContentFromFile(configFile));
                LOGGER.warn("------");
            }
            LOGGER.debug(e);
            throw e;
        }
    }

    @Deprecated
    public synchronized GoConfigHolder write(String configFileContent, boolean shouldMigrate) throws Exception {
        File configFile = fileLocation();
        try {
            if (shouldMigrate) {
                configFileContent = upgrader.upgradeIfNecessary(configFileContent);
            }
            GoConfigHolder configHolder = internalLoad(configFileContent, new ConfigModifyingUser(), new ArrayList<PartialConfig>());
            String toWrite = configAsXml(configHolder.configForEdit, false);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Writing config file: " + configFile.getAbsolutePath());
            }
            writeToConfigXmlFile(toWrite);
            return configHolder;
        } catch (Exception e) {
            LOGGER.error("Unable to write config file: " + configFile.getAbsolutePath()
                    + "\n" + e.getMessage(), e);
            throw e;
        }
    }

    private void writeToConfigXmlFile(String content) {
        FileChannel channel = null;
        FileOutputStream outputStream = null;
        FileLock lock = null;
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
            channel = randomAccessFile.getChannel();
            lock = channel.lock();
            randomAccessFile.seek(0);
            randomAccessFile.setLength(0);
            outputStream = new FileOutputStream(randomAccessFile.getFD());

            IOUtils.write(content, outputStream, UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (channel != null && lock != null) {
                try {
                    lock.release();
                    channel.close();
                    IOUtils.closeQuietly(outputStream);
                } catch (IOException e) {
                    LOGGER.error("Error occured when releasing file lock and closing file.", e);
                }
            }
        }
    }

    public synchronized EntityConfigSaveResult writeEntityWithLock(EntityConfigUpdateCommand updatingCommand, GoConfigHolder configHolder, Username currentUser) {
        CruiseConfig modifiedConfig = cloner.deepClone(configHolder.configForEdit);
        try {
            updatingCommand.update(modifiedConfig);
        } catch (Exception e) {
            bomb(e);
        }
        List<PartialConfig> lastValidPartials = cachedGoPartials.lastValidPartials();
        List<PartialConfig> lastKnownPartials = cachedGoPartials.lastKnownPartials();
        if (lastKnownPartials.isEmpty() || areKnownPartialsSameAsValidPartials(lastKnownPartials, lastValidPartials)) {
            return trySavingEntity(updatingCommand, currentUser, modifiedConfig, lastValidPartials);
        }
        try {
            return trySavingEntity(updatingCommand, currentUser, modifiedConfig, lastValidPartials);
        } catch (GoConfigInvalidException e) {
            StringBuilder errorMessageBuilder = new StringBuilder();
            try {
                String message = String.format(
                        "Merged update operation failed on VALID %s partials. Falling back to using LAST KNOWN %s partials. Exception message was: [%s %s]",
                        lastValidPartials.size(), lastKnownPartials.size(), e.getMessage(), e.getAllErrorMessages());
                errorMessageBuilder.append(message);
                LOGGER.warn(message, e);
                updatingCommand.clearErrors();
                modifiedConfig.setPartials(lastKnownPartials);
                String configAsXml = configAsXml(modifiedConfig, false);
                GoConfigHolder holder = internalLoad(configAsXml, new ConfigModifyingUser(currentUser.getUsername().toString()), lastKnownPartials);
                LOGGER.info(String.format("Update operation on merged configuration succeeded with %s KNOWN partials. Now there are %s LAST KNOWN partials",
                        lastKnownPartials.size(), cachedGoPartials.lastKnownPartials().size()));
                return new EntityConfigSaveResult(holder.config, holder);
            } catch (Exception exceptionDuringFallbackValidation) {
                String message = String.format(
                        "Merged config update operation failed using fallback LAST KNOWN %s partials. Exception message was: %s",
                        lastKnownPartials.size(), exceptionDuringFallbackValidation.getMessage());
                LOGGER.warn(message, exceptionDuringFallbackValidation);
                errorMessageBuilder.append(System.lineSeparator());
                errorMessageBuilder.append(message);
                throw new GoConfigInvalidException(e.getCruiseConfig(), errorMessageBuilder.toString());
            }
        }

    }

    private EntityConfigSaveResult trySavingEntity(EntityConfigUpdateCommand updatingCommand, Username currentUser, CruiseConfig modifiedConfig, List<PartialConfig> partials) {
        modifiedConfig.setPartials(partials);
        CruiseConfig preprocessedConfig = cloner.deepClone(modifiedConfig);
        MagicalGoConfigXmlLoader.preprocess(preprocessedConfig);

        if (updatingCommand.isValid(preprocessedConfig)) {
            try {
                LOGGER.info("[Configuration Changed] Saving updated configuration.");
                String configAsXml = configAsXml(modifiedConfig, true);
                String md5 = CachedDigestUtils.md5Hex(configAsXml);
                MagicalGoConfigXmlLoader.setMd5(modifiedConfig, md5);
                MagicalGoConfigXmlLoader.setMd5(preprocessedConfig, md5);
                writeToConfigXmlFile(configAsXml);
                checkinConfigToGitRepo(partials, preprocessedConfig, configAsXml, md5, currentUser.getUsername().toString());
                LOGGER.debug("[Config Save] Done writing with lock");
                return new EntityConfigSaveResult(updatingCommand.getPreprocessedEntityConfig(), new GoConfigHolder(preprocessedConfig, modifiedConfig));
            } catch (Exception e) {
                throw new RuntimeException("failed to save : " + e.getMessage());
            }
        } else {
            throw new GoConfigInvalidException(preprocessedConfig, "Validation failed.");
        }
    }

    public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand, GoConfigHolder configHolder) {
        try {

            // Need to convert to xml before we try to write it to the config file.
            // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly.
            GoConfigHolder validatedConfigHolder;

            List<PartialConfig> lastKnownPartials = cachedGoPartials.lastKnownPartials();
            List<PartialConfig> lastValidPartials = cachedGoPartials.lastValidPartials();
            try {
                validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastKnownPartials);
                updateMergedConfigForEdit(validatedConfigHolder, lastKnownPartials);
            } catch (Exception e) {
                if (lastKnownPartials.isEmpty() || areKnownPartialsSameAsValidPartials(lastKnownPartials, lastValidPartials)) {
                    throw e;
                } else {
                    LOGGER.warn(String.format(
                            "Merged config update operation failed on LATEST %s partials. Falling back to using LAST VALID %s partials. Exception message was: %s",
                            lastKnownPartials.size(), lastValidPartials.size(), e.getMessage()), e);
                    try {
                        validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastValidPartials);
                        updateMergedConfigForEdit(validatedConfigHolder, lastValidPartials);
                        LOGGER.info(String.format("Update operation on merged configuration succeeded with old %s LAST VALID partials.", lastValidPartials.size()));
                    } catch (GoConfigInvalidException fallbackFailed) {
                        LOGGER.warn(String.format(
                                "Merged config update operation failed using fallback LAST VALID %s partials. Exception message was: %s",
                                lastValidPartials.size(), fallbackFailed.getMessage()), fallbackFailed);
                        throw new GoConfigInvalidMergeException("Fallback merge failed", lastValidPartials, fallbackFailed);
                    }
                }
            }
            ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder) ? ConfigSaveState.MERGED : ConfigSaveState.UPDATED;
            return new GoConfigSaveResult(validatedConfigHolder, configSaveState);
        } catch (ConfigFileHasChangedException e) {
            LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: " + e.getMessage(), e);
            throw e;
        } catch (GoConfigInvalidException e) {
            LOGGER.warn("Configuration file is invalid: " + e.getMessage(), e);
            throw bomb(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error("Configuration file is not valid: " + e.getMessage(), e);
            throw bomb(e.getMessage(), e);
        } finally {
            LOGGER.debug("[Config Save] Done writing with lock");
        }
    }

    protected boolean areKnownPartialsSameAsValidPartials(List<PartialConfig> lastKnownPartials, List<PartialConfig> lastValidPartials) {
        if (lastKnownPartials.size() != lastValidPartials.size()) {
            return false;
        }
        final ArrayList<ConfigOrigin> validConfigOrigins = ListUtil.map(lastValidPartials, new ListUtil.Transformer<PartialConfig, ConfigOrigin>() {
            @Override
            public ConfigOrigin transform(PartialConfig partialConfig) {
                return partialConfig.getOrigin();
            }
        });
        PartialConfig invalidKnownPartial = ListUtil.find(lastKnownPartials, new ListUtil.Condition() {
            @Override
            public <T> boolean isMet(T item) {
                return !validConfigOrigins.contains(((PartialConfig) item).getOrigin());
            }
        });
        return invalidKnownPartial == null;
    }

    private void updateMergedConfigForEdit(GoConfigHolder validatedConfigHolder, List<PartialConfig> partialConfigs) {
        if (partialConfigs.isEmpty()) return;
        CruiseConfig mergedCruiseConfigForEdit = cloner.deepClone(validatedConfigHolder.configForEdit);
        mergedCruiseConfigForEdit.merge(partialConfigs, true);
        validatedConfigHolder.mergedConfigForEdit = mergedCruiseConfigForEdit;
    }

    private GoConfigHolder trySavingConfig(UpdateConfigCommand updatingCommand, GoConfigHolder configHolder, List<PartialConfig> partials) throws Exception {
        String configAsXml;
        GoConfigHolder validatedConfigHolder;
        LOGGER.debug("[Config Save] ==-- Getting modified config");
        if (shouldMergeConfig(updatingCommand, configHolder)) {
            if (!systemEnvironment.get(SystemEnvironment.ENABLE_CONFIG_MERGE_FEATURE)) {
                throw new ConfigMergeException(ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH);
            }
            configAsXml = getMergedConfig((NoOverwriteUpdateConfigCommand) updatingCommand, configHolder.configForEdit.getMd5(), partials);
            try {
                validatedConfigHolder = internalLoad(configAsXml, getConfigUpdatingUser(updatingCommand), partials);
            } catch (Exception e) {
                LOGGER.info(format("[CONFIG_MERGE] Post merge validation failed, latest-md5: %s", configHolder.configForEdit.getMd5()));
                throw new ConfigMergePostValidationException(e.getMessage(), e);
            }
        } else {
            configAsXml = getUnmergedConfig(updatingCommand, configHolder, partials);
            validatedConfigHolder = internalLoad(configAsXml, getConfigUpdatingUser(updatingCommand), partials);
        }
        LOGGER.info(String.format("[Configuration Changed] Saving updated configuration."));
        writeToConfigXmlFile(configAsXml);
        return validatedConfigHolder;
    }

    private ConfigModifyingUser getConfigUpdatingUser(UpdateConfigCommand updatingCommand) {
        return updatingCommand instanceof UserAware ? ((UserAware) updatingCommand).user() : new ConfigModifyingUser();
    }

    private String getUnmergedConfig(UpdateConfigCommand updatingCommand, GoConfigHolder configHolder, List<PartialConfig> partials) throws Exception {
        CruiseConfig deepCloneForEdit = cloner.deepClone(configHolder.configForEdit);
        deepCloneForEdit.setPartials(partials);
        CruiseConfig config = updatingCommand.update(deepCloneForEdit);
        String configAsXml = configAsXml(config, false);
        if (deepCloneForEdit.getPartials().size() < partials.size())
            throw new RuntimeException("should never be called");
        return configAsXml;
    }

    private boolean shouldMergeConfig(UpdateConfigCommand updatingCommand, GoConfigHolder configHolder) {
        LOGGER.debug("[Config Save] Checking whether config should be merged");
        if (updatingCommand instanceof NoOverwriteUpdateConfigCommand) {
            NoOverwriteUpdateConfigCommand noOverwriteCommand = (NoOverwriteUpdateConfigCommand) updatingCommand;
            if (!configHolder.configForEdit.getMd5().equals(noOverwriteCommand.unmodifiedMd5())) {
                return true;
            }
        }
        return false;
    }

    private String getMergedConfig(NoOverwriteUpdateConfigCommand noOverwriteCommand, String latestMd5, List<PartialConfig> partials) throws Exception {
        LOGGER.debug("[Config Save] Getting merged config");
        String oldMd5 = noOverwriteCommand.unmodifiedMd5();
        CruiseConfig modifiedConfig = getOldConfigAndMutateWithChanges(noOverwriteCommand, oldMd5);
        modifiedConfig.setPartials(partials);
        String modifiedConfigAsXml = convertMutatedConfigToXml(modifiedConfig, latestMd5);

        GoConfigRevision configRevision = new GoConfigRevision(modifiedConfigAsXml, "temporary-md5-for-branch", getConfigUpdatingUser(noOverwriteCommand).getUserName(),
                serverVersion.version(), timeProvider);

        String mergedConfigXml = configRepository.getConfigMergedWithLatestRevision(configRevision, oldMd5);
        LOGGER.debug("[Config Save] -=- Done converting merged config to XML");
        return mergedConfigXml;
    }

    private String convertMutatedConfigToXml(CruiseConfig modifiedConfig, String latestMd5) throws Exception {
        try {
            return configAsXml(modifiedConfig, false);
        } catch (Exception e) {
            LOGGER.info(format("[CONFIG_MERGE] Pre merge validation failed, latest-md5: %s", latestMd5));
            throw new ConfigMergePreValidationException(e.getMessage(), e);
        }
    }

    private CruiseConfig getOldConfigAndMutateWithChanges(NoOverwriteUpdateConfigCommand noOverwriteCommand, String oldMd5) throws Exception {
        LOGGER.debug("[Config Save] --- Mutating old config");
        String configXmlAtOldMd5 = configRepository.getRevision(oldMd5).getContent();
        CruiseConfig cruiseConfigAtOldMd5 = magicalGoConfigXmlLoader.fromXmlPartial(configXmlAtOldMd5, BasicCruiseConfig.class);
        CruiseConfig config = noOverwriteCommand.update(cruiseConfigAtOldMd5);
        LOGGER.debug("[Config Save] --- Done mutating old config");
        return config;
    }

    private GoConfigHolder internalLoad(final String content, final ConfigModifyingUser configModifyingUser, final List<PartialConfig> partials) throws Exception {
        GoConfigHolder configHolder = magicalGoConfigXmlLoader.loadConfigHolder(content, new MagicalGoConfigXmlLoader.Callback() {
            @Override
            public void call(CruiseConfig cruiseConfig) {
                cruiseConfig.setPartials(partials);
            }
        });
        CruiseConfig config = configHolder.config;
        checkinConfigToGitRepo(partials, config, content, configHolder.configForEdit.getMd5(), configModifyingUser.getUserName());
        return configHolder;
    }

    private void checkinConfigToGitRepo(List<PartialConfig> partials, CruiseConfig config, String configAsXml, String md5, String currentUser) throws Exception {
        reloadStrategy.latestState(config);
        configRepository.checkin(new GoConfigRevision(configAsXml, md5, currentUser, serverVersion.version(), timeProvider));
        cachedGoPartials.markAsValid(partials);
    }

    public String configAsXml(CruiseConfig config, boolean skipPreprocessingAndValidation) throws Exception {
        LOGGER.debug("[Config Save] === Converting config to XML");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        magicalGoConfigXmlWriter.write(config, outputStream, skipPreprocessingAndValidation);
        LOGGER.debug("[Config Save] === Done converting config to XML");
        return outputStream.toString();
    }

    public void upgradeIfNecessary() {
        GoConfigMigrationResult migrationResult = this.upgrader.upgradeIfNecessary(fileLocation(), serverVersion.version());

        if (migrationResult.isUpgradeFailure()) {
            String message = migrationResult.message();
            serverHealthService.update(ServerHealthState.warning("Invalid Configuration", message, HealthStateType.general(HealthStateScope.forInvalidConfig())));
            LOGGER.warn(message);
        }
    }

    public String getFileLocation() {
        return fileLocation().getAbsolutePath();
    }

    static class GoConfigSaveResult {
        private final GoConfigHolder configHolder;
        private final ConfigSaveState configSaveState;

        GoConfigSaveResult(GoConfigHolder holder, ConfigSaveState configSaveState) {
            configHolder = holder;
            this.configSaveState = configSaveState;
        }

        public GoConfigHolder getConfigHolder() {
            return configHolder;
        }

        public ConfigSaveState getConfigSaveState() {
            return configSaveState;
        }
    }

    private interface ReloadStrategy {
        class ReloadTestResult {
            final boolean requiresReload;
            final long fileSize;
            final long modifiedTime;

            public ReloadTestResult(boolean requiresReload, long fileSize, long modifiedTime) {
                this.requiresReload = requiresReload;
                this.fileSize = fileSize;
                this.modifiedTime = modifiedTime;
            }
        }

        ReloadTestResult requiresReload(File configFile);

        void latestState(CruiseConfig config);

        void hasLatest(ReloadTestResult reloadTestResult);

        void performingReload(ReloadTestResult reloadTestResult);
    }

    private static class AlwaysReload implements ReloadStrategy {
        public ReloadTestResult requiresReload(File configFile) {
            return new ReloadTestResult(true, 0, 0);
        }

        public void latestState(CruiseConfig config) {
        }

        public void hasLatest(ReloadTestResult result) {
        }

        public void performingReload(ReloadTestResult result) {
        }
    }

    static class ReloadIfModified implements ReloadStrategy {
        private long lastModified;
        private long prevSize;
        private volatile String md5 = "";

        private long length(File configFile) {
            return configFile.length();
        }

        private long lastModified(File configFile) {
            return configFile.lastModified();
        }

        private boolean requiresReload(File configFile, long currentLastModified, long currentSize) {
            return doFileAttributesDiffer(currentLastModified, currentSize) && doesFileContentDiffer(configFile);
        }

        boolean doesFileContentDiffer(File configFile) {
            return !md5.equals(getConfigFileMd5(configFile));
        }

        boolean doFileAttributesDiffer(long currentLastModified, long currentSize) {
            return currentLastModified != lastModified ||
                    prevSize != currentSize;
        }

        public ReloadTestResult requiresReload(File configFile) {
            long lastModified = lastModified(configFile);
            long length = length(configFile);
            boolean requiresReload = requiresReload(configFile, lastModified, length);
            return new ReloadTestResult(requiresReload, length, lastModified);
        }

        private String getConfigFileMd5(File configFile) {
            String newMd5;
            try (FileInputStream inputStream = new FileInputStream(configFile)) {
                newMd5 = CachedDigestUtils.md5Hex(inputStream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return newMd5;
        }

        public void latestState(CruiseConfig config) {
            md5 = config.getMd5();
        }

        public void hasLatest(ReloadTestResult result) {
            rememberLatestFileAttributes(result);
        }

        private void rememberLatestFileAttributes(ReloadTestResult result) {
            synchronized (this) {
                lastModified = result.modifiedTime;
                prevSize = result.fileSize;
            }
        }

        public void performingReload(ReloadTestResult result) {
            rememberLatestFileAttributes(result);
        }
    }

}


text:
from __future__ import unicode_literals, absolute_import

class QueryString(dict):

    def __init__(self, query, fields=None, default_field=None, tie_breaker=None, use_dis_max=None):
        super(QueryString, self).__init__()
        self.query = query
        self.fields = fields
        self.default_field = default_field
        self.tie_breaker = tie_breaker
        self.use_dis_max = use_dis_max
        self["query_string"] = self._build_dict()

    def _build_dict(self):
        query_string = {"query": self.query}
        if self.fields is not None:
            query_string["fields"] = self.fields
        elif self.default_field is not None:
            query_string["default_field"] = self.default_field
        if self.use_dis_max is not None:
            query_string["use_dis_max"] = self.use_dis_max
        if self.tie_breaker is not None:
            query_string["tie_breaker"] = self.tie_breaker
        return query_string


text:
@interface NSObject (PerformBlockAfterDelay)

//################################################################################
- (void)performBlock:(void (^)(NSObject * blockOwner))block afterDelay:(NSTimeInterval)delayInSeconds;

//################################################################################
@end
//################################################################################


text:
///<reference path='../references.ts' />

module Shumway.AVM1.Lib {
  import flash = Shumway.AVMX.AS.flash;

  export class AVM1ExternalInterface extends AVM1Object {
    static createAVM1Class(context: AVM1Context): AVM1Object {
      return wrapAVM1NativeClass(context, true, AVM1ExternalInterface,
        ['available#', 'addCallback', 'call'],
        []);
    }

    public static getAvailable(context: AVM1Context): boolean {
      return context.sec.flash.external.ExternalInterface.axClass.available;
    }

    public static addCallback(context: AVM1Context, methodName: string, instance: any, method: AVM1Function): boolean {
      methodName = alCoerceString(context, methodName);
      if (!alIsFunction(method)) {
        return false;
      }
      try {
        context.sec.flash.external.ExternalInterface.axClass.addCallback(methodName, function () {
          var args = Array.prototype.slice.call(arguments, 0);
          var result = context.executeFunction(method, instance, args);
          return result;
        });
        return true;
      } catch (e) {
      }
      return false;
    }

    public static call(context: AVM1Context, methodName: string, ...parameters: any[]): any {
      var args = [alCoerceString(context, methodName)];
      for (var i = 0; i < parameters.length; i++) {
        // TODO convert AVM1 objects to AVM2
        args.push(parameters[i]);
      }
      try {
        var result = context.sec.flash.external.ExternalInterface.axClass.call.apply(
          context.sec.flash.external.ExternalInterface.axClass, args);
        // TODO convert AVM2 result to AVM1
        return result;
      } catch (e) {
        return undefined;
      }
    }
  }
}


text:
"use strict";

var Admin = require('mongodb/lib/admin');
var makeSkinClass = require('./utils').makeSkinClass;

var SkinAdmin = exports.SkinAdmin = makeSkinClass(Admin, false, true);

SkinAdmin.prototype._open = function(callback) {
  var skindb = this._construct_args[0];
  skindb.open(function(err, p_db) {
      if(err) return callback(err);
      callback(null, p_db.admin());
  });
};


text:
from pydojo import *

# create game display
screen(1280, 720)

# CREATE ACTOR
pyco = Actor('example_asset/characters/pyco1.png')

# score variable
presi = 0

# CREATE SCORE TEXT
punti = Text(presi, color=RED)
punti.goto(100, 100)

# counter variable
inizioconta = ticks()

# MAIN LOOP
while True:

    # MOVE RANDOM
    if ticks() - inizioconta > 1000:
        pyco.gorand()
        inizioconta = ticks()

    # ADD 1 POINT when target actor is clicked
    if pyco.click():
        presi = presi + 1
        punti.write(presi)

    if pyco.rightclick():
        print("You must left-click Pyco!")

    # update screen and events queue
    update()


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.netcetera.trema</groupId>
  <artifactId>trema-maven-plugin</artifactId>
  <version>0.4.1-SNAPSHOT</version>
  <packaging>maven-plugin</packaging>
  <name>${project.artifactId}</name>
  <description>Trema - Text resource management</description>
  <url>https://github.com/netceteragroup/trema-maven</url>
  <inceptionYear>2014</inceptionYear>

  <prerequisites>
    <maven>3.0.0</maven>
  </prerequisites>

  <organization>
    <name>Netcetera</name>
    <url>https://www.netcetera.com</url>
  </organization>

  <licenses>
    <license>
      <name>MIT License</name>
      <url>https://opensource.org/licenses/mit-license.php</url>
    </license>
  </licenses>

  <developers>
    <developer>
      <id>jstadler</id>
      <name>Jacques Stadler</name>
      <email>firstname dot lastname at netcetera.com</email>
    </developer>
    <developer>
      <id>mstoer</id>
      <name>Marcel Stör</name>
      <email>firstname dot lastname at netcetera.com</email>
    </developer>
  </developers>

  <scm>
    <url>${project.url}</url>
    <connection>scm:git:git@github.com:netceteragroup/trema-maven.git</connection>
    <developerConnection>scm:git:git@github.com:netceteragroup/trema-maven.git</developerConnection>
    <tag>HEAD</tag>
  </scm>

  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <name>Maven Central Snapshot Repository</name>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <name>Maven Central Staging Repository</name>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
    <site>
      <id>gh-pages</id>
      <url>${project.scm.developerConnection}</url>
    </site>
  </distributionManagement>

  <properties>
    <!-- How to detect if you're running the latest version of the configured dependencies:
         mvn -N versions:display-property-updates OR
         mvn -N versions:display-plugin-updates
    -->

    <jdk.version>1.8</jdk.version>
    <maven.version>3.0.5</maven.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <!-- Dependencies -->
    <trema-core.version>0.4.0</trema-core.version>
    <hamcrest.version>2.2</hamcrest.version>
    <junit.version>5.8.2</junit.version>
    <mockito.version>4.1.0</mockito.version>
    <maven-plugin-api.version>3.8.4</maven-plugin-api.version>
    <plexus-build-api.version>0.0.7</plexus-build-api.version>

    <!-- Plugins -->
    <coveralls-maven-plugin.version>4.3.0</coveralls-maven-plugin.version>
    <jacoco-maven-plugin.version>0.8.7</jacoco-maven-plugin.version>
    <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
    <maven-gpg-plugin.version>3.0.1</maven-gpg-plugin.version>
    <maven-javadoc-plugin.version>3.3.1</maven-javadoc-plugin.version>
    <maven-plugin-plugin.version>3.6.2</maven-plugin-plugin.version>
    <maven-project-info-reports-plugin.version>3.1.2</maven-project-info-reports-plugin.version>
    <maven-release-plugin.version>2.5.3</maven-release-plugin.version>
    <maven-resources-plugin.version>2.6</maven-resources-plugin.version>
    <maven-scm-publish-plugin.version>3.1.0</maven-scm-publish-plugin.version>
    <maven-site-plugin.version>3.9.1</maven-site-plugin.version>
    <maven-source-plugin.version>3.2.1</maven-source-plugin.version>
    <maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.netcetera.trema</groupId>
      <artifactId>trema-core</artifactId>
      <version>${trema-core.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>${maven-plugin-api.version}</version>
    </dependency>
    <dependency>
      <groupId>org.sonatype.plexus</groupId>
      <artifactId>plexus-build-api</artifactId>
      <version>${plexus-build-api.version}</version>
    </dependency>

    <!-- Test Dependencies -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>${mockito.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest</artifactId>
      <version>${hamcrest.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eluder.coveralls</groupId>
        <artifactId>coveralls-maven-plugin</artifactId>
        <version>${coveralls-maven-plugin.version}</version>
        <!--The Coveralls API token is made available as 'repoToken' env variable by Travis CI (see .travis.yml for secure -->
        <!--env). If it weren't you could define it here and reference some property from your settings.xml. -->
        <!--<configuration> -->
        <!--<repoToken>${coveralls.trema-core.token}</repoToken> -->
        <!--</configuration> -->
      </plugin>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco-maven-plugin.version}</version>
        <configuration>
          <!--<excludes /> -->
        </configuration>
        <executions>
          <execution>
            <id>prepare-agent</id>
            <goals>
              <goal>prepare-agent</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven-compiler-plugin.version}</version>
        <configuration>
          <source>${jdk.version}</source>
          <target>${jdk.version}</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven-surefire-plugin.version}</version>
        <configuration>
          <runOrder>random</runOrder>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <version>${maven-release-plugin.version}</version>
        <configuration>
          <autoVersionSubmodules>true</autoVersionSubmodules>
          <useReleaseProfile>false</useReleaseProfile>
          <!-- references the profile defined just below -->
          <releaseProfiles>release</releaseProfiles>
          <goals>deploy</goals>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>${maven-site-plugin.version}</version>
        <configuration>
          <!-- We are deploying site using scm-publish, not site-deploy... -->
          <skipDeploy>true</skipDeploy>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-plugin-plugin</artifactId>
        <version>${maven-plugin-plugin.version}</version>
        <configuration>
          <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
        </configuration>
        <executions>
          <execution>
            <id>mojo-descriptor</id>
            <goals>
              <goal>descriptor</goal>
            </goals>
          </execution>
          <execution>
            <id>generated-helpmojo</id>
            <goals>
              <goal>helpmojo</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <artifactId>maven-scm-publish-plugin</artifactId>
        <version>${maven-scm-publish-plugin.version}</version>
        <configuration>
          <scmBranch>gh-pages</scmBranch>
          <pubScmUrl>${project.scm.developerConnection}</pubScmUrl>
          <content>${project.reporting.outputDirectory}</content>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>publish-scm</goal>
            </goals>
            <phase>site-deploy</phase>
          </execution>
        </executions>
      </plugin>
    </plugins>

    <pluginManagement>
      <plugins>
        <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
        <plugin>
          <groupId>org.eclipse.m2e</groupId>
          <artifactId>lifecycle-mapping</artifactId>
          <version>1.0.0</version>
          <configuration>
            <lifecycleMappingMetadata>
              <pluginExecutions>
                <pluginExecution>
                  <pluginExecutionFilter>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-plugin-plugin</artifactId>
                    <versionRange>[3.3,)</versionRange>
                    <goals>
                      <goal>descriptor</goal>
                      <goal>helpmojo</goal>
                    </goals>
                  </pluginExecutionFilter>
                  <action>
                    <ignore />
                  </action>
                </pluginExecution>
              </pluginExecutions>
            </lifecycleMappingMetadata>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <version>${maven-project-info-reports-plugin.version}</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-plugin-plugin</artifactId>
        <reportSets>
          <reportSet>
            <reports>
              <report>report</report>
            </reports>
          </reportSet>
        </reportSets>
      </plugin>
    </plugins>
  </reporting>

  <profiles>
    <!-- all plugins below are usually only required for release builds -->
    <profile>
      <id>release</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <version>${maven-source-plugin.version}</version>
            <executions>
              <execution>
                <id>attach-sources</id>
                <goals>
                  <goal>jar-no-fork</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>${maven-javadoc-plugin.version}</version>
            <executions>
              <execution>
                <id>attach-javadocs</id>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>${maven-gpg-plugin.version}</version>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>java8</id>
      <activation>
        <jdk>1.8</jdk>
      </activation>
      <properties>
        <!--Turn of the silly Java 8 Javadoc linter because it complains about unknown annotations when it encounters Mojo JavaDoc Tags such as '@phase'.-->
        <additionalparam>-Xdoclint:none</additionalparam>
      </properties>
    </profile>
  </profiles>
</project>


text:
<?php

namespace Google\AdsApi\Dfp\v201702;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class UnarchiveProposals extends \Google\AdsApi\Dfp\v201702\ProposalAction
{

    public function __construct()
    {

    }

}


text:
require 'spec_helper'

RSpec.describe PrometheusAlertEvent do
  subject { build(:prometheus_alert_event) }

  let(:alert) { subject.prometheus_alert }

  describe 'associations' do
    it { is_expected.to belong_to(:prometheus_alert).required }
  end

  describe 'validations' do
    it { is_expected.to be_valid }

    it { is_expected.to validate_presence_of(:prometheus_alert).with_message(:required) }
    it { is_expected.to validate_uniqueness_of(:payload_key).scoped_to(:prometheus_alert_id) }
    it { is_expected.to validate_presence_of(:started_at) }

    describe 'payload_key & ended_at' do
      context 'absent if firing?' do
        subject { build(:prometheus_alert_event) }

        it { is_expected.to validate_presence_of(:payload_key) }
        it { is_expected.not_to validate_presence_of(:ended_at) }
      end

      context 'present if resolved?' do
        subject { build(:prometheus_alert_event, :resolved) }

        it { is_expected.not_to validate_presence_of(:payload_key) }
        it { is_expected.to validate_presence_of(:ended_at) }
      end
    end
  end

  describe '#title' do
    it 'delegates to alert' do
      expect(subject.title).to eq(alert.title)
    end
  end

  describe 'prometheus_metric_id' do
    it 'delegates to alert' do
      expect(subject.prometheus_metric_id).to eq(alert.prometheus_metric_id)
    end
  end

  describe 'transaction' do
    describe 'fire' do
      let(:started_at) { Time.current }

      context 'when status is none' do
        subject { build(:prometheus_alert_event, :none) }

        it 'fires an event' do
          result = subject.fire(started_at)

          expect(result).to eq(true)
          expect(subject).to be_firing
          expect(subject.started_at).to be_like_time(started_at)
        end
      end

      context 'when firing' do
        subject { build(:prometheus_alert_event) }

        it 'cannot fire again' do
          result = subject.fire(started_at)

          expect(result).to eq(false)
        end
      end
    end

    describe 'resolve' do
      let(:ended_at) { Time.current }

      context 'when firing' do
        subject { build(:prometheus_alert_event) }

        it 'resolves an event' do
          result = subject.resolve!(ended_at)

          expect(result).to eq(true)
          expect(subject).to be_resolved
          expect(subject.ended_at).to be_like_time(ended_at)
        end
      end

      context 'when resolved' do
        subject { build(:prometheus_alert_event, :resolved) }

        it 'cannot resolve again' do
          result = subject.resolve(ended_at)

          expect(result).to eq(false)
        end
      end
    end
  end
end


text:
package com.example.android.spotifystreamer.ui;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;

/**
 * Created by jc on 6/30/15.
 */
public class ArtistSearchTextWatcher implements TextWatcher {

    private EditText mArtistSearchBox;

    private static final String TAG =ArtistSearchTextWatcher.class.getSimpleName();
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String text = mArtistSearchBox.getText().toString().trim();
        if (text.length()> 2){
            Log.d(TAG, text);
            FetchArtistsTask artistsTask = new FetchArtistsTask();
            artistsTask.execute(text);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
/**
 * Pipes
 */
import { GenderPipe } from './pipes/gender.pipe';
/**
 * Directives
 */
import { InfiniteScrollDirective } from './directives/infinite-scroll.directive';
import { DisableButtonDirective } from './directives/disable-button.directive';

@NgModule({
	imports: [CommonModule],
	declarations: [GenderPipe, InfiniteScrollDirective, DisableButtonDirective],
	exports: [GenderPipe, InfiniteScrollDirective, DisableButtonDirective, CommonModule, FormsModule]
})
export class SharedModule { }


text:
'use strict'

const path = require('path')
const Enzyme = require('enzyme')
const EnzymeAdapter = require('enzyme-adapter-react-16')

require('@babel/register')({
  configFile: path.join(__dirname, '../babel.config.js'),
  plugins: ['@babel/plugin-transform-modules-commonjs'],
  extensions: ['.ts', '.d.ts', '.tsx'],
  sourceMaps: 'inline',
})

Enzyme.configure({adapter: new EnzymeAdapter()})

const chai = require('chai')
const sinonChai = require('sinon-chai')
const chaiAsPromised = require('chai-as-promised')

chai.use(sinonChai)
chai.use(chaiAsPromised)


text:
FROM centos/systemd:latest
RUN yum install -y epel-release
RUN yum install -y python-devel python-pip openssl-devel libffi-devel gcc
RUN pip install --upgrade pip setuptools
RUN pip install ansible testinfra
ADD "inventory.conf" "/etc/ansible/hosts"


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
    <name>ChangeFilter</name>
    <message>
        <location filename="changefilter.cpp" line="+51"/>
        <source>Extra Filter: %1</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+20"/>
        <source>Filter: %1</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>DatabaseController</name>
    <message>
        <location filename="databasecontroller.cpp" line="+53"/>
        <source>Failed to load last database file!</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+192"/>
        <source>Failed to reload changed package database</source>
        <oldsource>Failed to reload changed file</oldsource>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+89"/>
        <source>Failed to save package database!</source>
        <oldsource>Failed to save file!</oldsource>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>DatabaseMerger</name>
    <message>
        <location filename="databasemerger.cpp" line="+36"/>
        <source>Conflict on install state of package %1. Has been set to "install"</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+9"/>
        <source>Conflict on reason for unclear package %1 - kept info of current database</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+6"/>
        <source>Conflict on global filter mode - kept state of current database</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+10"/>
        <source>%1-%2</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+3"/>
        <source>Conflict on filter %1 - renamed new filter to %2</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+12"/>
        <source>Conflict on extra filter %1 - kept state of current database</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location line="+5"/>
        <source>Unable to merge settings - kept state of current database</source>
        <oldsource>Unable to merger settings - kept state of current database</oldsource>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>OperationQueue</name>
    <message>
        <location filename="operationqueue.cpp" line="+79"/>
        <source>Failed to reload database!</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
Code for creation and simple navigation of n-order markov chains for use on words of text.

The resulting graph/chain object can be (de)serialized using either a standard sqlite database or a more space efficient raw format.

It's geared up for storing and using the resulting chain/graph on fairly resource constrained devices like mobiles. However, the *compilation* of the chain/graph isn't quite so optimised, so that's more suitable for laptops/desktops when the original source text is large.

## Contents and dependencies:

* `graphs/src/main/java` - The main code tree for the graph model objects. All code in this tree has no mandatory dependencies.
* `compiler/src/main/java` - The main code tree for the graph compiler. This source tree has some dependencies, as detailed below.
* `src/test/java` - JUnit 4 tests

### Some useful starting points..

* `compiler/src/main/java/org/abatons/markov/compiler/GraphCompiler.java` - This contains a main method that takes text file's filenames as arguments. It'll generate the first 5 order graphs, run a little test parody using each, then save each graph in both a raw format and as a sqlite database.
* `graphs/src/main/java/org/abatons/markov/graph` - This package, and subpackages, contain all the classes for representing, navigating, (de)serializing graphs, and for running a parody.

### Dependencies:

There need be no dependencies if you just want to read and navigate raw graph objects.

For reading/compiling graph objects from/to sqlite, you'll need a sqlite JDBC driver.
For compiling either raw or sqlite based graph objects, you'll need the commons-io library.

* `commons-io-2.4.jar` - used during graph compilation for just a single utility method to read lines of the source text into an array. Can be easily removed.
* `sqlite-jdbc-3.7.2.jar` - Sqlite JDBC driver, if using sqlite for persistence.
* junit 4 - For the unit tests

## Limitations:

* The main one that springs to mind is that only 65536 unique words can be captured in the source text (where different capitalisations of the same word are considered different words). Mind you, running this code over the complete works of Shakespeare from Project Gutenburg only required about 54664 unique words to capture the complete graph.
* It currently only works on words, but this could be tweaked at a future date.
* Some abbreviations using periods, such as abbrv., may be considered as the end of a sentence. There's a list of some abbreviations in `org.abatons.markov.compiler.SentenceReader` that can easily be added to.

## Build:

Easy way is to use Maven if you have it installed already. Just run the command `mvn clean package --projects compiler assembly:single` at the top project level.

This will create one library jar in `graphs/target/` that contains classes for reading and navigating the graph objects. It is free from any dependencies.

Two jars will be created under the `compiler/target` directory, which both contain the classes for compiling the graph objects. One jar is without the dependencies and the other bundles all dependencies in it for running the compiler and using sqlite without any hassle.

## Usage examples

### Usage example: For compiling

`java -jar compiler/MarkovChains-compiler-1.0-SNAPSHOT-jar-with-dependencies.jar jabberwocky.txt`
That'll generate order 1 through 4 graphs for the text in the `jabberwocky.txt` file and create both `.raw` and `.sqlite.db` files representing the same Graph object.

### Usage example: For reading and navigating compiled graphs

Use the `GraphPersistenceRaw` or `GraphPersistenceSqlite` classes to load and instantiate a Graph object. You can test the `Graph` object by using the cheap and cheerful `Parody` class.


text:
import * as e6p from 'es6-promise'
(e6p as any).polyfill()
import 'isomorphic-fetch'

import * as React                     from 'react'
import * as ReactDOMServer            from 'react-dom/server'
import { Provider                   } from 'react-redux'
import { createMemoryHistory, match } from 'react-router'
import { syncHistoryWithStore       } from 'react-router-redux'

const ReduxConnect = require('redux-connect')
const path         = require('path')
const Chalk        = require('chalk')
const express      = require('express')
const app          = express()

import routes             from '~/routes'
import { Html           } from '~/components/Html'
import { configureStore } from '~/redux/store'

const appConfig = require('../config/main')
const manifest  = require('../build/manifest.json')

const renderPage = (renderProps: any, store: any, res: any) => {
  const asyncRenderData = Object.assign({}, renderProps, { store })

  ReduxConnect.loadOnServer(asyncRenderData).then(() => {
    const markup = ReactDOMServer.renderToString(
      <Provider store={store} key='provider'>
        <ReduxConnect.ReduxAsyncConnect {...renderProps} />
      </Provider>
    )
    const html = ReactDOMServer.renderToString(
      <Html markup={markup} manifest={manifest} store={store} />
    )
    res.status(200).send(`<!doctype html> ${html}`)
  })
}

const devSetup = () => {
  const webpackConfig   = require('../config/webpack/partials/client-dev')
  const webpackCompiler = require('webpack')(webpackConfig)

  app.use(require('webpack-dev-middleware')(webpackCompiler, {
    publicPath:         webpackConfig.output.publicPath,
    stats:              { colors: true },
    noInfo:             true,
    hot:                true,
    inline:             true,
    lazy:               false,
    historyApiFallback: true,
    quiet:              true,
  }))

  app.use(require('webpack-hot-middleware')(webpackCompiler))
}

const router = (req: any, res: any) => {
  const location      = req.url
  const memoryHistory = createMemoryHistory(req.originalUrl)
  const store         = configureStore(memoryHistory)
  const history       = syncHistoryWithStore(memoryHistory, store)

  match({ history, routes, location }, (error, redirectLocation, renderProps) => {
    if (error) {
      res.status(500).send(error.message)
      return
    }

    if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search)
      return
    }

    if (renderProps) {
      renderPage(renderProps, store, res)
      return
    }

    res.status(404).send('Not Found?')
  })
}

if (process.env.NODE_ENV !== 'production') {
  devSetup()
}
app.use(require('compression')())
app.use(require('serve-favicon')(path.join(__dirname, '../src/assets/favicon.ico')))
app.use('/public', express.static(path.join(__dirname, '../build/public')))
app.get('*', router)
app.listen(appConfig.port, appConfig.host, (error: string) => {
  if (error) {
    console.error(Chalk.bgRed(error))
    return
  }
  console.info(Chalk.black.bgGreen(`\n\nListening at http://${appConfig.host}:${appConfig.port}\n`))
})


text:
const ProductStatus = require('../models/ProductStatus')
const map = {
  aktiv: ProductStatus.ACTIVE,
  utsolgt: ProductStatus.OUT_OF_STOCK,
  utgatt: ProductStatus.EXPIRED
}

module.exports = function statusFilter(val) {
  return map[val]
}


text:
package at.dotpoint.gradle.cross.variant.target;

import at.dotpoint.gradle.cross.variant.model.IVariant;

/**
 * Created by RK on 08.07.2016.
 */
public interface IVariationsTarget
{
	/**
	 * IFlavor, IPlatform, IBuildType
	 */
	VariantCombination<IVariant> getTargetVariantCombination();
}


text:
import { Router, Express } from 'express'
import Crowi from 'server/crowi'

import Admin from './admin'
import Attachment from './attachment'
import Bookmark from './bookmark'
import Comment from './comment'
import Like from './like'
import Notification from './notification'
import Page from './page'
import Revision from './revision'
import Share from './share'
import Version from './version'

const router = Router()

export default (crowi: Crowi, app: Express, form) => {
  const routes = {
    Admin: Admin(crowi, app, form),
    Attachment: Attachment(crowi, app, form),
    Bookmark: Bookmark(crowi, app, form),
    Comment: Comment(crowi, app, form),
    Like: Like(crowi, app, form),
    Notification: Notification(crowi, app, form),
    Page: Page(crowi, app, form),
    Revision: Revision(crowi, app, form),
    Share: Share(crowi, app, form),
    Version: Version(crowi, app, form),
  }

  for (const route of Object.values(routes)) {
    router.use(route)
  }

  return router
}


text:
package com.sourcegraph.javagraph;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;

/**
 * This class generates Sourcefile for Android Support framework because it needs special treatment, such as
 * - there is no need to run scanners, everything is included into Srcfile's units
 * - source unit should contain special markers indicating that we are working with Android Support framework project
 * Usage: AndroidSupportSrcFileGenerator [DIRECTORY]
 * Expected scenario
 * - clone Android source code
 * - build Android source code
 * - generate Sourcefile for Support framework
 * - run `srclib make`
 */
public class AndroidSupportSrcFileGenerator {

    public static void main(String[] args) throws IOException {

        if (args.length > 0) {
            PathUtil.CWD = Paths.get(args[0]);
        }

        JSONUtil.writeJSON(getSrcfile());
    }

    /**
     * Generates Srcfile for Android libcore
     * @return generated Srcfile
     * @throws IOException
     */
    private static Srcfile getSrcfile() throws IOException {
        Collection<SourceUnit> units = new LinkedList<>();

        units.add(AndroidSupportProject.createSourceUnit());

        Srcfile srcfile = new Srcfile();
        srcfile.SourceUnits = units;
        srcfile.Scanners = Collections.emptyList();
        return srcfile;
    }
}


text:
Given(/^the following funding sources exist:$/) do |fss|
  pending
end


text:
package com.smartling.connector.hubspot.sdk.email;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CloneEmailRequest
{
    private String name;
}


text:
from abc import ABCMeta, abstractmethod

class DefaultExperimentProvider:
    """
    Abstract base class for objects that provide the ID of an MLflow Experiment based on the
    current client context. For example, when the MLflow client is running in a Databricks Job,
    a provider is used to obtain the ID of the MLflow Experiment associated with the Job.

    Usually the experiment_id is set explicitly by the user, but if the experiment is not set,
    MLflow computes a default experiment id based on different contexts.
    When an experiment is created via the fluent ``mlflow.start_run`` method, MLflow iterates
    through the registered ``DefaultExperimentProvider``s until it finds one whose
    ``in_context()`` method returns ``True``; MLflow then calls the provider's
    ``get_experiment_id()`` method and uses the resulting experiment ID for Tracking operations.
    """

    __metaclass__ = ABCMeta

    @abstractmethod
    def in_context(self):
        """
        Determine if the MLflow client is running in a context where this provider can
        identify an associated MLflow Experiment ID.

        :return: ``True`` if the MLflow client is running in a context where the provider
                can identify an associated MLflow Experiment ID. ``False`` otherwise.
        """
        pass

    @abstractmethod
    def get_experiment_id(self):
        """
        Provide the MLflow Experiment ID for the current MLflow client context.
        Assumes that ``in_context()`` is ``True``.

        :return: The ID of the MLflow Experiment associated with the current context.
        """
        pass


text:
package com.microsoft.bingads.v12.api.test.entities.campaign;

import java.util.Map;

import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.internal.functionalinterfaces.Function;
import com.microsoft.bingads.internal.functionalinterfaces.Supplier;
import com.microsoft.bingads.v12.api.test.entities.BulkEntityTest;
import com.microsoft.bingads.v12.api.test.entities.EqualityComparerWithDescription;
import com.microsoft.bingads.v12.bulk.entities.BulkCampaign;
import com.microsoft.bingads.v12.campaignmanagement.Campaign;

public abstract class BulkCampaignTest extends BulkEntityTest<BulkCampaign> {

    @Override
    protected void onEntityCreation(BulkCampaign entity) {
        Campaign c = new Campaign();
        c.setId(100L);
        entity.setCampaign(c);
    }

    @Override
    protected <TProperty> void testWriteProperty(
            String header,
            String expectedRowValue,
            TProperty propertyValue,
            BiConsumer<BulkCampaign, TProperty> setFunc
    ) {
        testWriteProperty(
                header,
                expectedRowValue,
                propertyValue,
                setFunc,
                new Supplier<BulkCampaign>() {
                    @Override
                    public BulkCampaign get() {
                        return new BulkCampaign();
                    }
                }
        );
    }

    @Override
    protected <TProperty> void testReadProperty(
            String header,
            String input,
            TProperty expectedResult,
            Function<BulkCampaign, TProperty> actualValueFunc
    ) {
        testReadProperty(
                header,
                input,
                expectedResult,
                actualValueFunc,
                new Supplier<BulkCampaign>() {
                    @Override
                    public BulkCampaign get() {
                        return new BulkCampaign();
                    }
                }
        );
    }

    @Override
    protected <TProperty> void testReadProperty(
            Map<String, String> rowValues,
            TProperty expectedResult,
            Function<BulkCampaign, TProperty> actualValueFunc
    ) {
        testReadProperty(
                rowValues,
                expectedResult,
                actualValueFunc,
                new Supplier<BulkCampaign>() {
                    @Override
                    public BulkCampaign get() {
                        return new BulkCampaign();
                    }
                }
        );
    }

    protected <TProperty> void testReadProperty(
            String header,
            String input,
            TProperty expectedResult,
            Function<BulkCampaign, TProperty> actualValueFunc,
            EqualityComparerWithDescription<TProperty> comparer
    ) {
        testReadProperty(
                header,
                input,
                expectedResult,
                actualValueFunc,
                new Supplier<BulkCampaign>() {
                    @Override
                    public BulkCampaign get() {
                        return new BulkCampaign();
                    }
                },
                comparer
        );
    }

    protected <TProperty> void testReadProperty(
            Map<String, String> rowValues,
            TProperty expectedResult,
            Function<BulkCampaign, TProperty> actualValueFunc,
            EqualityComparerWithDescription<TProperty> comparer
    ) {
        testReadProperty(
                rowValues,
                expectedResult,
                actualValueFunc,
                new Supplier<BulkCampaign>() {
                    @Override
                    public BulkCampaign get() {
                        return new BulkCampaign();
                    }
                },
                comparer
        );
    }
}


text:
module ComfortableMexicanSofa::AccessControl
  module AdminAuthorization
    # By default there's no authorization of any kind
    def authorize
      true
    end
  end
end


text:
module Admin::StockInHelper
end


text: export { InProgressError24 as default } from "../../";


text:
{-# LANGUAGE DeriveGeneric #-}

module Minibas.Types (
    VOGame(..), voGameProperty, voGameScore
) where

import ClassyPrelude.Yesod
import Control.Lens (makeLenses)
import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier)
import Jabara.Util (omittedFirstCharLower)
import Jabara.Yesod.Util (tc, ttc)
import Model (Score, Game)

data VOGame = VOGame {
    _voGameProperty :: Entity Game
  , _voGameLeagueName :: Text
  , _voGameScore    :: [Entity Score]
} deriving (Show, Eq, Read, Generic)
makeLenses ''VOGame
$(deriveJSON defaultOptions {
    fieldLabelModifier = omittedFirstCharLower "_voGame"
} ''VOGame)

instance ToContent VOGame where toContent = tc
instance ToTypedContent VOGame where toTypedContent = ttc

instance ToContent [VOGame] where toContent = tc
instance ToTypedContent [VOGame] where toTypedContent = ttc