text:
#include "Token.h"

#include "../OperatorDescriptor.h"
#include "../OperatorDescriptorList.h"

namespace Interaction {

QStringList Token::specialSignatureWords_ = {"SPACE", "EXPR", "ID"};

Token::Token()
{
}

Token::Token(QString text, Type type)
	: text_{text}, type_{type}
{}

QVector<Token> Token::tokenize(QString input, const OperatorDescriptorList* ops)
{
	QVector<Token> result;

	auto it = input.constBegin();
	while (it != input.constEnd())
	{
		auto oldIt = it;

		if (it->isLetter() || *it == '_') result.append(parseIdentifier(it, input.constEnd(), ops));
		else if (it->isDigit()) result.append(parseNumberLiteral(it, input.constEnd()));
		else if (*it == '"' || *it == '\'') result.append(parseStringLiteral(it, input.constEnd()));
		else result.append(parseOperator(it, input.constEnd(), ops));

		Q_ASSERT(!result.last().text().isEmpty());
		Q_ASSERT(it - oldIt == result.last().text().size());
	}

	// Remove all spaces, except for trailing ones
	//
	// TODO: Figure out a good way to implement the condition below.
	//
	// The commented part of the condition below used to prevent removing of spaces if quotes are mismatched.
	// Removing spaces with mismatched quotes might end up removing spaces inside of strings while the expression is
	// being modified. So if the condition is enabled, one could remove the leading quote of a string without bad
	// consequences for double spaces within the string.
	//
	// However, we were forced to disbale the condition in its current form since, it had a negative side effect.
	// When typing an unmatched quote, spaces would proliferate and multiply on each keystroke, since many expressions
	// automatically insert spaces after they keyword (throw, new, delete, etc.) and these would be become part of an
	// error expression since they were not removed. E.g. typing 'new f("xxxxx' would result in a bunch of spaces
	// after 'new'.
	if (!result.empty()) // && result.last().type() != PartialLiteral)
	{
		bool trailing = true;
		QRegExp space{" +"};
		for (int i = result.length() - 1; i>=0;)
		{
			if (!space.exactMatch(result[i].text()))
			{
				trailing = false;
				--i;
				continue;
			}

			// We have a space
			if (trailing) --i;
			else result.removeAt(i);
		}
	}

	return result;
}

Token Token::parseStringLiteral(QString::const_iterator& it, const QString::const_iterator end)
{
	Q_ASSERT( it != end );
	Q_ASSERT( *it== '"' || *it == '\'');

	QString text = *it;
	QChar first = *it;
	bool escaped = false;

	++it;
	while (it != end)
	{
		text.append(*it);
		if (escaped) escaped = false;
		else
		{
			if (*it == '\\') escaped = true;
			else if (*it == first)
			{
				//finalize the string
				++it;
				return Token{text, Literal};
			}
		}

		++it;
	}

	// Return a partial (unfinished) token
	return Token{text, PartialLiteral};
}

Token Token::parseNumberLiteral(QString::const_iterator& it, const QString::const_iterator end)
{
	Q_ASSERT( it != end );
	Q_ASSERT( it->isDigit() );

	QString text = *it;
	++it;

	if (it == end) return Token{text, Literal};

	// Check for bin/hex
	if (text[0] == '0' && (*it == 'x' || *it == 'X' || *it == 'b' || *it == 'B') )
	{
		text.append(*it);
		++it;
	}

	auto accumulateDigitsAndSeparators = [&it, &end, &text](){
		while (it != end && (it->isDigit() || *it == '\'' || *it == '_'))
		{
			text.append(*it);
			++it;
		}
	};

	accumulateDigitsAndSeparators();

	if (it == end) return Token{text, Literal};

	if (*it == '.')
	{
		text.append(*it);
		++it;

		accumulateDigitsAndSeparators();
	}
	else if (*it == 'e' || *it == 'E')
	{
		text.append(*it);
		++it;

		if (it == end) return Token{text, Literal};

		if (*it == '+' || *it == '-')
		{
			text.append(*it);
			++it;
		}

		accumulateDigitsAndSeparators();
	}

	if (it == end) return Token{text, Literal};

	//Accumulate type specifiers
	while (it != end && (*it == 'l' || *it == 'L' || *it == 'f' || *it == 'F'
								|| *it == 'd' || *it == 'D' || *it == 'u' || *it == 'U'))
	{
		text.append(*it);
		++it;
	}

	return Token{text, Literal};
}

Token Token::parseIdentifier(QString::const_iterator& it, const QString::const_iterator end,
									  const OperatorDescriptorList* ops)
{
	Q_ASSERT( it != end );
	Q_ASSERT( it->isLetter() || *it == '_' );

	QString text = *it;
	++it;

	while (it != end && (it->isLetterOrNumber() || *it == '_'))
	{
		text.append(*it);
		++it;
	}

	// This might look like an identifier, but it could be a reserved keyword that represents an operator (e.g. 'delete')
	return Token{text, tokenExistsInOperators(text, ops) ? OperatorDelimiter : Identifier};
}

Token Token::parseOperator(QString::const_iterator& it, const QString::const_iterator end,
									const OperatorDescriptorList* ops)
{
	Q_ASSERT( it != end );
	Q_ASSERT( !it->isLetterOrNumber() && *it != '_'  && *it != '"' && *it != '\'');

	QString text = *it;
	++it;

	// See if adding more characters will yield an operator
	// Keep in mind that in this method we are only concerned with non-textual operators ( so no 'delete' for example).
	static constexpr int LOOK_AHEAD = 8; // Not quite sure anymore, why this number is 8
	auto finalLookAheadPos = it + LOOK_AHEAD;
	QString potentialOperator = text;

	for (auto peekIterator = it; peekIterator != end && peekIterator != finalLookAheadPos; ++peekIterator)
	{
		potentialOperator += *peekIterator;
		if ( tokenExistsInOperators(potentialOperator, ops) )
		{
			text = potentialOperator;
			it = peekIterator+1;
		}
	}

	return Token{text, OperatorDelimiter};
}

bool Token::tokenExistsInOperators(QString token, const OperatorDescriptorList* ops)
{
	for (int i = 0; i < ops->size(); ++i)
		if (ops->at(i)->signature().contains(token) )
			return OperatorDescriptor::isDelimiter(token) && !specialSignatureWords_.contains(token);

	return false;
}

QVector<Token> Token::createSubExpressions(const QVector<Token>& tokens)
{
	QVector<QChar> parens = {'(', ')', '{', '}', '[', ']'};

	QMultiMap<int, QPair<QChar, QChar>> parensSorted;
	for (int i = 0; i<parens.size(); i+=2)
		parensSorted.insert(
				countUnmatched(tokens.begin(), tokens.end(), parens[i], parens[i+1]), qMakePair(parens[i], parens[i+1]));

	QVector<Token> result = tokens;
	for (auto parens : parensSorted.values())
		result = createSubExpressions(result.begin(), result.end(), parens.first, parens.second);

	return result;
}

QVector<Token> Token::createSubExpressions(QVector<Token>::const_iterator start, QVector<Token>::const_iterator end,
		QChar openParen, QChar closeParen)
{
	auto splitStart = start;
	auto splitEnd = end;

	bool foundSplit = findSplit(splitStart, splitEnd, openParen, closeParen);

	if (!foundSplit) splitStart = end;
	QVector<Token> result;

	//Add all initial tokens
	auto it = start;
	while (it != splitStart)
	{
		result.append(*it);
		if ( result.last().type_ == SubExpression )
			// Look into already created sub expressions from other types of parenthesis
			result.last().subExpressionTokens_ = createSubExpressions(result.last().subExpressionTokens_.begin(),
					result.last().subExpressionTokens_.end(), openParen, closeParen);
		++it;
	}

	if (foundSplit)
	{
		// Create sub expression
		result.append(Token{QString{}, SubExpression});
		Token& sub = result.last();
		sub.subExpressionTokens_ = createSubExpressions(splitStart, splitEnd, openParen, closeParen);
		for (auto t : sub.subExpressionTokens_) sub.text_ += t.text_;

		// Add trailing tokens
		for (auto t : createSubExpressions(splitEnd, end, openParen, closeParen))
		result.append(t);
	}

	return result;
}

int Token::countUnmatched(QVector<Token>::const_iterator start, QVector<Token>::const_iterator end,
		QChar openParen, QChar closeParen)
{
	int current = 0;
	int unmatched = 0;
	while (start != end)
	{
		if (start->type_ == OperatorDelimiter)
		{
			if (start->text_ == openParen) ++current;
			else if (start->text_ == closeParen) --current;
		}

		if (current < 0)
		{
			++unmatched;
			current = 0;
		}

		++start;
	}

	return unmatched + current;
}

/**
 * Adjusts the \a splitStart and \a splitEnd arguments to indicate the best split of the given range and returns true
 * if a split was found.
 *
 * If the return value is false the input sequence of tokens should remain as it is.
 *
 * The range is given by the initial values of \a splitStart and \a splitEnd. The returned values are such that:
 * tokens before \a splitStart should remain as they are (there is no open paren); \a splitStart points just after the
 * first open paren; \a splitEnd points at the closing paren that matches the one from \a splitStart.
 *
 * The best possible split is determined by trying to minimize the sum of the unmatched count of the tokens:
 * between \a splitStart and \a splitEnd; after \a splitEnd
 */
bool Token::findSplit(QVector<Token>::const_iterator& splitStart, QVector<Token>::const_iterator& splitEnd,
				QChar openParen, QChar closeParen)
{
	// Find open paren
	while (splitStart != splitEnd && (splitStart->type_ != OperatorDelimiter || splitStart->text_ != openParen))
		++splitStart;

	if (splitStart == splitEnd) return false;
	++splitStart; // Advance to just after the first open paren
	if (splitStart == splitEnd) return false;

	auto splitMid = splitStart;
	TokenSplitData bestSplit;

	int leftBalance = 0;
	int leftUnmatched = 0;
	bool foundSplit = false;
	do
	{
		if (splitMid->type_ == OperatorDelimiter)
		{
			if (splitMid->text_ == openParen)
			{
				++leftBalance;
			}
			else if (splitMid->text_ == closeParen)
			{
				//Try using this as a closing paren for splitStart

				--leftBalance;
				if (leftBalance < 0)
				{
					leftBalance = 0;
					++leftUnmatched;
				}

				TokenSplitData candidateSplit{splitMid, leftBalance + leftUnmatched,
					countUnmatched(splitMid, splitEnd, openParen, closeParen)};

				if (!foundSplit || candidateSplit < bestSplit) bestSplit = candidateSplit;

				foundSplit = true;
			}
		}

		++splitMid;
	} while ( splitMid != splitEnd);

	if (foundSplit) splitEnd = bestSplit.end;
	return foundSplit;
}

bool operator< (const TokenSplitData& left, const TokenSplitData& right)
{
	auto leftTotal = left.unmatchedBeforeEnd + left.unmatchedAfterEnd;
	auto rightTotal = right.unmatchedBeforeEnd + right.unmatchedAfterEnd;

	if (leftTotal < rightTotal) return true;
	if (leftTotal > rightTotal) return false;

	// Here it's possible to explore alternatives that will result in a different split
	// For example: return left.unmatchedBeforeEnd < right.unmatchedAfterEnd;
	return left.unmatchedAfterEnd < right.unmatchedAfterEnd;
}

}


text:
package cli

import (
	"fmt"

	log "github.com/sirupsen/logrus"
	"github.com/bitrise-io/stepman/stepman"
	"github.com/urfave/cli"
)

func update(c *cli.Context) error {
	collectionURIs := []string{}

	// StepSpec collection path
	collectionURI := c.String(CollectionKey)
	if collectionURI == "" {
		log.Info("No StepLib specified, update all...")
		collectionURIs = stepman.GetAllStepCollectionPath()
	} else {
		collectionURIs = []string{collectionURI}
	}

	if len(collectionURIs) == 0 {
		log.Info("No local StepLib found, nothing to update...")
	}

	for _, URI := range collectionURIs {
		log.Infof("Update StepLib (%s)...", URI)
		if _, err := stepman.UpdateLibrary(URI); err != nil {
			return fmt.Errorf("Failed to update StepLib (%s), error: %s", URI, err)
		}
	}

	return nil
}

redpajama_set_name: RedPajamaGithub


text:
require_relative 'projects_finder'

class IssuableFinder
  NONE = '0'

  attr_accessor :current_user, :params

  def initialize(current_user, params)
    @current_user = current_user
    @params = params
  end

  def execute
    items = init_collection
    items = by_scope(items)
    items = by_state(items)
    items = by_group(items)
    items = by_project(items)
    items = by_search(items)
    items = by_milestone(items)
    items = by_assignee(items)
    items = by_author(items)
    items = by_label(items)
    sort(items)
  end

  def group
    return @group if defined?(@group)

    @group =
      if params[:group_id].present?
        Group.find(params[:group_id])
      else
        nil
      end
  end

  def project
    return @project if defined?(@project)

    @project =
      if params[:project_id].present?
        Project.find(params[:project_id])
      else
        nil
      end
  end

  def search
    params[:search].presence
  end

  def milestones?
    params[:milestone_title].present?
  end

  def milestones
    return @milestones if defined?(@milestones)

    @milestones =
      if milestones? && params[:milestone_title] != Milestone::None.title
        Milestone.where(title: params[:milestone_title])
      else
        nil
      end
  end

  def assignee?
    params[:assignee_id].present?
  end

  def assignee
    return @assignee if defined?(@assignee)

    @assignee =
      if assignee? && params[:assignee_id] != NONE
        User.find(params[:assignee_id])
      else
        nil
      end
  end

  def author?
    params[:author_id].present?
  end

  def author
    return @author if defined?(@author)

    @author =
      if author? && params[:author_id] != NONE
        User.find(params[:author_id])
      else
        nil
      end
  end

  private

  def init_collection
    table_name = klass.table_name

    if project
      if Ability.abilities.allowed?(current_user, :read_project, project)
        project.send(table_name)
      else
        []
      end
    elsif current_user && params[:authorized_only].presence && !current_user_related?
      klass.of_projects(current_user.authorized_projects).references(:project)
    else
      klass.of_projects(ProjectsFinder.new.execute(current_user)).references(:project)
    end
  end

  def by_scope(items)
    case params[:scope]
    when 'created-by-me', 'authored' then
      items.where(author_id: current_user.id)
    when 'all' then
      items
    when 'assigned-to-me' then
      items.where(assignee_id: current_user.id)
    else
      raise 'You must specify default scope'
    end
  end

  def by_state(items)
    case params[:state]
    when 'closed'
      items.closed
    when 'merged'
      items.respond_to?(:merged) ? items.merged : items.closed
    when 'all'
      items
    when 'opened'
      items.opened
    else
      raise 'You must specify default state'
    end
  end

  def by_group(items)
    items = items.of_group(group) if group

    items
  end

  def by_project(items)
    items = items.of_projects(project.id) if project

    items
  end

  def by_search(items)
    items = items.search(search) if search

    items
  end

  def sort(items)
    items.sort(params[:sort])
  end

  def by_milestone(items)
    if milestones?
      items = items.where(milestone_id: milestones.try(:pluck, :id))
    end

    items
  end

  def by_assignee(items)
    if assignee?
      items = items.where(assignee_id: assignee.try(:id))
    end

    items
  end

  def by_author(items)
    if author?
      items = items.where(author_id: author.try(:id))
    end

    items
  end

  def by_label(items)
    if params[:label_name].present?
      label_names = params[:label_name].split(",")

      item_ids = LabelLink.joins(:label).
        where('labels.title in (?)', label_names).
        where(target_type: klass.name).pluck(:target_id)

      items = items.where(id: item_ids)
    end

    items
  end

  def current_user_related?
    params[:scope] == 'created-by-me' || params[:scope] == 'authored' || params[:scope] == 'assigned-to-me'
  end
end


text:
package org.apache.camel.idea.completion;

import java.util.Arrays;
import java.util.List;

import com.intellij.codeInsight.completion.CompletionType;
import org.apache.camel.idea.CamelLightCodeInsightFixtureTestCaseIT;
import org.hamcrest.Matchers;

import static org.junit.Assert.assertThat;

/**
 * Testing smart completion with Camel Java DSL
 */
public class JavaEndpointSmartCompletionValueTestIT extends CamelLightCodeInsightFixtureTestCaseIT {

    public void testEnumValue() {
        myFixture.configureByFiles("CompleteJavaEndpointValueEnumTestData.java");
        myFixture.complete(CompletionType.BASIC, 1);
        List<String> strings = myFixture.getLookupElementStrings();
        assertEquals(8, strings.size());
        assertThat(strings, Matchers.contains("file:inbox?readLock=changed", "file:inbox?readLock=fileLock", "file:inbox?readLock=idempotent",
            "file:inbox?readLock=idempotent-changed", "file:inbox?readLock=idempotent-rename", "file:inbox?readLock=markerFile",
            "file:inbox?readLock=none", "file:inbox?readLock=rename"));
    }

    public void testDefaultValue() {
        myFixture.configureByFiles("CompleteJavaEndpointValueDefaultTestData.java");
        myFixture.complete(CompletionType.BASIC, 1);
        List<String> strings = myFixture.getLookupElementStrings();
        assertEquals(1, strings.size());
        assertThat(strings, Matchers.contains("file:inbox?delay=500"));
    }

    public void testBooleanValue() {
        myFixture.configureByFiles("CompleteJavaEndpointValueBooleanTestData.java");
        myFixture.complete(CompletionType.BASIC, 1);
        List<String> strings = myFixture.getLookupElementStrings();
        assertEquals(2, strings.size());
        assertThat(strings, Matchers.contains("file:inbox?delay=1000&recursive=false", "file:inbox?delay=1000&recursive=true"));
    }

    private String getJavaInTheMiddleUnresolvedValueTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10&fixedRate=<caret>\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }
    public void testInTheMiddleUnresolvedValuesCompletion() {
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaInTheMiddleUnresolvedValueTestData());
        myFixture.complete(CompletionType.BASIC, 1);
        List<String> strings = myFixture.getLookupElementStrings();
        assertFalse(strings.containsAll(Arrays.asList("timer:trigger?repeatCount=10")));
        assertThat(strings, Matchers.contains("timer:trigger?repeatCount=10&fixedRate=false", "timer:trigger?repeatCount=10&fixedRate=true"));
        assertEquals(2, strings.size());
    }

    private String getJavaUnresolvedValueWithPreTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?exchangePattern=In<caret>&repeatCount=10\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }
    public void testUnresolvedValueWithPreTestCompletion() {
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaUnresolvedValueWithPreTestData());
        myFixture.complete(CompletionType.BASIC, 1);
        List<String> strings = myFixture.getLookupElementStrings();
        assertFalse(strings.containsAll(Arrays.asList("timer:trigger?repeatCount=10")));
        assertThat(strings, Matchers.containsInAnyOrder(
            "timer:trigger?exchangePattern=InOut",
            "timer:trigger?exchangePattern=InOnly",
            "timer:trigger?exchangePattern=InOptionalOut",
            "timer:trigger?exchangePattern=OutIn",
            "timer:trigger?exchangePattern=RobustInOnly",
            "timer:trigger?exchangePattern=OutOptionalIn"));
        assertEquals(6, strings.size());
    }

}


text:
$ProgressPreference = 'SilentlyContinue'

# Get main download page for application.
$Page = Invoke-WebRequest -Uri 'https://notepad-plus-plus.org/downloads/' -UseBasicParsing

# Get download page for latest version.
$Page2 = Invoke-WebRequest -Uri ('https://notepad-plus-plus.org' + ($Page.Links | Where-Object {$_.outerHTML -like "*Current Version*"}).href) -UseBasicParsing

# Get installer link for latest version.
$DownloadLink = ($Page2.Links | Where-Object {$_.href -like "*Installer.exe*"})[0]

# Download installer.
$InstallerName = [System.IO.Path]::GetFileName($DownloadLink.href)
wget $DownloadLink.href -O $InstallerName

# Print the installer filename.
$InstallerName


text:
package com.netflix.spinnaker.clouddriver.ecs.services;

import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ecs.model.NetworkBinding;
import com.netflix.spinnaker.clouddriver.ecs.cache.Keys;
import com.netflix.spinnaker.clouddriver.ecs.cache.client.ContainerInstanceCacheClient;
import com.netflix.spinnaker.clouddriver.ecs.cache.client.EcsInstanceCacheClient;
import com.netflix.spinnaker.clouddriver.ecs.cache.client.ServiceCacheClient;
import com.netflix.spinnaker.clouddriver.ecs.cache.client.TaskCacheClient;
import com.netflix.spinnaker.clouddriver.ecs.cache.client.TaskHealthCacheClient;
import com.netflix.spinnaker.clouddriver.ecs.cache.model.ContainerInstance;
import com.netflix.spinnaker.clouddriver.ecs.cache.model.Service;
import com.netflix.spinnaker.clouddriver.ecs.cache.model.Task;
import com.netflix.spinnaker.clouddriver.ecs.cache.model.TaskHealth;
import com.netflix.spinnaker.clouddriver.ecs.security.ECSCredentialsConfig;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ContainerInformationService {

  private final ECSCredentialsConfig ecsCredentialsConfig;
  private final TaskCacheClient taskCacheClient;
  private final ServiceCacheClient serviceCacheClient;
  private final TaskHealthCacheClient taskHealthCacheClient;
  private final EcsInstanceCacheClient ecsInstanceCacheClient;
  private final ContainerInstanceCacheClient containerInstanceCacheClient;

  @Autowired
  public ContainerInformationService(
      ECSCredentialsConfig ecsCredentialsConfig,
      TaskCacheClient taskCacheClient,
      ServiceCacheClient serviceCacheClient,
      TaskHealthCacheClient taskHealthCacheClient,
      EcsInstanceCacheClient ecsInstanceCacheClient,
      ContainerInstanceCacheClient containerInstanceCacheClient) {
    this.ecsCredentialsConfig = ecsCredentialsConfig;
    this.taskCacheClient = taskCacheClient;
    this.serviceCacheClient = serviceCacheClient;
    this.taskHealthCacheClient = taskHealthCacheClient;
    this.ecsInstanceCacheClient = ecsInstanceCacheClient;
    this.containerInstanceCacheClient = containerInstanceCacheClient;
  }

  public List<Map<String, Object>> getHealthStatus(
      String taskId, String serviceName, String accountName, String region) {
    String serviceCacheKey = Keys.getServiceKey(accountName, region, serviceName);
    Service service = serviceCacheClient.get(serviceCacheKey);

    String healthKey = Keys.getTaskHealthKey(accountName, region, taskId);
    TaskHealth taskHealth = taskHealthCacheClient.get(healthKey);

    String taskKey = Keys.getTaskKey(accountName, region, taskId);
    Task task = taskCacheClient.get(taskKey);

    List<Map<String, Object>> healthMetrics = new ArrayList<>();

    // Load balancer-based health
    if (service == null || taskHealth == null) {
      Map<String, Object> loadBalancerHealth = new HashMap<>();
      loadBalancerHealth.put("instanceId", taskId);
      loadBalancerHealth.put("state", "Unknown");
      loadBalancerHealth.put("type", "loadBalancer");

      healthMetrics.add(loadBalancerHealth);
    } else {
      Map<String, Object> loadBalancerHealth = new HashMap<>();
      loadBalancerHealth.put("instanceId", taskId);
      loadBalancerHealth.put("state", taskHealth.getState());
      loadBalancerHealth.put("type", taskHealth.getType());

      healthMetrics.add(loadBalancerHealth);
    }

    // Task-based health
    if (task != null) {
      Map<String, Object> taskPlatformHealth = new HashMap<>();
      taskPlatformHealth.put("instanceId", taskId);
      taskPlatformHealth.put("type", "ecs");
      taskPlatformHealth.put("healthClass", "platform");
      taskPlatformHealth.put("state", toPlatformHealthState(task.getLastStatus()));
      healthMetrics.add(taskPlatformHealth);
    }

    return healthMetrics;
  }

  private String toPlatformHealthState(String ecsTaskStatus) {
    switch (ecsTaskStatus) {
      case "PROVISIONING":
      case "PENDING":
      case "ACTIVATING":
        return "Starting";
      case "RUNNING":
        return "Unknown";
      default:
        return "Down";
    }
  }

  public String getClusterArn(String accountName, String region, String taskId) {
    String key = Keys.getTaskKey(accountName, region, taskId);
    Task task = taskCacheClient.get(key);
    if (task != null) {
      return task.getClusterArn();
    }
    return null;
  }

  public String getClusterName(String serviceName, String accountName, String region) {
    String serviceCachekey = Keys.getServiceKey(accountName, region, serviceName);
    Service service = serviceCacheClient.get(serviceCachekey);
    if (service != null) {
      return service.getClusterName();
    }
    return null;
  }

  public String getTaskPrivateAddress(String accountName, String region, Task task) { //
    int hostPort;

    if (task.getContainers().size() > 1) {
      hostPort = getAddressHostPortForMultipleContainers(task);
    } else {
      try {
        hostPort = task.getContainers().get(0).getNetworkBindings().get(0).getHostPort();
      } catch (Exception e) {
        hostPort = -1;
      }
    }

    if (hostPort < 0 || hostPort > 65535) {
      return null;
    }

    Instance instance = getEc2Instance(accountName, region, task);
    if (instance == null) {
      return null;
    }

    String hostPrivateIpAddress = instance.getPrivateIpAddress();
    if (hostPrivateIpAddress == null || hostPrivateIpAddress.isEmpty()) {
      return null;
    }

    return String.format("%s:%s", hostPrivateIpAddress, hostPort);
  }

  public String getTaskZone(String accountName, String region, Task task) {
    Instance ec2Instance = getEc2Instance(accountName, region, task);
    if (ec2Instance != null && ec2Instance.getPlacement() != null) {
      return ec2Instance.getPlacement().getAvailabilityZone();
    }

    // TODO for tasks not placed on an instance (e.g. Fargate), determine the zone from the network
    // interface attachment
    return null;
  }

  public Instance getEc2Instance(String ecsAccount, String region, Task task) {
    String containerInstanceCacheKey =
        Keys.getContainerInstanceKey(ecsAccount, region, task.getContainerInstanceArn());
    ContainerInstance containerInstance =
        containerInstanceCacheClient.get(containerInstanceCacheKey);
    if (containerInstance == null) {
      return null;
    }

    Set<Instance> instances =
        ecsInstanceCacheClient.find(
            containerInstance.getEc2InstanceId(), getAwsAccountName(ecsAccount), region);
    if (instances.size() > 1) {
      throw new IllegalArgumentException(
          "There cannot be more than 1 EC2 container instance for a given region and instance ID.");
    } else if (instances.size() == 0) {
      return null;
    }

    return instances.iterator().next();
  }

  private String getAwsAccountName(String ecsAccountName) {
    for (ECSCredentialsConfig.Account ecsAccount : ecsCredentialsConfig.getAccounts()) {
      if (ecsAccount.getName().equals(ecsAccountName)) {
        return ecsAccount.getAwsAccount();
      }
    }
    return null;
  }

  private int getAddressHostPortForMultipleContainers(Task task) {
    List<Integer> hostPorts = new ArrayList<Integer>() {};

    task.getContainers()
        .forEach(
            (c) -> {
              List<NetworkBinding> networkBindings = c.getNetworkBindings();
              networkBindings.forEach(
                  (b) -> {
                    if (b.getHostPort() != null) {
                      hostPorts.add(b.getHostPort());
                    }
                  });
            });

    if (hostPorts.size() == 1) {
      return hostPorts.get(0);
    }

    return -1;
  }
}


text:
package org.apache.directory.api.ldap.codec.decorators;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;

import org.apache.directory.api.asn1.EncoderException;
import org.apache.directory.api.asn1.ber.tlv.TLV;
import org.apache.directory.api.i18n.I18n;
import org.apache.directory.api.ldap.codec.api.LdapApiService;
import org.apache.directory.api.ldap.codec.api.LdapConstants;
import org.apache.directory.api.ldap.model.message.ModifyDnResponse;

/**
 * A decorator for the ModifyDnResponse message
 *
 * @author Apache Directory Project
 */
public class ModifyDnResponseDecorator extends ResponseDecorator<ModifyDnResponse>
    implements ModifyDnResponse
{
    /** The encoded modifyDnResponse length */
    private int modifyDnResponseLength;

    /**
     * Makes a ModifyDnResponse encodable.
     *
     * @param decoratedMessage the decorated ModifyDnResponse
     */
    public ModifyDnResponseDecorator( LdapApiService codec, ModifyDnResponse decoratedMessage )
    {
        super( codec, decoratedMessage );
    }

    /**
     * @param modifyDnResponseLength The encoded ModifyDnResponse's length
     */
    public void setModifyDnResponseLength( int modifyDnResponseLength )
    {
        this.modifyDnResponseLength = modifyDnResponseLength;
    }

    /**
     * Stores the encoded length for the ModifyDnResponse
     * @return The encoded length
     */
    public int getModifyDnResponseLength()
    {
        return modifyDnResponseLength;
    }

    //-------------------------------------------------------------------------
    // The Decorator methods
    //-------------------------------------------------------------------------
    /**
     * Compute the ModifyDNResponse length
     *
     * ModifyDNResponse :
     *

     * 0x6D L1
     *   |
     *   +--> LdapResult
     *
     * L1 = Length(LdapResult)
     * Length(ModifyDNResponse) = Length(0x6D) + Length(L1) + L1
     *

     */
    public int computeLength()
    {
        int modifyDnResponseLength = ( ( LdapResultDecorator ) getLdapResult() ).computeLength();

        setModifyDnResponseLength( modifyDnResponseLength );

        return 1 + TLV.getNbBytes( modifyDnResponseLength ) + modifyDnResponseLength;
    }

    /**
     * Encode the ModifyDnResponse message to a PDU.
     *
     * @param buffer The buffer where to put the PDU
     */
    public ByteBuffer encode( ByteBuffer buffer ) throws EncoderException
    {
        try
        {
            // The ModifyResponse Tag
            buffer.put( LdapConstants.MODIFY_DN_RESPONSE_TAG );
            buffer.put( TLV.getBytes( getModifyDnResponseLength() ) );

            // The LdapResult
            ( ( LdapResultDecorator ) getLdapResult() ).encode( buffer );
        }
        catch ( BufferOverflowException boe )
        {
            throw new EncoderException( I18n.err( I18n.ERR_04005 ) );
        }

        return buffer;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PhpUnit">
    <phpunit_settings>
      <PhpUnitSettings load_method="CUSTOM_LOADER" bootstrap_file_path="$PROJECT_DIR$/tests/bootstrap.php" configuration_file_path="$PROJECT_DIR$/phpunit.xml" custom_loader_path="$PROJECT_DIR$/vendor/autoload.php" phpunit_phar_path="" use_bootstrap_file="true" use_configuration_file="true" />
    </phpunit_settings>
  </component>
</project>


text:
var useragent = require('useragent')
var Charm = require('charm')

module.exports = matrixReporter

var COLORS = {
  white: 'white',
  black: 'black',
  header: 25,
  darkgrey: 234,
  grey: 240,
  running: 33,
  failure: 124,
  success: 112,
  pending: 240,
  err: 208
}

function matrixReporter (kawa) {
  var charm = Charm()
  charm.pipe(process.stdout)
  charm.reset()
  charm.cursor(false)

  process.on('exit', function () {
    charm.cursor(true)
  })

  var stats = {}

  kawa.on('reload', function (data) {
    Object.keys(stats).forEach(function (k) {
      if (stats[k].status === -1) {
        delete stats[k]
      } else {
        stats[k].status = -1
      }
    })
    update()
  })

  kawa.on('json', function (data) {
    stats[data.userAgent] = data
    update()
  })

  // Update (to draw the interface at least one time before receiving any data)
  update()

  function update () {
    var keys = Object.keys(stats)
    var count = keys.length
    var port = kawa.server.address().port

    // Write kawa header
    charm
      .display('reset')
      .position(1, 1)
      .background(COLORS.header)
      .foreground(COLORS.white)
      .erase('line')
      .display('bright')
      .write(' KAWA ➔ http://localhost:' + port)
      .foreground(COLORS.darkgrey)
      .write(' (press ^C to leave)')

    // Clear screen
    charm
      .foreground(COLORS.white)
      .position(1, 2)
      .background(COLORS.darkgrey)
      .erase('line')
      .position(1, 3)
      .background(COLORS.black)
      .erase('down')

    keys.forEach(function (k, index) {
      var data = stats[k]
      var ua = useragent.parse(data.userAgent)

      // Prepare line for one user agent
      charm
        .position((index * 3) + 1, 2)
        .display('reset')
        .foreground(COLORS.white)
        .background(COLORS.black)
        .display('bright')

      switch (data.status) {
        case 0:
          charm.display('blink')
          charm.background(COLORS.running)
          break
        case 1:
          if (data.stats.failures > 0) {
            charm.background(COLORS.failure)
          } else {
            charm.background(COLORS.success)
          }
          break
        default:
          charm.background(COLORS.pending)
      }

      // Write user agent index (horizontal)
      charm.write(' ' + index + ' ')

      // Write user agent index (vertical)
      charm
        .position(1, index + 3)
        .write(' ' + index + ' ')

      // Write user agent name
      charm
        .display('reset')
        .background(COLORS.black)
        .foreground(COLORS.white)
        .right(1)
        .write(ua.toString())

      // Add state (duration / running / pending)
      charm.foreground(COLORS.grey)
      if (data.stats.duration) {
        charm.write(' (' + data.stats.duration + 'ms)')
      } else if (data.status === 0) {
        charm.write(' (running)')
      } else if (data.status === -1) {
        charm.write(' (pending)')
      }

      // Print last error
      if (data.stats.failures && data.tests) {
        charm.display('reset')
        data.tests.forEach(function (test) {
          if (!test.err.stack) {
            return
          }
          // Error header
          charm
            .position(1, count + 4)
            .erase('down')
            .background(COLORS.grey)
            .foreground(COLORS.err)
            .write(' ERR ')
            .background(COLORS.black)
            .foreground(COLORS.white)
            .write(' ' + test.fullTitle + ' (' + ua.toString() + ')')
          // Error stack
          charm
            .foreground(COLORS.grey)
            .position(1, keys.length + 6)
            .write(test.err.stack)
        })
      }
    })
  }
}


text:
package org.javarosa.core.util;

/**
 * @author Clayton Sims
 */
public class NoLocalizedTextException extends RuntimeException {
    private final String keynames;
    private final String locale;

    public NoLocalizedTextException(String message, String keynames, String locale) {
        super(message);
        this.keynames = keynames;
        this.locale = locale;
    }

    public String getMissingKeyNames() {
        return keynames;
    }

    public String getLocaleMissingKey() {
        return locale;
    }
}


text:
#import "CCScrollView.h"

@class CCButton;
@class CCTableView;

#pragma mark CCTableViewCell

@interface CCTableViewCell : CCNode
{
    NSUInteger _index;
}

@property (nonatomic,readonly) CCButton* button;

@end

#pragma mark CCTableViewDataSource

@protocol CCTableViewDataSource <NSObject>

- (CCTableViewCell*) tableView:(CCTableView*)tableView nodeForRowAtIndex:(NSUInteger) index;
- (NSUInteger) tableViewNumberOfRows:(CCTableView*) tableView;

@optional

- (float) tableView:(CCTableView*)tableView heightForRowAtIndex:(NSUInteger) index;

@end

#pragma mark CCTableView

@interface CCTableView : CCScrollView
{
    BOOL _visibleRowsDirty;
    NSMutableArray* _rows;
    NSRange _currentlyVisibleRange;
    struct {
        int heightForRowAtIndex:1;
        // reserved for future dataSource delegation
    } _dataSourceFlags;
}

@property (nonatomic,strong) id <CCTableViewDataSource> dataSource;
@property (nonatomic,assign) CGFloat rowHeight;
@property (nonatomic,assign) CCSizeUnit rowHeightUnit;
@property (nonatomic,readonly) CGFloat rowHeightInPoints;
@property (nonatomic,assign) NSUInteger selectedRow;

@property (nonatomic,copy) void(^block)(id sender);
-(void) setTarget:(id)target selector:(SEL)selector;

- (void) reloadData;

@end


text:
const motivations = require('motivations');
const pickOne = require('pick-one');

const express = require('express');
const exphbs  = require('express-handlebars');

const app = express();

app.use(express.static('./app/public'));

app.engine('handlebars', exphbs({
  defaultLayout: 'main',
  layoutsDir:'./app/views/layouts'
}));

app.set('view engine', 'handlebars');
app.set('views', './app/views');

app.get("/", function(request, response){
  const catImageFiles = [1, 2, 3, 4, 5, 6];

  var motivation = pickOne(motivations);
  var image = pickOne(catImageFiles)

  response.render('motivation', { motivation, image });
});

module.exports = app


text:
require_relative '../scrapper_conf'
ScrapperConf.load

require_relative '../../websites/website_scrapper'
require_relative '../../websites/tumblr/tumblr2_scrapper'

url = YAML.load_file('private-conf/tumblr.yml')["tumblr2"]["url"]
tumblr2 = Tumblr2Scrapper.new(url)
scrapper = WebsiteScrapper.new(tumblr2)
scrapper.start


text:
FactoryBot.define do
  factory :sink_fund_allocation do
    name { "MyString" }
    bank_account
    amount { 1 }
  end

end


text:
package com.intel.analytics.bigdl.torch

import java.io.PrintWriter

import com.intel.analytics.bigdl.nn._
import com.intel.analytics.bigdl.optim.SGD
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.RandomGenerator._
import com.intel.analytics.bigdl.utils.T

import scala.sys.process._

@com.intel.analytics.bigdl.tags.Serial
class LSTMPeepholeSpec  extends TorchSpec {
  override def torchCheck(): Unit = {
    if (!TH.hasTorch()) {
      cancel("Torch is not installed")
    }
    val tmpFile = java.io.File.createTempFile("checkRNN", ".lua")
    val writer = new PrintWriter(tmpFile)
    writer.write("exist = (pcall(require, 'rnn'))\n print(exist)")
    writer.close()

    val existsRNN =
      Seq(System.getProperty("torch_location", "th"), tmpFile.getAbsolutePath).!!.trim
    if (!existsRNN.contains("true")) {
      cancel("Torch rnn is not installed")
    }
  }

  "A LSTMPeepwhole " should "has same loss as torch rnn" in {
    torchCheck()

    import com.intel.analytics.bigdl.numeric.NumericDouble
    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val seqLength = 5
    val seed = 100
    val batchSize = 1

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(batchSize, seqLength, inputSize))
    val labels = Tensor[Double](Array(batchSize, seqLength))
    for (b <- 1 to batchSize) {
      for (i <- 1 to seqLength) {
        val rdmInput = Math.ceil(RNG.uniform(0.0, 1.0) * inputSize).toInt
        input.setValue(b, i, rdmInput, 1.0)
        val rdmLabel = Math.ceil(RNG.uniform(0.0, 1.0) * outputSize).toInt
        labels.setValue(b, i, rdmLabel)
      }
    }

    println(input)
    val rec = Recurrent[Double](hiddenSize)

    val model = Sequential[Double]()
      .add(rec
        .add(LSTMPeephole[Double](inputSize, hiddenSize)))
      //      .add(LSTM[Double](inputSize, hiddenSize)))
      //      .add(RnnCell[Double](inputSize, hiddenSize, Sigmoid[Double]())))
      //            .add(FastLSTMCell[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double](), false)
    val logSoftMax = TimeDistributed[Double](LogSoftMax[Double]())

    val (weights, grad) = model.getParameters()

    val code =
      s"""
         |
      |-- 1.4. Combine 1.1 and 1.3 to produce final model
         |require 'rnn'
         |torch.manualSeed($seed)
         |
      |local rm =  nn.Sequential() -- input is {x[t], h[t-1]}
         |         :add(nn.ParallelTable()
         |            :add(nn.Linear($inputSize, $hiddenSize)) -- input layer
         |            :add(nn.Linear($hiddenSize, $hiddenSize))) -- recurrent layer
         |         :add(nn.CAddTable()) -- merge
         |         :add(nn.Sigmoid()) -- transfer
         |     --    :add(nn.Tanh()) -- transfer
         |
      | -- local rm1 =  nn.Sequential() -- input is {x[t], h[t-1]}
         | --        :add(nn.ParallelTable()
         | --           :add(nn.Linear($inputSize, $hiddenSize)) -- input layer
         | --           :add(nn.Identity())) -- recurrent layer
         | --        :add(nn.CAddTable()) -- merge
         | --        :add(nn.Sigmoid()) -- transfer
         |      rnn = nn.Recurrence(rm, $hiddenSize, 1)
         | --     rnn.userPrevOutput = torch.Tensor(1, $hiddenSize):zero()
         |
      |model = nn.Sequential()
         |:add(nn.SplitTable(1))
         |:add(nn.Sequencer(
         | nn.Sequential()
         |   :add(nn.LSTM($inputSize, $hiddenSize, 1, true))
         |   --:add(nn.FastLSTM($inputSize, $hiddenSize, 1, nil, nil, nil, 0.3))
         |   :add(nn.Linear($hiddenSize, $outputSize))
         |   ))
         |
         |
         |local parameters, gradParameters = model:getParameters()
         |model:zeroGradParameters()
         |parameters:copy(weights)
         |
         |parameters_initial = parameters : clone()
         |gradParameters_initial = gradParameters : clone()
         |
         |local criterion =  nn.SequencerCriterion(nn.CrossEntropyCriterion())
         |
      |
      |state = {
         |  learningRate = 0.5,
         |  momentum = 0.0,
         |  dampening = 0.0,
         |  weightDecay = 0.0
         |}
         |
      |feval = function(x)
         |model:zeroGradParameters()
         |model_initial = model : clone()
         |
      |local output1 = model:forward(input)
         |local err1 = criterion:forward(output1, labels)
         |local gradOutput1 = criterion:backward(output1, labels)
         |model:backward(input, gradOutput1)
         |return err1, gradParameters
         |end
         |
      |for i = 1,100,1 do
         |   optim.sgd(feval, parameters, state)
         |end
         |
      |output=model.output
         |err=criterion.output
         |err2=criterion.gradInput
         |gradOutput=criterion.gradInput
         |gradInput = model.gradInput
    """.stripMargin

    val (luaTime, torchResult) = TH.run(code,
      Map("input" -> input.transpose(1, 2), "weights" -> weights,
        "labels" -> SplitTable[Double](1).forward(labels.t())),
      Array("output", "err", "parameters", "gradParameters", "output2", "gradInput", "err2"))

    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.forward(input).toTensor[Double].clone())
    //
    val luaOutput2 = torchResult("err").asInstanceOf[Double]
    val luaweight = torchResult("parameters").asInstanceOf[Tensor[Double]]

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Double]
    def feval(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model.forward(input).asInstanceOf[Tensor[Double]]
      val _loss = criterion.forward(output, labels)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model.backward(input, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Double] = null
    for (i <- 1 to 100) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    //    println("Element weight: " + luaweight)
    //    println("BigDL weight: " + weights)
    //
    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.output)
    //
    //    println("BigDL labels: " + labels)
    //
    //    val crtnGradInput = criterion.backward(model.output, labels)
    //    println(s"element: criterion gradInput: $err2")
    //    println("BigDL criterion gradInput: " + crtnGradInput)
    //
    //    println(s"element: gradInput: $gradInput1")
    //    println("BigDL: " + model.gradInput.toTensor[Double])
    //
    //    println(s"element: gradWeight: $gradParameters")
    //    println("BigDL: " + model.getParameters()._2)

    val output = model.forward(input).toTensor
    val logOutput = logSoftMax.forward(output)
    val prediction = logOutput.max(3)._2

    luaOutput2 should be(loss(0) +- 1e-5)
  }

  "A LSTMPeepwhole " should "converge" in {
    torchCheck()

    import com.intel.analytics.bigdl.numeric.NumericDouble
    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val seqLength = 5
    val seed = 100

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(1, seqLength, inputSize))
    val labels = Tensor[Double](Array(1, seqLength))
    for (i <- 1 to seqLength) {
      val rdmLabel = Math.ceil(RNG.uniform(0, 1) * outputSize).toInt
      val rdmInput = Math.ceil(RNG.uniform(0, 1) * inputSize).toInt
      input.setValue(1, i, rdmInput, 1.0)
      labels.setValue(1, i, rdmLabel)
    }

    println(input)
    val rec = Recurrent[Double](hiddenSize)

    val model = Sequential[Double]()
      .add(rec
        .add(LSTMPeephole[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double](), false)
    val logSoftMax = TimeDistributed[Double](LogSoftMax[Double]())

    val (weights, grad) = model.getParameters()

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Double]
    def feval(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model.forward(input).asInstanceOf[Tensor[Double]]
      val _loss = criterion.forward(output, labels)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model.backward(input, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Double] = null
    for (i <- 1 to 100) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    val output = model.forward(input).toTensor
    val logOutput = logSoftMax.forward(output)
    val prediction = logOutput.max(3)._2

    labels.squeeze() should be (prediction.squeeze())
  }

  "A LSTMPeepwhole " should "has same loss as torch rnn in batch mode" in {
    torchCheck()

    import com.intel.analytics.bigdl.numeric.NumericFloat
    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val seqLength = 5
    val seed = 100
    val batchSize = 5

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(batchSize, seqLength, inputSize))
    val labels = Tensor[Double](Array(batchSize, seqLength))
    for (b <- 1 to batchSize) {
      for (i <- 1 to seqLength) {
        val rdmInput = Math.ceil(RNG.uniform(0, 1)  * inputSize).toInt
        input.setValue(b, i, rdmInput, 1f)
        val rdmLabel = Math.ceil(RNG.uniform(0, 1)  * outputSize).toInt
        labels.setValue(b, i, rdmLabel)
      }
    }

    println(input)
    val rec = Recurrent(hiddenSize)

    val model = Sequential()
      .add(rec
        .add(LSTMPeephole(inputSize, hiddenSize)))
      .add(TimeDistributed(Linear(hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion(
      CrossEntropyCriterion())
    val logSoftMax = TimeDistributed(LogSoftMax())

    val (weights, grad) = model.getParameters()

    val code =
      s"""
         |
      |-- 1.4. Combine 1.1 and 1.3 to produce final model
         |require 'rnn'
         |torch.manualSeed($seed)
         |
      |local rm =  nn.Sequential() -- input is {x[t], h[t-1]}
         |         :add(nn.ParallelTable()
         |            :add(nn.Linear($inputSize, $hiddenSize)) -- input layer
         |            :add(nn.Linear($hiddenSize, $hiddenSize))) -- recurrent layer
         |         :add(nn.CAddTable()) -- merge
         |         :add(nn.Sigmoid()) -- transfer
         |     --    :add(nn.Tanh()) -- transfer
         |
      |model = nn.Sequential()
         |:add(nn.SplitTable(1))
         |:add(nn.Sequencer(
         | nn.Sequential()
         |   :add(nn.LSTM($inputSize, $hiddenSize, 1, true))
         |   --:add(nn.FastLSTM($inputSize, $hiddenSize, 1))
         |   :add(nn.Linear($hiddenSize, $outputSize))
         |   ))
         |
         |
         |local parameters, gradParameters = model:getParameters()
         |model:zeroGradParameters()
         |parameters:copy(weights)
         |
         |parameters_initial = parameters : clone()
         |gradParameters_initial = gradParameters : clone()
         |
         |local criterion =  nn.SequencerCriterion(nn.CrossEntropyCriterion())
         |
      |
      |state = {
         |  learningRate = 0.5,
         |  momentum = 0.0,
         |  dampening = 0.0,
         |  weightDecay = 0.0
         |}
         |
      |feval = function(x)
         |model:zeroGradParameters()
         |model_initial = model : clone()
         |
      |local output1 = model:forward(input)
         |local err1 = criterion:forward(output1, labels)
         |local gradOutput1 = criterion:backward(output1, labels)
         |model:backward(input, gradOutput1)
         |return err1, gradParameters
         |end
         |
      |for i = 1,20,1 do
         |   optim.sgd(feval, parameters, state)
         |end
         |
      |output=model.output
         |err=criterion.output
         |err2=criterion.gradInput
         |gradOutput=criterion.gradInput
         |gradInput = model.gradInput
    """.stripMargin
    scala.Seq

    val (luaTime, torchResult) = TH.run(code,
      Map("input" -> input.transpose(1, 2), "weights" -> weights,
        "labels" -> SplitTable[Double](1).forward(labels.t())),
      Array("output", "err", "parameters", "gradParameters", "output2", "gradInput", "err2"))

    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.forward(input).toTensor[Double].clone())
    //
    val luaOutput2 = torchResult("err").asInstanceOf[Double]
    val luaweight = torchResult("parameters").asInstanceOf[Tensor[Double]]

    val floatInput = Tensor(Array(batchSize, seqLength, inputSize))
    val floatLabel = Tensor(Array(batchSize, seqLength))

    for (i <- 0 until floatInput.nElement()) {
      floatInput.storage().array()(i) = input.storage().array()(i).toFloat
    }
    for (i <- 0 until floatLabel.nElement()) {
      floatLabel.storage().array()(i) = labels.storage().array()(i).toFloat
    }

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Float]()
    def feval(x: Tensor[Float]): (Float, Tensor[Float]) = {
      val output = model.forward(floatInput).asInstanceOf[Tensor[Float]]
      val _loss = criterion.forward(output, floatLabel)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, floatLabel)
      model.backward(floatInput, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Float] = null
    for (i <- 1 to 20) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    //    println("Element weight: " + luaweight)
    //    println("BigDL weight: " + weights)
    //
    //    println("Element forward: " + output1)
    //    println("BigDL forward: " + model.output)
    //
    //    println("BigDL labels: " + labels)
    //
    //    val crtnGradInput = criterion.backward(model.output, labels)
    //    println(s"element: criterion gradInput: $err2")
    //    println("BigDL criterion gradInput: " + crtnGradInput)
    //
    //    println(s"element: gradInput: $gradInput1")
    //    println("BigDL: " + model.gradInput.toTensor[Double])
    //
    //    println(s"element: gradWeight: $gradParameters")
    //    println("BigDL: " + model.getParameters()._2)

    val output = model.forward(floatInput).toTensor
    val logOutput = logSoftMax.forward(output)

    luaOutput2.toFloat should be(loss(0) +- 2e-2f)
  }

  "A LSTMPeepwhole " should "converge in batch mode" in {
    torchCheck()

    import com.intel.analytics.bigdl.numeric.NumericDouble
    val hiddenSize = 4
    val inputSize = 6
    val outputSize = 5
    val bpttTruncate = 3
    val batchSize = 3
    val seqLength = 5
    val seed = 100

    RNG.setSeed(seed)
    val input = Tensor[Double](Array(batchSize, seqLength, inputSize))
    val labels = Tensor[Double](Array(batchSize, seqLength))
    for (b <- 1 to batchSize) {
      for (i <- 1 to seqLength) {
        val rdmInput = Math.ceil(RNG.uniform(0.0, 1.0) * inputSize).toInt
        input.setValue(b, i, rdmInput, 1.0)
        val rdmLabel = Math.ceil(RNG.uniform(0.0, 1.0) * outputSize).toInt
        labels.setValue(b, i, rdmLabel)
      }
    }

    println(input)
    val rec = Recurrent[Double](hiddenSize)

    val model = Sequential[Double]()
      .add(rec
        .add(LSTMPeephole[Double](inputSize, hiddenSize)))
      .add(TimeDistributed[Double](Linear[Double](hiddenSize, outputSize)))

    val criterion = TimeDistributedCriterion[Double](
      CrossEntropyCriterion[Double](), false)
    val logSoftMax = TimeDistributed[Double](LogSoftMax[Double]())

    val (weights, grad) = model.getParameters()

    val state = T("learningRate" -> 0.5, "momentum" -> 0.0,
      "weightDecay" -> 0.0, "dampening" -> 0.0)
    val sgd = new SGD[Double]
    def feval(x: Tensor[Double]): (Double, Tensor[Double]) = {
      val output = model.forward(input).asInstanceOf[Tensor[Double]]
      val _loss = criterion.forward(output, labels)
      model.zeroGradParameters()
      val gradInput = criterion.backward(output, labels)
      model.backward(input, gradInput)
      (_loss, grad)
    }

    val start = System.nanoTime()
    var loss: Array[Double] = null
    for (i <- 1 to 300) {
      loss = sgd.optimize(feval, weights, state)._2
      println(s"${i}-th loss = ${loss(0)}")
    }
    val end = System.nanoTime()
    println("Time: " + (end - start) / 1E6)

    val output = model.forward(input).toTensor
    val logOutput = logSoftMax.forward(output)
    val prediction = logOutput.max(3)._2

    labels.squeeze() should be (prediction.squeeze())
  }

  "A LSTMPeepwhole " should "perform correct gradient check" in {
    torchCheck()

    val hiddenSize = 4
    val inputSize = 5
    val outputSize = 5
    val bpttTruncate = 10
    val seed = 100
    RNG.setSeed(seed)

    val model = Sequential[Double]()
      .add(Recurrent[Double](hiddenSize)
        .add(LSTMPeephole[Double](inputSize, hiddenSize)))
      .add(Select(1, 1))
      .add(Linear[Double](hiddenSize, outputSize))

    model.reset()

    val input = Tensor[Double](Array(1, 5, inputSize))
    val labels = Tensor[Double](Array(1, 5))
    for (i <- 1 to 5) {
      val rdmLabel = Math.ceil(RNG.uniform(0, 1)*inputSize).toInt
      val rdmInput = Math.ceil(RNG.uniform(0, 1)*inputSize).toInt
      input.setValue(1, i, rdmInput, 1.0)
      labels.setValue(1, i, rdmLabel)
    }

    println("gradient check for input")
    val gradCheckerInput = new GradientChecker(1e-2, 1)
    val checkFlagInput = gradCheckerInput.checkLayer[Double](model, input)
    println("gradient check for weights")
    val gradCheck = new GradientCheckerRNN(1e-2, 1)
    val checkFlag = gradCheck.checkLayer(model, input, labels)
  }
}


text:
This directory contains a snapshot of protobuf ruby 3.0.0 unittest code and
test scripts used to verifies whether the latest version of protobuf is
still compatible with 3.0.0 generated code.


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\CorePluginsAdmin;

use Piwik\Config;
use Piwik\Plugin;

class CorePluginsAdmin extends Plugin
{
    /**
     * @see Plugin::registerEvents
     */
    public function registerEvents()
    {
        return array(
            'AssetManager.getJavaScriptFiles'        => 'getJsFiles',
            'AssetManager.getStylesheetFiles'        => 'getStylesheetFiles',
            'Translate.getClientSideTranslationKeys' => 'getClientSideTranslationKeys'
        );
    }

    public function getStylesheetFiles(&$stylesheets)
    {
        $stylesheets[] = "plugins/CorePluginsAdmin/stylesheets/plugins_admin.less";
        $stylesheets[] = "plugins/CorePluginsAdmin/angularjs/plugin-settings/plugin-settings.directive.less";
    }

    public static function isPluginsAdminEnabled()
    {
        return (bool) Config::getInstance()->General['enable_plugins_admin'];
    }

    public function getJsFiles(&$jsFiles)
    {
        $jsFiles[] = "libs/bower_components/jQuery.dotdotdot/src/js/jquery.dotdotdot.min.js";
        $jsFiles[] = "plugins/CoreHome/javascripts/popover.js";
    }

    public function getClientSideTranslationKeys(&$translations)
    {
        $translations[] = 'CorePluginsAdmin_NoZipFileSelected';
        $translations[] = 'CorePluginsAdmin_NoPluginSettings';
        $translations[] = 'CoreAdminHome_PluginSettingsIntro';
        $translations[] = 'CoreAdminHome_PluginSettingsSaveSuccess';
        $translations[] = 'General_Save';
    }

}


text:
xen
===

xenFramework Library


text:
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class TestDetails(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get("http://gamingdb.info")

    def test_select_game(self):
        driver = self.driver
        driver.find_element_by_class_name('grid-item').click()

    def test_title(self):
        driver = self.driver
        driver.find_element_by_class_name('grid-item').click()

        # Test that there is a game title
        title = driver.find_element_by_class_name('detail-title').text
        self.assertIsNotNone(title)
        self.assertNotEqual(title, "")

    def test_image(self):
        driver = self.driver
        driver.find_element_by_class_name('grid-item').click()

        # Test that there is an image
        image = driver.find_element_by_class_name('sidebar-img').get_property('src')
        self.assertIsNotNone(image)
        self.assertNotEqual(image, "")

    def test_description(self):
        driver = self.driver
        driver.find_element_by_class_name('grid-item').click()

        #Test that there is a description
        description = driver.find_element_by_class_name('detail-description').text
        self.assertIsNotNone(description)
        self.assertNotEqual(description, "")

    def test_related_game(self):
        driver = self.driver

        # Click game
        driver.find_element_by_class_name('grid-item').click()

        # Get a related game if there is one
        try:
            relatedGame = driver.find_element_by_class_name('grid-item')
            relatedGame.click()
            self.assertIn("gamingdb.info/games/", driver.current_url)
        except Exception as e:
            # In some rare cases the related games have failed to load yet
            # So just pass here if there are no related games
            pass

    def tearDown(self):
        self.driver.close()

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


text:
module Mousereco
  class VisitsController < Mousereco::ApplicationController
    def index
      @visits = Mousereco::Visit.order("created_at DESC")
    end
  end
end


text:
/* - Coeus web framework -------------------------
 *
 * Licensed under the Apache License, Version 2.0.
 *
 * Author: Spiros Tzavellas
 */
package com.tzavellas.coeus.core

import scala.collection.Set

trait HandlerMap {

  def isEmpty: Boolean

  def apply(method: Symbol): Handler

  def isMethodAllowed(method: Symbol): Boolean

  def supportedMethods: Set[String]
}

object HandlerMap {
  val empty: HandlerMap = new MutableHandlerMap
}


text:
<?php

namespace Pum\Core\Extension\Core\Type;

use Doctrine\ORM\Mapping\ClassMetadata;
use Pum\Core\AbstractType;
use Pum\Core\Context\FieldBuildContext;
use Pum\Core\Context\FieldContext;
use Doctrine\ORM\QueryBuilder;
use Pum\Core\Definition\View\FormViewField;
use Pum\Core\Extension\Validation\Constraints\Date as DateTimeConstraints;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata as ValidationClassMetadata;

class DateType extends AbstractType
{
    const DATE_FORMAT    = "dd/MM/yyyy";
    const JS_DATE_FORMAT = "dd/mm/yy";

    const ANTERIOR_DATE  = 'anterior';
    const POSTERIOR_DATE = 'posterior';

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            '_doctrine_type'   => 'date',
            'unique'           => false,
            'restriction'      => null,
            'required'         => false,
            'label'            => null,
            'placeholder'      => null
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function buildOptionsForm(FormBuilderInterface $builder)
    {
        $builder
            ->add('unique', 'checkbox', array('required' => false))
            ->add('required', 'checkbox', array('required' => false))
            ->add('restriction', 'choice', array(
                    'required' => false,
                    'choices'   => array(
                            self::ANTERIOR_DATE  => 'pum.form.field.type.name.restriction.values.date.' . self::ANTERIOR_DATE,
                            self::POSTERIOR_DATE => 'pum.form.field.type.name.restriction.values.date.' . self::POSTERIOR_DATE
                    ),
                    'placeholder' => 'pum.form.field.type.name.restriction.values.date.emptyvalue'
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function addFilterCriteria(FieldContext $context, QueryBuilder $qb, $filter)
    {
        if (!isset($filter['type']) || !$filter['type']) {
            return $qb;
        }
        if (!isset($filter['value'])) {
            return $qb;
        }

        if (in_array($filter['type'], array('<', '>', '<=', '>=', '<>', '='))) {
            $operator = $filter['type'];
        } else {
            throw new \InvalidArgumentException(sprintf('Unexpected filter type "%s".', $filter['type']));
        }

        $value = $filter['value'];

        if (is_string($value)) {
            $value = new \DateTime($value);
        }

        $parameterKey = count($qb->getParameters());

        return $qb
            ->andWhere($qb->getRootAlias().'.'.$context->getField()->getCamelCaseName().' '.$operator.' ?'.$parameterKey)
            ->setParameter($parameterKey, $value)
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildField(FieldBuildContext $context)
    {
        $cb = $context->getClassBuilder();
        $camel = $context->getField()->getCamelCaseName();

        $cb->createProperty($camel);

        $cb->createMethod('get'.ucfirst($camel), '', '
            return $this->'.$camel.';
        ');

        $cb->createMethod('set'.ucfirst($camel), '\DateTime $'.$camel.' = null', '
            $this->'.$camel.' = $'.$camel.';

            return $this;
        ');
    }

    /**
     * {@inheritdoc}
     */
    public function mapDoctrineField(FieldContext $context, ClassMetadata $metadata)
    {
        $metadata->mapField(array(
            'columnName' => $context->getField()->getLowercaseName(),
            'fieldName' => $context->getField()->getCamelCaseName(),
            'type'      => $context->getOption('_doctrine_type'),
            'nullable'  => true,
            'unique'    => $context->getOption('unique'),
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function mapValidation(FieldContext $context, ValidationClassMetadata $metadata)
    {
        $metadata->addGetterConstraint($context->getField()->getCamelCaseName(), new DateTimeConstraints(array('restriction' => $context->getOption('restriction'))));
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FieldContext $context, FormBuilderInterface $form, FormViewField $formViewField)
    {
        $restriction = $context->getOption('restriction');

        if ($restriction === self::ANTERIOR_DATE) {
            $yearsRange = "-70:+0";
            $minDate = new \DateTime("-70 years");
            $maxDate = new \DateTime();
        } elseif ($restriction === self::POSTERIOR_DATE) {
            $yearsRange = "-0:+70";
            $minDate = new \DateTime();
            $maxDate = new \DateTime("+70 years");
        } else {
            $yearsRange = "-35:+35";
            $minDate = new \DateTime("-35 years");
            $maxDate = new \DateTime("+35 years");
        }

        $form->add($context->getField()->getCamelCaseName(), 'date', array(
            'widget' => 'single_text',
            'format' => self::DATE_FORMAT,
            'attr'   => array(
                'class' => 'datepicker',
                'data-yearrange'  => $yearsRange,
                'data-mindate'    => $minDate->format("U"),
                'data-maxdate'    => $maxDate->format("U"),
                'data-dateFormat' => self::JS_DATE_FORMAT,
                'placeholder'     => $formViewField->getPlaceholder()
            ),
            'label'    => $formViewField->getLabel(),
            'required' => $context->getOption('required'),
            'disabled' => $formViewField->getDisabled(),
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'date';
    }
}


text:
class Person
  def initialize(name, phone)
    @name = name
    @phone = phone
  end

  def say_name
    puts "My name is #{@name}"
  end

  def receive_call
    @phone.ring
  end
end


text:
package de.lukweb.twitchchat.events.chat;

import de.lukweb.twitchchat.events.Event;

public class ChatReconnectEvent extends Event {

}


text:
package run

import (
	"os"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/papercutsoftware/silver/lib/logging"
)

func TestServiceNormalShutdown(t *testing.T) {

	const timeout = 2
	const maxRun = 10

	c := new(ServiceConfig)
	c.Path = os.Args[0]
	c.Args = helperArgs("sleep-for", strconv.Itoa(maxRun))

	terminate := make(chan struct{})
	go func() {
		time.Sleep(timeout * time.Second)
		close(terminate)
	}()

	startingTime := time.Now().UTC()
	err := RunService(c, terminate)
	if err != nil {
		t.Errorf("Service did not exit cleanly: %v", err)
	}
	endingTime := time.Now().UTC()

	duration := endingTime.Sub(startingTime)

	if duration >= time.Duration(maxRun*time.Second) {
		t.Error("Did not time out")
	}
}

func TestServiceCrashCount(t *testing.T) {
	const timeout = 20

	c := new(ServiceConfig)
	c.Path = os.Args[0]
	c.Args = helperArgs("crash-in", "1")
	c.MaxCrashCount = 2

	terminate := make(chan struct{})
	go func() {
		time.Sleep(timeout * time.Second)
		close(terminate)
	}()

	startingTime := time.Now().UTC()
	err := RunService(c, terminate)
	if err == nil {
		t.Errorf("Error expected from crashing service")
	}
	if !strings.Contains(err.Error(), "MaxCrashCount") {
		t.Errorf("Expected error with MaxCrashCount exceeded. Got: %s", err.Error())
	}
	endingTime := time.Now().UTC()

	duration := endingTime.Sub(startingTime)

	if duration >= time.Duration(timeout*time.Second) {
		t.Error("Did not exit due to persistent crashes")
	}
}

func TestServiceGracefulShutdown(t *testing.T) {
	const timeout = 1
	const shutdownTime = 5

	c := new(ServiceConfig)
	c.Path = os.Args[0]
	c.Args = helperArgs("work-before-exit", strconv.Itoa(shutdownTime))

	terminate := make(chan struct{})
	go func() {
		time.Sleep(timeout * time.Second)
		close(terminate)
	}()

	startingTime := time.Now().UTC()
	err := RunService(c, terminate)
	if err != nil {
		t.Errorf("Error reported from service: %v", err)
	}
	endingTime := time.Now().UTC()

	duration := endingTime.Sub(startingTime)

	if duration <= time.Duration(shutdownTime*time.Second) {
		t.Error("Expected graceful shutdown to take longer")
	}
	if duration > time.Duration((shutdownTime+2)*time.Second) {
		t.Error("Looks like graceful shutdown did not complete in expected time? Check.")
	}
}

func TestServiceUngracefulShutdown(t *testing.T) {
	const timeout = 1
	const shutdownTimeout = 5
	const shutdownTime = 20

	c := new(ServiceConfig)
	c.Path = os.Args[0]
	c.Args = helperArgs("work-before-exit", strconv.Itoa(shutdownTime))
	c.GracefulShutdownTimeoutSecs = shutdownTimeout

	terminate := make(chan struct{})
	go func() {
		time.Sleep(timeout * time.Second)
		close(terminate)
	}()

	startingTime := time.Now().UTC()
	err := RunService(c, terminate)
	if err != nil {
		t.Errorf("Error reported from service: %v", err)
	}
	endingTime := time.Now().UTC()

	duration := endingTime.Sub(startingTime)

	if duration <= time.Duration((timeout+shutdownTimeout)*time.Second) {
		t.Error("Expected shutdown to take longer")
	}
	if duration > time.Duration((timeout+shutdownTimeout+2)*time.Second) {
		t.Error("Looks like shutdown did not complete in expected time? Check.")
	}
}

func TestServiceEchoMonitorFailure(t *testing.T) {

	const timeout = 15
	const failTime = 5

	c := new(ServiceConfig)
	c.Path = os.Args[0]
	c.Args = helperArgs("echo-ping-fail-after", strconv.Itoa(failTime))
	c.Logger = logging.NewConsoleLogger()
	c.MaxCrashCount = 1
	c.MonitorPing = &PingConfig{
		URL:                   "echo://127.0.0.1:4300",
		IntervalSecs:          1,
		TimeoutSecs:           3,
		RestartOnFailureCount: 0,
	}

	terminate := make(chan struct{})
	go func() {
		time.Sleep(timeout * time.Second)
		close(terminate)
	}()

	startingTime := time.Now().UTC()
	err := RunService(c, terminate)
	if err == nil {
		t.Errorf("Service should have raised MaxCrashCount error")
	}
	endingTime := time.Now().UTC()

	duration := endingTime.Sub(startingTime)

	if duration < time.Duration(failTime*time.Second) {
		t.Error("Expected test to take longer")
	}
	if duration >= time.Duration(timeout*time.Second) {
		t.Error("Looks like failure detection did not work. Check.")
	}
}

func TestServiceTCPMonitorFailure(t *testing.T) {

	const timeout = 15
	const failTime = 5

	c := new(ServiceConfig)
	c.Path = os.Args[0]
	c.Args = helperArgs("tcp-ping-fail-after", strconv.Itoa(failTime))
	c.Logger = logging.NewConsoleLogger()
	c.MaxCrashCount = 1
	c.MonitorPing = &PingConfig{
		URL:                   "tcp://127.0.0.1:4300",
		IntervalSecs:          1,
		TimeoutSecs:           3,
		RestartOnFailureCount: 0,
	}

	terminate := make(chan struct{})
	go func() {
		time.Sleep(timeout * time.Second)
		close(terminate)
	}()

	startingTime := time.Now().UTC()
	err := RunService(c, terminate)
	if err == nil {
		t.Errorf("Service should have raised MaxCrashCount error")
	}
	endingTime := time.Now().UTC()

	duration := endingTime.Sub(startingTime)

	if duration < time.Duration(failTime*time.Second) {
		t.Error("Expected test to take longer. Check.")
	}
	if duration >= time.Duration(timeout*time.Second) {
		t.Error("Looks like failure detection did not work. Check.")
	}
}

func TestServiceFileMonitorFailure(t *testing.T) {

	const timeout = 15
	const failTime = 5
	const statusFile = "status.file"

	defer os.Remove(statusFile)

	c := new(ServiceConfig)
	c.Path = os.Args[0]
	c.Args = helperArgs("file-ping-fail-after", strconv.Itoa(failTime))
	c.Logger = logging.NewConsoleLogger()
	c.MaxCrashCount = 1
	c.MonitorPing = &PingConfig{
		URL:                   "file://" + statusFile,
		IntervalSecs:          1,
		TimeoutSecs:           3,
		RestartOnFailureCount: 0,
	}

	terminate := make(chan struct{})
	go func() {
		time.Sleep(timeout * time.Second)
		close(terminate)
	}()

	startingTime := time.Now().UTC()
	err := RunService(c, terminate)
	if err == nil {
		t.Errorf("Service should have raised MaxCrashCount error")
	}
	endingTime := time.Now().UTC()

	duration := endingTime.Sub(startingTime)

	if duration < time.Duration(failTime*time.Second) {
		t.Error("Expected test to take longer. Check.")
	}
	if duration >= time.Duration(timeout*time.Second) {
		t.Error("Looks like failure detection did not work. Check.")
	}
}


text:
class API::V1::EmailsAPI < Grape::API
  include Grape::Kaminari

  resource :emails do
    desc 'Gets a list of email objects with pagination and optional search params'
    params do
      optional :q, type: String
      optional :state, type: String
      optional :pending, type: String
      optional :_type, type: String
      optional :vfe, type: Boolean
    end
    paginate
    get do
      ors = []
      ands = []

      if params[:q].present?
        ors << {address: Regexp.new(params[:q].gsub(/\s/, '.*'), Regexp::IGNORECASE)}
        ors << {uuid: params[:q]}
      end

      if params[:state].present?
        ands << {state: params[:state]}
      end

      if params[:pending].present?
        ands << {:'deprovision_schedules.scheduled_for'.ne => nil, 'deprovision_schedules.completed_at' => nil, 'deprovision_schedules.canceled' => nil}
      end

      if params[:_type].present?
        ands << {_type: params[:_type]}
      end

      if params[:vfe].present?
        ands << {vfe: params[:vfe]}
      end

      emails = if ors.any? || ands.any?
        UniversityEmail.or(*ors).and(*ands)
      else
        UniversityEmail.asc(:address)
      end

      present paginate(emails), with: API::V1::UniversityEmailEntity
    end

    desc 'Gets an individual email'
    params do
      requires :id, type: String
    end
    get ':id' do
      email = UniversityEmail.find(params[:id])

      present email, with: API::V1::UniversityEmailEntity
    end
  end
end


text:
using System;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;

namespace CoCo.Test.Common
{
    internal class TextBuffer : ITextBuffer
    {
        public TextBuffer(IContentType contentType, StringOperand source)
        {
            ContentType = contentType;
            CurrentSnapshot = new TextSnapshot(this, new TextVersion(this, new TextImageVersion(source.Length)), source);
        }

        public IContentType ContentType { get; }

        public ITextSnapshot CurrentSnapshot { get; }

        public bool EditInProgress => throw new NotImplementedException();

        public PropertyCollection Properties { get; } = new PropertyCollection();

        public event EventHandler<SnapshotSpanEventArgs> ReadOnlyRegionsChanged;

        public event EventHandler<TextContentChangedEventArgs> Changed;

        public event EventHandler<TextContentChangedEventArgs> ChangedLowPriority;

        public event EventHandler<TextContentChangedEventArgs> ChangedHighPriority;

        public event EventHandler<TextContentChangingEventArgs> Changing;

        public event EventHandler PostChanged;

        public event EventHandler<ContentTypeChangedEventArgs> ContentTypeChanged;

        public void ChangeContentType(IContentType newContentType, object editTag)
        {
            throw new NotImplementedException();
        }

        public bool CheckEditAccess()
        {
            throw new NotImplementedException();
        }

        public ITextEdit CreateEdit(EditOptions options, int? reiteratedVersionNumber, object editTag)
        {
            throw new NotImplementedException();
        }

        public ITextEdit CreateEdit()
        {
            throw new NotImplementedException();
        }

        public IReadOnlyRegionEdit CreateReadOnlyRegionEdit()
        {
            throw new NotImplementedException();
        }

        public ITextSnapshot Delete(Span deleteSpan)
        {
            throw new NotImplementedException();
        }

        public NormalizedSpanCollection GetReadOnlyExtents(Span span)
        {
            throw new NotImplementedException();
        }

        public ITextSnapshot Insert(int position, string text)
        {
            throw new NotImplementedException();
        }

        public bool IsReadOnly(int position) => true;

        public bool IsReadOnly(int position, bool isEdit) => true;

        public bool IsReadOnly(Span span) => true;

        public bool IsReadOnly(Span span, bool isEdit) => true;

        public ITextSnapshot Replace(Span replaceSpan, string replaceWith) => throw new NotImplementedException();

        public void TakeThreadOwnership()
        {
            throw new NotImplementedException();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Orders;

namespace Nop.Services.Catalog
{
    /// <summary>
    /// Product service
    /// </summary>
    public partial interface IProductService
    {
        #region Products

        /// <summary>
        /// Delete a product
        /// </summary>
        /// <param name="product">Product</param>
        void DeleteProduct(Product product);

        /// <summary>
        /// Gets all products displayed on the home page
        /// </summary>
        /// <returns>Product collection</returns>
        IList<Product> GetAllProductsDisplayedOnHomePage();

        /// <summary>
        /// Gets product
        /// </summary>
        /// <param name="productId">Product identifier</param>
        /// <returns>Product</returns>
        Product GetProductById(int productId);

        /// <summary>
        /// Gets products by identifier
        /// </summary>
        /// <param name="productIds">Product identifiers</param>
        /// <returns>Products</returns>
        IList<Product> GetProductsByIds(int[] productIds);

        /// <summary>
        /// Inserts a product
        /// </summary>
        /// <param name="product">Product</param>
        void InsertProduct(Product product);

        /// <summary>
        /// Updates the product
        /// </summary>
        /// <param name="product">Product</param>
        void UpdateProduct(Product product);

        /// <summary>
        /// Get (visible) product number in certain category
        /// </summary>
        /// <param name="categoryIds">Category identifiers</param>
        /// <param name="storeId">Store identifier; 0 to load all records</param>
        /// <returns>Product number</returns>
        int GetCategoryProductNumber(IList<int> categoryIds = null, int storeId = 0);

        /// <summary>
        /// Search products
        /// </summary>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="categoryIds">Category identifiers</param>
        /// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
        /// <param name="storeId">Store identifier; 0 to load all records</param>
        /// <param name="vendorId">Vendor identifier; 0 to load all records</param>
        /// <param name="warehouseId">Warehouse identifier; 0 to load all records</param>
        /// <param name="parentGroupedProductId">Parent product identifier (used with grouped products); 0 to load all records</param>
        /// <param name="productType">Product type; 0 to load all records</param>
        /// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>
        /// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers). 0 to load featured products only, 1 to load not featured products only, null to load all products</param>
        /// <param name="priceMin">Minimum price; null to load all records</param>
        /// <param name="priceMax">Maximum price; null to load all records</param>
        /// <param name="productTagId">Product tag identifier; 0 to load all records</param>
        /// <param name="keywords">Keywords</param>
        /// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
        /// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
        /// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
        /// <param name="languageId">Language identifier (search for text searching)</param>
        /// <param name="filteredSpecs">Filtered product specification identifiers</param>
        /// <param name="orderBy">Order by</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Products</returns>
        IPagedList<Product> SearchProducts(
            int pageIndex = 0,
            int pageSize = int.MaxValue,
            IList<int> categoryIds = null,
            int manufacturerId = 0,
            int storeId = 0,
            int vendorId = 0,
            int warehouseId = 0,
            int parentGroupedProductId = 0,
            ProductType? productType = null,
            bool visibleIndividuallyOnly = false,
            bool? featuredProducts = null,
            decimal? priceMin = null,
            decimal? priceMax = null,
            int productTagId = 0,
            string keywords = null,
            bool searchDescriptions = false,
            bool searchSku = true,
            bool searchProductTags = false,
            int languageId = 0,
            IList<int> filteredSpecs = null,
            ProductSortingEnum orderBy = ProductSortingEnum.Position,
            bool showHidden = false);

        /// <summary>
        /// Search products
        /// </summary>
        /// <param name="filterableSpecificationAttributeOptionIds">The specification attribute option identifiers applied to loaded products (all pages)</param>
        /// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="categoryIds">Category identifiers</param>
        /// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
        /// <param name="storeId">Store identifier; 0 to load all records</param>
        /// <param name="vendorId">Vendor identifier; 0 to load all records</param>
        /// <param name="warehouseId">Warehouse identifier; 0 to load all records</param>
        /// <param name="parentGroupedProductId">Parent product identifier (used with grouped products); 0 to load all records</param>
        /// <param name="productType">Product type; 0 to load all records</param>
        /// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>
        /// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers). 0 to load featured products only, 1 to load not featured products only, null to load all products</param>
        /// <param name="priceMin">Minimum price; null to load all records</param>
        /// <param name="priceMax">Maximum price; null to load all records</param>
        /// <param name="productTagId">Product tag identifier; 0 to load all records</param>
        /// <param name="keywords">Keywords</param>
        /// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
        /// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
        /// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
        /// <param name="languageId">Language identifier (search for text searching)</param>
        /// <param name="filteredSpecs">Filtered product specification identifiers</param>
        /// <param name="orderBy">Order by</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Products</returns>
        IPagedList<Product> SearchProducts(
            out IList<int> filterableSpecificationAttributeOptionIds,
            bool loadFilterableSpecificationAttributeOptionIds = false,
            int pageIndex = 0,
            int pageSize = int.MaxValue,
            IList<int> categoryIds = null,
            int manufacturerId = 0,
            int storeId = 0,
            int vendorId = 0,
            int warehouseId = 0,
            int parentGroupedProductId = 0,
            ProductType? productType = null,
            bool visibleIndividuallyOnly = false,
            bool? featuredProducts = null,
            decimal? priceMin = null,
            decimal? priceMax = null,
            int productTagId = 0,
            string keywords = null,
            bool searchDescriptions = false,
            bool searchSku = true,
            bool searchProductTags = false,
            int languageId = 0,
            IList<int> filteredSpecs = null,
            ProductSortingEnum orderBy = ProductSortingEnum.Position,
            bool showHidden = false);

        /// <summary>
        /// Gets associated products
        /// </summary>
        /// <param name="parentGroupedProductId">Parent product identifier (used with grouped products)</param>
        /// <param name="storeId">Store identifier; 0 to load all records</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Products</returns>
        IList<Product> GetAssociatedProducts(int parentGroupedProductId,
            int storeId = 0, bool showHidden = false);

        /// <summary>
        /// Update product review totals
        /// </summary>
        /// <param name="product">Product</param>
        void UpdateProductReviewTotals(Product product);

        /// <summary>
        /// Get low stock products
        /// </summary>
        /// <param name="vendorId">Vendor identifier; 0 to load all records</param>
        /// <param name="products">Low stock products</param>
        /// <param name="combinations">Low stock  attribute combinations</param>
        void GetLowStockProducts(int vendorId,
            out IList<Product> products,
            out IList<ProductVariantAttributeCombination> combinations);

        /// <summary>
        /// Gets a product by SKU
        /// </summary>
        /// <param name="sku">SKU</param>
        /// <returns>Product</returns>
        Product GetProductBySku(string sku);

        /// <summary>
        /// Adjusts inventory
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="decrease">A value indicating whether to increase or descrease product stock quantity</param>
        /// <param name="quantity">Quantity</param>
        /// <param name="attributesXml">Attributes in XML format</param>
        void AdjustInventory(Product product, bool decrease,
            int quantity, string attributesXml);

        /// <summary>
        /// Update HasTierPrices property (used for performance optimization)
        /// </summary>
        /// <param name="product">Product</param>
        void UpdateHasTierPricesProperty(Product product);

        /// <summary>
        /// Update HasDiscountsApplied property (used for performance optimization)
        /// </summary>
        /// <param name="product">Product</param>
        void UpdateHasDiscountsApplied(Product product);

        #endregion

        #region Related products

        /// <summary>
        /// Deletes a related product
        /// </summary>
        /// <param name="relatedProduct">Related product</param>
        void DeleteRelatedProduct(RelatedProduct relatedProduct);

        /// <summary>
        /// Gets a related product collection by product identifier
        /// </summary>
        /// <param name="productId1">The first product identifier</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Related product collection</returns>
        IList<RelatedProduct> GetRelatedProductsByProductId1(int productId1, bool showHidden = false);

        /// <summary>
        /// Gets a related product
        /// </summary>
        /// <param name="relatedProductId">Related product identifier</param>
        /// <returns>Related product</returns>
        RelatedProduct GetRelatedProductById(int relatedProductId);

        /// <summary>
        /// Inserts a related product
        /// </summary>
        /// <param name="relatedProduct">Related product</param>
        void InsertRelatedProduct(RelatedProduct relatedProduct);

        /// <summary>
        /// Updates a related product
        /// </summary>
        /// <param name="relatedProduct">Related product</param>
        void UpdateRelatedProduct(RelatedProduct relatedProduct);

        #endregion

        #region Cross-sell products

        /// <summary>
        /// Deletes a cross-sell product
        /// </summary>
        /// <param name="crossSellProduct">Cross-sell</param>
        void DeleteCrossSellProduct(CrossSellProduct crossSellProduct);

        /// <summary>
        /// Gets a cross-sell product collection by product identifier
        /// </summary>
        /// <param name="productId1">The first product identifier</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Cross-sell product collection</returns>
        IList<CrossSellProduct> GetCrossSellProductsByProductId1(int productId1, bool showHidden = false);

        /// <summary>
        /// Gets a cross-sell product
        /// </summary>
        /// <param name="crossSellProductId">Cross-sell product identifier</param>
        /// <returns>Cross-sell product</returns>
        CrossSellProduct GetCrossSellProductById(int crossSellProductId);

        /// <summary>
        /// Inserts a cross-sell product
        /// </summary>
        /// <param name="crossSellProduct">Cross-sell product</param>
        void InsertCrossSellProduct(CrossSellProduct crossSellProduct);

        /// <summary>
        /// Updates a cross-sell product
        /// </summary>
        /// <param name="crossSellProduct">Cross-sell product</param>
        void UpdateCrossSellProduct(CrossSellProduct crossSellProduct);

        /// <summary>
        /// Gets a cross-sells
        /// </summary>
        /// <param name="cart">Shopping cart</param>
        /// <param name="numberOfProducts">Number of products to return</param>
        /// <returns>Cross-sells</returns>
        IList<Product> GetCrosssellProductsByShoppingCart(IList<ShoppingCartItem> cart, int numberOfProducts);

        #endregion

        #region Tier prices

        /// <summary>
        /// Deletes a tier price
        /// </summary>
        /// <param name="tierPrice">Tier price</param>
        void DeleteTierPrice(TierPrice tierPrice);

        /// <summary>
        /// Gets a tier price
        /// </summary>
        /// <param name="tierPriceId">Tier price identifier</param>
        /// <returns>Tier price</returns>
        TierPrice GetTierPriceById(int tierPriceId);

        /// <summary>
        /// Inserts a tier price
        /// </summary>
        /// <param name="tierPrice">Tier price</param>
        void InsertTierPrice(TierPrice tierPrice);

        /// <summary>
        /// Updates the tier price
        /// </summary>
        /// <param name="tierPrice">Tier price</param>
        void UpdateTierPrice(TierPrice tierPrice);

        #endregion

        #region Product pictures

        /// <summary>
        /// Deletes a product picture
        /// </summary>
        /// <param name="productPicture">Product picture</param>
        void DeleteProductPicture(ProductPicture productPicture);

        /// <summary>
        /// Gets a product pictures by product identifier
        /// </summary>
        /// <param name="productId">The product identifier</param>
        /// <returns>Product pictures</returns>
        IList<ProductPicture> GetProductPicturesByProductId(int productId);

        /// <summary>
        /// Gets a product picture
        /// </summary>
        /// <param name="productPictureId">Product picture identifier</param>
        /// <returns>Product picture</returns>
        ProductPicture GetProductPictureById(int productPictureId);

        /// <summary>
        /// Inserts a product picture
        /// </summary>
        /// <param name="productPicture">Product picture</param>
        void InsertProductPicture(ProductPicture productPicture);

        /// <summary>
        /// Updates a product picture
        /// </summary>
        /// <param name="productPicture">Product picture</param>
        void UpdateProductPicture(ProductPicture productPicture);

        #endregion

        #region Product reviews

        /// <summary>
        /// Gets all product reviews
        /// </summary>
        /// <param name="customerId">Customer identifier; 0 to load all records</param>
        /// <param name="approved">A value indicating whether to content is approved; null to load all records</param>
        /// <param name="fromUtc">Item creation from; null to load all records</param>
        /// <param name="toUtc">Item item creation to; null to load all records</param>
        /// <param name="message">Search title or review text; null to load all records</param>
        /// <returns>Reviews</returns>
        IList<ProductReview> GetAllProductReviews(int customerId, bool? approved,
            DateTime? fromUtc = null, DateTime? toUtc = null,
            string message = null);

        /// <summary>
        /// Gets product review
        /// </summary>
        /// <param name="productReviewId">Product review identifier</param>
        /// <returns>Product review</returns>
        ProductReview GetProductReviewById(int productReviewId);

        /// <summary>
        /// Deletes a product review
        /// </summary>
        /// <param name="productReview">Product review</param>
        void DeleteProductReview(ProductReview productReview);

        #endregion
    }
}


text:
<?php

namespace BusinessLogic\Tickets;

use DataAccess\Tickets\VerifiedEmailGateway;
use PHPUnit\Framework\TestCase;

class VerifiedEmailCheckerTest extends TestCase {
    /**
     * @var $verifiedEmailGateway \PHPUnit_Framework_MockObject_MockObject
     */
    private $verifiedEmailGateway;

    /**
     * @var $verifiedEmailChecker VerifiedEmailChecker
     */
    private $verifiedEmailChecker;

    /**
     * @var $heskSettings array
     */
    private $heskSettings;

    protected function setUp(): void {
        $this->verifiedEmailGateway = $this->createMock(VerifiedEmailGateway::clazz());
        $this->heskSettings = array();
        $this->verifiedEmailChecker = new VerifiedEmailChecker($this->verifiedEmailGateway);
    }

    function testItGetsTheValidationStateFromTheGatewayWhenItItTrue() {
        //-- Arrange
        $this->verifiedEmailGateway->method('isEmailVerified')
            ->with('some email', $this->heskSettings)
            ->willReturn(true);

        //-- Act
        $actual = $this->verifiedEmailChecker->isEmailVerified('some email', $this->heskSettings);

        //-- Assert
        self::assertThat($actual, self::isTrue());
    }

    function testItGetsTheValidationStateFromTheGatewayWhenItItFalse() {
        //-- Arrange
        $this->verifiedEmailGateway->method('isEmailVerified')
            ->with('some email', $this->heskSettings)
            ->willReturn(false);

        //-- Act
        $actual = $this->verifiedEmailChecker->isEmailVerified('some email', $this->heskSettings);

        //-- Assert
        self::assertThat($actual, self::isFalse());
    }
}