text:
<?php

namespace iFixit\Matryoshka;

use iFixit\Matryoshka;

/**
 * A convenience class for making wrapping backends who's functions fall
 * through to the underlying backend when they aren't implemented.
 *
 * Makes it easier to implement one or two of the functions without having to
 * do all of them.
 */
abstract class BackendWrap extends Backend {
   protected $backend;

   public function __construct(Backend $backend) {
      $this->backend = $backend;
   }

   public function set($key, $value, $expiration = 0) {
      return $this->backend->set($key, $value, $expiration);
   }

   public function setMultiple(array $values, $expiration = 0) {
      return $this->backend->setMultiple($values, $expiration);
   }

   public function add($key, $value, $expiration = 0) {
      return $this->backend->add($key, $value, $expiration);
   }

   public function increment($key, $amount = 1, $expiration = 0) {
      return $this->backend->increment($key, $amount, $expiration);
   }

   public function decrement($key, $amount = 1, $expiration = 0) {
      return $this->backend->decrement($key, $amount, $expiration);
   }

   public function get($key) {
      return $this->backend->get($key);
   }

   public function getMultiple(array $keys) {
      return $this->backend->getMultiple($keys);
   }

   public function delete($key) {
      return $this->backend->delete($key);
   }

   public function deleteMultiple(array $keys) {
      return $this->backend->deleteMultiple($keys);
   }

   public function getAbsoluteKey($key) {
      return $this->backend->getAbsoluteKey($key);
   }
}

redpajama_set_name: RedPajamaGithub


text:
package bitbucketpullrequestbuilder.bitbucketpullrequestbuilder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import bitbucketpullrequestbuilder.bitbucketpullrequestbuilder.bitbucket.BitbucketApiClient;
import bitbucketpullrequestbuilder.bitbucketpullrequestbuilder.bitbucket.BitbucketPullRequestComment;
import bitbucketpullrequestbuilder.bitbucketpullrequestbuilder.bitbucket.BitbucketPullRequestResponseValue;
import bitbucketpullrequestbuilder.bitbucketpullrequestbuilder.bitbucket.BitbucketPullRequestResponseValueRepository;

/**
 * Created by nishio
 */
public class BitbucketRepository {
    private static final Logger logger = Logger.getLogger(BitbucketRepository.class.getName());
    public static final String BUILD_START_MARKER = "[*BuildStarted* **%s**] %s into %s";
    public static final String BUILD_FINISH_MARKER = "[*BuildFinished* **%s**] %s into %s";

    public static final String BUILD_START_REGEX = "\\[\\*BuildStarted\\* \\*\\*%s\\*\\*\\] ([0-9a-fA-F]+) into ([0-9a-fA-F]+)";
    public static final String BUILD_FINISH_REGEX = "\\[\\*BuildFinished\\* \\*\\*%s\\*\\*\\] ([0-9a-fA-F]+) into ([0-9a-fA-F]+)";

    public static final String BUILD_FINISH_SENTENCE = BUILD_FINISH_MARKER + " \n\n **%s** - %s";
    public static final String BUILD_REQUEST_MARKER = "test this please";

    public static final String BUILD_SUCCESS_COMMENT =  "SUCCESS";
    public static final String BUILD_FAILURE_COMMENT = "FAILURE";
    private String projectPath;
    private BitbucketPullRequestsBuilder builder;
    private BitbucketBuildTrigger trigger;
    private BitbucketApiClient client;

    public BitbucketRepository(String projectPath, BitbucketPullRequestsBuilder builder) {
        this.projectPath = projectPath;
        this.builder = builder;
    }

    public void init() {
        trigger = this.builder.getTrigger();
        client = new BitbucketApiClient(
                trigger.getUsername(),
                trigger.getPassword(),
                trigger.getRepositoryOwner(),
                trigger.getRepositoryName());
    }

    public Collection<BitbucketPullRequestResponseValue> getTargetPullRequests() {
        logger.info("Fetch PullRequests.");
        List<BitbucketPullRequestResponseValue> pullRequests = client.getPullRequests();
        List<BitbucketPullRequestResponseValue> targetPullRequests = new ArrayList<BitbucketPullRequestResponseValue>();
        for(BitbucketPullRequestResponseValue pullRequest : pullRequests) {
            if (isBuildTarget(pullRequest)) {
                targetPullRequests.add(pullRequest);
            }
        }
        return targetPullRequests;
    }

    public String postBuildStartCommentTo(BitbucketPullRequestResponseValue pullRequest) {
            String sourceCommit = pullRequest.getSource().getCommit().getHash();
            String destinationCommit = pullRequest.getDestination().getCommit().getHash();
            String comment = String.format(BUILD_START_MARKER, builder.getProject().getDisplayName(), sourceCommit, destinationCommit);
            BitbucketPullRequestComment commentResponse = this.client.postPullRequestComment(pullRequest.getId(), comment);
            return commentResponse.getCommentId().toString();
    }

    public void addFutureBuildTasks(Collection<BitbucketPullRequestResponseValue> pullRequests) {
        for(BitbucketPullRequestResponseValue pullRequest : pullRequests) {
            String commentId = "";
            if ( this.trigger.getPostPRComment()) {
              commentId = postBuildStartCommentTo(pullRequest);
            }
            if ( this.trigger.getApproveIfSuccess() ) {
                deletePullRequestApproval(pullRequest.getId());
            }
            BitbucketCause cause = new BitbucketCause(
                    pullRequest.getSource().getBranch().getName(),
                    pullRequest.getDestination().getBranch().getName(),
                    pullRequest.getSource().getRepository().getOwnerName(),
                    pullRequest.getSource().getRepository().getRepositoryName(),
                    pullRequest.getId(),
                    pullRequest.getDestination().getRepository().getOwnerName(),
                    pullRequest.getDestination().getRepository().getRepositoryName(),
                    pullRequest.getTitle(),
                    pullRequest.getSource().getCommit().getHash(),
                    pullRequest.getDestination().getCommit().getHash(),
                    commentId);
            this.builder.getTrigger().startJob(cause);
        }
    }

    public void deletePullRequestComment(String pullRequestId, String commentId) {
        this.client.deletePullRequestComment(pullRequestId,commentId);
    }

    public void postFinishedComment(String pullRequestId, String sourceCommit,  String destinationCommit, boolean success, String buildUrl) {
        String message = BUILD_FAILURE_COMMENT;
        if (success){
            message = BUILD_SUCCESS_COMMENT;
        }
        String comment = String.format(BUILD_FINISH_SENTENCE, builder.getProject().getDisplayName(), sourceCommit, destinationCommit, message, buildUrl);

        this.client.postPullRequestComment(pullRequestId, comment);
    }

    public void deletePullRequestApproval(String pullRequestId) {
        this.client.deletePullRequestApproval(pullRequestId);
    }

    public void postPullRequestApproval(String pullRequestId) {
        this.client.postPullRequestApproval(pullRequestId);
    }

    private boolean isBuildTarget(BitbucketPullRequestResponseValue pullRequest) {

        boolean shouldBuild = true;
        if (pullRequest.getState() != null && pullRequest.getState().equals("OPEN")) {
            if (isSkipBuild(pullRequest.getTitle())) {
                return false;
            }

            String sourceCommit = pullRequest.getSource().getCommit().getHash();

            BitbucketPullRequestResponseValueRepository destination = pullRequest.getDestination();
            String owner = destination.getRepository().getOwnerName();
            String repositoryName = destination.getRepository().getRepositoryName();
            String destinationCommit = destination.getCommit().getHash();

            String id = pullRequest.getId();
            List<BitbucketPullRequestComment> comments = client.getPullRequestComments(owner, repositoryName, id);

            if (comments != null) {
                Collections.sort(comments);
                Collections.reverse(comments);
                for (BitbucketPullRequestComment comment : comments) {
                    String content = comment.getContent();
                    if (content == null || content.isEmpty()) {
                        continue;
                    }

                    //These will match any start or finish message -- need to check commits
                    String project_build_start = String.format(BUILD_START_REGEX, builder.getProject().getDisplayName());
                    String project_build_finished = String.format(BUILD_FINISH_REGEX, builder.getProject().getDisplayName());
                    Matcher startMatcher = Pattern.compile(project_build_start, Pattern.CASE_INSENSITIVE).matcher(content);
                    Matcher finishMatcher = Pattern.compile(project_build_finished, Pattern.CASE_INSENSITIVE).matcher(content);

                    if (startMatcher.find() ||
                        finishMatcher.find()) {

                        String sourceCommitMatch;
                        String destinationCommitMatch;

                        if (startMatcher.find(0)) {
                            sourceCommitMatch = startMatcher.group(1);
                            destinationCommitMatch = startMatcher.group(2);
                        } else {
                            sourceCommitMatch = finishMatcher.group(1);
                            destinationCommitMatch = finishMatcher.group(2);
                        }

                        //first check source commit -- if it doesn't match, just move on. If it does, investigate further.
                        if (sourceCommitMatch.equalsIgnoreCase(sourceCommit)) {
                            // if we're checking destination commits, and if this doesn't match, then move on.
                            if (this.trigger.getCheckDestinationCommit()
                                    && (!destinationCommitMatch.equalsIgnoreCase(destinationCommit))) {
                            	continue;
                            }

                            shouldBuild = false;
                            break;
                        }
                    }

                    if (content.contains(BUILD_REQUEST_MARKER.toLowerCase())) {
                        shouldBuild = true;
                        break;
                    }
                }
            }
        }
        return shouldBuild;
    }

    private boolean isSkipBuild(String pullRequestTitle) {
        String skipPhrases = this.trigger.getCiSkipPhrases();
        if (skipPhrases != null && !"".equals(skipPhrases)) {
            String[] phrases = skipPhrases.split(",");
            for(String phrase : phrases) {
                if (pullRequestTitle.toLowerCase().contains(phrase.trim().toLowerCase())) {
                    return true;
                }
            }
        }
        return false;
    }
}


text:
package it.hysen.springmvc.configuration;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CORSFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
	        throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers",
		        "X-Requested-with, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");
		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig filterConfig) {
	}

}


text:
<?php

namespace Oro\Bundle\OrganizationBundle\Event;

use Oro\Bundle\EntityConfigBundle\Config\ConfigManager;
use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Oro\Bundle\EntityConfigBundle\Event\PersistConfigEvent;
use Oro\Bundle\EntityConfigBundle\Event\Events;

class ConfigSubscriber implements EventSubscriberInterface
{
    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            Events::PRE_PERSIST_CONFIG => ['prePersistEntityConfig', 100]
        ];
    }

    /**
     * @param PersistConfigEvent $event
     */
    public function prePersistEntityConfig(PersistConfigEvent $event)
    {
        $className               = $event->getConfig()->getId()->getClassName();
        $configManager           = $event->getConfigManager();
        $ownershipConfigProvider = $configManager->getProvider('ownership');
        if ($ownershipConfigProvider->hasConfig($className)) {
            $ownershipConfig = $ownershipConfigProvider->getConfig($className);
            $ownerType       = $ownershipConfig->get('owner_type');
            if ($ownerType === 'NONE') {
                $ownerType = null;
                $ownershipConfig->remove('owner_type');
                $configManager->persist($ownershipConfig);
                $configManager->calculateConfigChangeSet($ownershipConfig);
            }
            if ($ownerType
                && !$ownershipConfig->has('owner_field_name')
                && $this->isCustomEntity($className, $configManager)
            ) {
                // update 'ownership' config for entity
                $ownershipConfig->set('owner_field_name', 'owner');
                $ownershipConfig->set('owner_column_name', 'owner_id');
                $configManager->persist($ownershipConfig);
                $configManager->calculateConfigChangeSet($ownershipConfig);
            }
        }
    }

    /**
     * @param string        $className
     * @param ConfigManager $configManager
     * @return bool
     */
    protected function isCustomEntity($className, ConfigManager $configManager)
    {
        $extendConfigProvider = $configManager->getProvider('extend');
        if ($extendConfigProvider->hasConfig($className)) {
            $extendConfig = $extendConfigProvider->getConfig($className);
            if ($extendConfig->is('owner', ExtendScope::OWNER_CUSTOM)) {
                return true;
            }
        }

        return false;
    }
}


text:
package io.vertx.ext.apex.handler.sockjs;

import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;

/**
 * Specify a match to allow for inbound and outbound traffic using the
 * {@link io.vertx.ext.apex.handler.sockjs.BridgeOptions}.
 *
 * @author Julien Viet
 */
@DataObject
public class PermittedOptions {

  /**
   * The default permission address : {@code null}.
   */
  public static String DEFAULT_ADDRESS = null;

  /**
   * The default permission address regex : {@code null}.
   */
  public static String DEFAULT_ADDRESS_REGEX = null;

  /**
   * The default permission required role : {@code null}.
   */
  public static String DEFAULT_REQUIRED_ROLE = null;

  /**
   * The default permission required permission : {@code null}.
   */
  public static String DEFAULT_REQUIRED_PERMISSION = null;

  /**
   * The default permission match : {@code null}.
   */
  public static JsonObject DEFAULT_MATCH = null;

  private String address;
  private String addressRegex;
  private String requiredRole;
  private String requiredPermission;
  private JsonObject match;

  public PermittedOptions() {
  }

  public PermittedOptions(PermittedOptions that) {
    address = that.address;
    addressRegex = that.addressRegex;
    requiredRole = that.requiredRole;
    requiredPermission = that.requiredPermission;
    match = that.match != null ? new JsonObject(that.match.encode()) : null;
  }

  public PermittedOptions(JsonObject json) {
    address = json.getString("address", DEFAULT_ADDRESS);
    addressRegex = json.getString("addressRegex", DEFAULT_ADDRESS_REGEX);
    requiredRole = json.getString("requiredRole", DEFAULT_REQUIRED_ROLE);
    requiredPermission = json.getString("requiredPermission", DEFAULT_REQUIRED_PERMISSION);
    match = json.getJsonObject("match", DEFAULT_MATCH);
  }

  public String getAddress() {
    return address;
  }

  /**
   * The exact address the message is being sent to. If you want to allow messages based on
   * an exact address you use this field.
   *
   * @param address the address
   * @return a reference to this, so the API can be used fluently
   */
  public PermittedOptions setAddress(String address) {
    this.address = address;
    return this;
  }

  public String getAddressRegex() {
    return addressRegex;
  }

  /**
   * A regular expression that will be matched against the address. If you want to allow messages
   * based on a regular expression you use this field. If the {@link #setAddress} value is specified
   * this will be ignored.
   *
   * @param addressRegex the address regex
   * @return a reference to this, so the API can be used fluently
   */
  public PermittedOptions setAddressRegex(String addressRegex) {
    this.addressRegex = addressRegex;
    return this;
  }

  public String getRequiredRole() {
    return requiredRole;
  }

  /**
   * Declare a specific role for the logged-in user is required in order to access allow the messages.
   *
   * @param requiredRole the role
   * @return a reference to this, so the API can be used fluently
   */
  public PermittedOptions setRequiredRole(String requiredRole) {
    this.requiredRole = requiredRole;
    return this;
  }

  public String getRequiredPermission() {
    return requiredPermission;
  }

  /**
   * Declare a specific permission for the logged-in user is required in order to access allow the messages;
   *
   * @param requiredPermission the permission
   * @return a reference to this, so the API can be used fluently
   */
  public PermittedOptions setRequiredPermission(String requiredPermission) {
    this.requiredPermission = requiredPermission;
    return this;
  }

  public JsonObject getMatch() {
    return match;
  }

  /**
   * This allows you to allow messages based on their structure. Any fields in the match must exist in the
   * message with the same values for them to be allowed. This currently only works with JSON messages.
   *
   * @param match the match json object
   * @return a reference to this, so the API can be used fluently
   */
  public PermittedOptions setMatch(JsonObject match) {
    this.match = match;
    return this;
  }
}


text:
namespace AdventureWorks.Repository.Test.Repository.Production
{
    using EntityClasses.Production;
    using Main;
    using NUnit.Framework;

    [TestFixture]
    [Category("Production")]
    public class ProductDocumentRepositoryTest : BaseRepositoryTest<ProductDocument, ProductDocumentRepositoryTest>
    {
        public override System.Linq.Expressions.Expression<System.Func<ProductDocument, bool>> SearchForExpresion()
        {
            throw new System.NotImplementedException();
        }

        public override void BaseSearchForAsserts(System.Collections.Generic.IList<ProductDocument> input)
        {
            throw new System.NotImplementedException();
        }

        [Test]
        [Order(1)]
        public void ProductDocumentRepositoryTest_Insert()
        {
            BaseInsert();
        }

        [Test]
        [Order(2)]
        public void ProductDocumentRepositoryTest_GetById()
        {
            BaseGetById();
        }

        [Test]
        [Order(3)]
        public void ProductDocumentRepositoryTest_SearchFor()
        {
            BaseSearchFor();
        }

        [Test]
        [Order(4)]
        public void ProductDocumentRepositoryTest_GetAll()
        {
            BaseGetAll();
        }

        [Test]
        [Order(5)]
        public void ProductDocumentRepositoryTest_Delete()
        {
            BaseDelete();
        }
    }
}


text:
#ifdef LIBVA_ANDROID_SUPPORT
#ifdef ANDROID

#include "vaapi_utils_android.h"

CLibVA* CreateLibVA(int)
{
    return new AndroidLibVA;
}

/*------------------------------------------------------------------------------*/

typedef unsigned int vaapiAndroidDisplay;

#define VAAPI_ANDROID_DEFAULT_DISPLAY 0x18c34078

AndroidLibVA::AndroidLibVA(void)
    : CLibVA(MFX_LIBVA_AUTO)
    , m_display(NULL)
{
    VAStatus va_res = VA_STATUS_SUCCESS;
    mfxStatus sts = MFX_ERR_NONE;
    int major_version = 0, minor_version = 0;
    vaapiAndroidDisplay* display = NULL;

    m_display = display = (vaapiAndroidDisplay*)malloc(sizeof(vaapiAndroidDisplay));
    if (NULL == m_display) sts = MFX_ERR_NOT_INITIALIZED;
    else *display = VAAPI_ANDROID_DEFAULT_DISPLAY;

    if (MFX_ERR_NONE == sts)
    {
        m_va_dpy = vaGetDisplay(m_display);
        if (!m_va_dpy)
        {
            free(m_display);
            sts = MFX_ERR_NULL_PTR;
        }
    }
    if (MFX_ERR_NONE == sts)
    {
        va_res = vaInitialize(m_va_dpy, &major_version, &minor_version);
        sts = va_to_mfx_status(va_res);
        if (MFX_ERR_NONE != sts)
        {
            free(display);
            m_display = NULL;
        }
    }
    if (MFX_ERR_NONE != sts) throw std::bad_alloc();
}

AndroidLibVA::~AndroidLibVA(void)
{
    if (m_va_dpy)
    {
        vaTerminate(m_va_dpy);
    }
    if (m_display)
    {
        free(m_display);
    }
}

#endif // #ifdef ANDROID
#endif // #ifdef LIBVA_ANDROID_SUPPORT


text:
/**
 * Partial Rhino implementation of Node.js' `os` module.
 * @module os
 * @author Jeff Williams <jeffrey.l.williams@gmail.com>
 * @see http://nodejs.org/api/os.html
 */

exports.EOL = java.lang.System.getProperty('line.separator') + '';


text:
package rs.tickettracker.validation;

import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import rs.tickettracker.R;

/**
 * Validate text fields that need to be entered. Checking isRequired, MaxLength, isDecimal, etc...
 */
public class Validator implements TextWatcher {
    private EditText inputField;
    private View view;
    private TextInputLayout ticketName, posibleGain;

    public Validator(View view, EditText inputField) {
        this.inputField = inputField;
        this.view = view;
        this.ticketName = (TextInputLayout) view.findViewById(R.id.input_ticket_name);
        this.posibleGain = (TextInputLayout) view.findViewById(R.id.input_posible_gain);
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    /**
     * On each text entered validate max length.
     * @param editable - field that need to be checked.
     */
    public void afterTextChanged(Editable editable) {
        if (validateRequired(inputField.getText().toString())) {
            switch (inputField.getId()) {
                case R.id.add_ticket_name:
                    validateMaxLength(inputField.getText().toString());
                    break;
            }
        }
    }

    /**
     * Validate if current value is empty.
     * @param value - value to be checked
     * @return True if value is NOT empty.
     */
    private boolean validateRequired(String value) {
        if (value.trim().isEmpty()) {
            switch (inputField.getId()) {
                case R.id.add_ticket_name:
                    ticketName.setError(view.getResources().getString(R.string.error_msg_required));
                    ticketName.requestFocus();
                    break;
                case R.id.add_ticket_gain:
                    posibleGain.setError(view.getResources().getString(R.string.error_msg_required));
                    posibleGain.requestFocus();
                    break;
            }
            return false;
        } else {
            switch (inputField.getId()) {
                case R.id.add_ticket_name:
                    ticketName.setErrorEnabled(false);
                    break;
                case R.id.add_ticket_gain:
                    posibleGain.setErrorEnabled(false);
                    break;
            }
        }
        return true;
    }

    /**
     * Validate max length of value.
     * @param value - value to be checked
     * @return True if length of value is lower than 30.
     */
    private boolean validateMaxLength(String value) {
        if (value.length() > 30) {
            ticketName.setError(view.getResources().getString(R.string.error_msg_max_length));
            ticketName.requestFocus();
            return false;
        } else {
            ticketName.setErrorEnabled(false);
        }
        return true;
    }
}


text:
namespace dukat
{
	class DiamondSquareGenerator : public HeightMapGenerator
	{
	private:
		int seed;
		float roughness;
		float min_val, max_val; // range of output values [0..1]

		void divide(HeightMap::Level& level, int size) const;
		void square(HeightMap::Level& level, int x, int y, int size, float offset) const;
		void diamond(HeightMap::Level& level, int x, int y, int size, float offset) const;

	public:
		DiamondSquareGenerator(int seed = 0) : seed(seed), min_val(0.0f), max_val(1.0f) { }
		~DiamondSquareGenerator(void) { }

		void generate(HeightMap::Level& level) const;

		void set_roughness(float roughness) { this->roughness = roughness; }
		void set_range(float min_val, float max_val) { this->min_val = min_val; this->max_val = max_val; }
	};
}


text:
ObjectDetector::ObjectDetector(
	const string &cascadePath,
	double scaleFactor,
	int    minNeighbors,
	Size   minSize,
	Size   maxSize) :
	scaleFactor(scaleFactor),
	minNeighbors(minNeighbors),
	minSize(minSize),
	maxSize(maxSize) {

	try {

		cascade.load(cascadePath);
	}
	catch (cv::Exception e) {}

	if (cascade.empty()) {

		cerr << "ERROR: Couldn't load Face Detector (";
		cerr << cascadePath << ")!" << endl;
		exit(1);
	}
}

ObjectDetector::~ObjectDetector() {}

bool ObjectDetector::detectObjects(const Mat &image, vector<Rect> &objects, int cascadeMode) {

	Mat image_gray = image.clone();

	objects.clear();

	if (image_gray.channels() == 3) {

		cvtColor(image_gray, image_gray, CV_BGR2GRAY);
	}
	else if (image_gray.channels() == 4) {

		cvtColor(image_gray, image_gray, CV_BGRA2GRAY);
	}

	equalizeHist(image_gray, image_gray);

	cascade.detectMultiScale(image_gray, objects, scaleFactor, minNeighbors, cascadeMode,
		minSize, maxSize);

	if (objects.size() > 0) {

		return true;
	}
	else {

		return false;
	}
}

bool ObjectDetector::detectLargestObject(const Mat &image, Point &center) {

	Mat image_gray = image.clone();

	if (image_gray.channels() == 3) {

		cvtColor(image_gray, image_gray, CV_BGR2GRAY);
	}
	else if (image_gray.channels() == 4) {

		cvtColor(image_gray, image_gray, CV_BGRA2GRAY);
	}

	equalizeHist(image_gray, image_gray);

	vector<Rect> objects;

	detectObjects(image_gray, objects, CASCADE_FIND_BIGGEST_OBJECT);

	if (objects.size() > 0) {

		center = Point(objects[0].x + objects[0].width / 2, objects[0].y + objects[0].height / 2);

		return true;
	}
	else {

		center = Point(-1, -1);

		return false;
	}
}

bool ObjectDetector::detectLargestObject(const Mat &image, Rect &object) {

	Mat image_gray = image.clone();

	if (image_gray.channels() == 3) {

		cvtColor(image_gray, image_gray, CV_BGR2GRAY);
	}
	else if (image_gray.channels() == 4) {

		cvtColor(image_gray, image_gray, CV_BGRA2GRAY);
	}

	equalizeHist(image_gray, image_gray);

	vector<Rect> objects;

	detectObjects(image_gray, objects, CASCADE_FIND_BIGGEST_OBJECT);

	if (objects.size() > 0) {

		object = objects[0];

		return true;
	}
	else {

		object = Rect(-1, -1, -1, -1);

		return false;
	}
}

bool ObjectDetector::detectLargestObject(const Mat &image, Rect &object, Point &center) {

	Mat image_gray = image.clone();

	if (image_gray.channels() == 3) {

		cvtColor(image_gray, image_gray, CV_BGR2GRAY);
	}
	else if (image_gray.channels() == 4) {

		cvtColor(image_gray, image_gray, CV_BGRA2GRAY);
	}

	equalizeHist(image_gray, image_gray);

	vector<Rect> objects;

	detectObjects(image_gray, objects, CASCADE_FIND_BIGGEST_OBJECT);

	if (objects.size() > 0) {

		object = objects[0];
		center = Point(object.x + object.width / 2, object.y + object.height / 2);

		return true;
	}
	else {

		object = Rect(-1, -1, -1, -1);
		center = Point(-1, -1);

		return false;
	}
}


text:
package hirondelle.predict.main.prediction;

import static hirondelle.web4j.util.Consts.FAILS;
import hirondelle.predict.main.codes.CodeTable;
import hirondelle.web4j.model.Check;
import hirondelle.web4j.model.Code;
import hirondelle.web4j.model.DateTime;
import hirondelle.web4j.model.Id;
import hirondelle.web4j.model.ModelCtorException;
import hirondelle.web4j.model.ModelUtil;
import hirondelle.web4j.security.SafeText;

import java.util.List;

/**
 Model Object for a Prediction.

This class is interesting since it does not include the foreign key to the PredictionList table;
  that is taken only from the session, not from the database, nor from user input.

This object is immutable, and makes defensive copies where needed.
*/
public final class Prediction {

  /**
   Full constructor. Used when fetching from the database.

   @param aId internal database identifier (optional)
   @param aParentId internal database identifier (required)
   @param aText main text of the prediction max 255 characters (required)
   @param aCreationDate date-time the prediction was created (required)
   @param aRemark any remark the user may wish to make (justification, special remark on the outcome, etc.)  max 2000 chars (optional)
   @param aOutcome final outcome of the prediction (optional)
   @param aOutcomeDate Date the final outcome was established, if ever (optional); if outcome is specified, then the
   outcome date must also be specified
  */
  public Prediction(
   Id aId, Id aParentId,  SafeText aText,  DateTime aCreationDate,
   SafeText aRemark,  Id aOutcome,  DateTime aOutcomeDate
  ) throws ModelCtorException {
    fId = aId;
    fParentId = aParentId;
    fText = aText;
    fCreationDate = aCreationDate;
    fRemark = aRemark;
    fOutcome = CodeTable.codeFor(aOutcome, CodeTable.OUTCOMES);
    fOutcomeDate = aOutcomeDate;
    validateState(CheckDates.YES);
  }

  /**
   Partial constructor, used for user input.

Similar to the full constructor, but the user never inputs the creation date, or the outcome date.
   Here, those dates are simply set to <tt>null</tt>.
   */
  public Prediction(
    Id aId,  Id aParentId, SafeText aText, SafeText aRemark,  Id aOutcome
   ) throws ModelCtorException {
     fId = aId;
     fParentId = aParentId;
     fText = aText;
     fRemark = aRemark;
     fOutcome = CodeTable.codeFor(aOutcome, CodeTable.OUTCOMES);
     fCreationDate = null;
     fOutcomeDate = null;
     validateState(CheckDates.NO);
 }

  public Id getId() { return fId; }
  public Id getParentId() { return fParentId; }
  public SafeText getText() { return fText; }
  public DateTime getCreationDate() { return fCreationDate; }
  public SafeText getRemark() { return fRemark; }
  public Code getOutcome() { return fOutcome; }

  /**
    Returns <tt>null</tt> if there is no outcome.
    Otherwise, returns the score attached to the outcome (see {@link CodeTable#OUTCOMES}).
   */
  public Integer getOutcomeScore() {
    Integer result = null;
    if (fOutcome != null) {
      //Undecidable items will have the short text as null
      SafeText value = fOutcome.getShortText();
      if( value != null ) {
        result = Integer.valueOf(value.getRawString());
      }
    }
    return result;
  }

  public DateTime getOutcomeDate() {
    return fOutcomeDate;
  }

  /**
   Calculate the average of {@link #getOutcomeScore()} for all of the predictions in a list.

Predictions which have a <tt>null</tt> outcome do not contribute to the result.
    If none of the predictions in the list have an outcome, then <tt>null</tt> is returned.
    Integer division is used to calculate the result, so there will be some rounding.
  */
  public static Integer calculateAverageScore(List<Prediction> aPredictions){
    Integer result = null;
    int sum = 0;
    int numScores = 0;
    for(Prediction prediction : aPredictions){
      if(prediction.getOutcomeScore() != null){
        ++numScores;
        sum = sum + prediction.getOutcomeScore();
      }
    }
    if ( numScores > 0 ) {
      result = sum / numScores ; //integer division is close enough
    }
    return result;
  }

  @Override public String toString(){
    return ModelUtil.toStringFor(this);
  }

  @Override public boolean equals(Object aThat){
    Boolean result = ModelUtil.quickEquals(this, aThat);
    if ( result == null ) {
      Prediction that = (Prediction)aThat;
      result = ModelUtil.equalsFor(this.getSignificantFields(), that.getSignificantFields());
    }
    return result;
  }

  @Override public int hashCode(){
    if ( fHashCode == 0 ) {
      fHashCode = ModelUtil.hashCodeFor(getSignificantFields());
    }
    return fHashCode;
  }

  // PRIVATE
  private final Id fId;
  private final Id fParentId;
  private final SafeText fText;
  private final DateTime fCreationDate;
  private final SafeText fRemark;
  private final Code fOutcome;
  private final DateTime fOutcomeDate;
  private int fHashCode;

  private enum CheckDates{YES, NO};

  private void validateState(CheckDates aCheckDates) throws ModelCtorException {
    ModelCtorException ex = new ModelCtorException();

    if ( FAILS == Check.required(fParentId) ) {
      ex.add("Parent Id is required. Programmer error.");
    }
    if ( FAILS == Check.required(fText, Check.range(1, 255)) ) {
      ex.add("You must input text for your prediction (maximum 255 characters)");
    }
    if ( FAILS == Check.optional(fRemark, Check.range(1, 2000)) ) {
      ex.add("Remark must have visible text, maximum 2,000 chars.");
    }

    if(CheckDates.YES == aCheckDates){
      if ( FAILS == Check.required(fCreationDate) ) {
        ex.add("Creation Date is missing (programmer error)");
      }
      if( fOutcome != null && fOutcomeDate == null) {
        ex.add("Outcome and Outcome Date must appear together.");
      }
      if( fOutcome == null && fOutcomeDate != null) {
        ex.add("Outcome and Outcome Date must appear together.");
      }
    }

    if ( ! ex.isEmpty() ) throw ex;
  }

  private Object[] getSignificantFields(){
    return new Object[] {fText, fCreationDate, fRemark, fOutcome, fOutcomeDate};
  }
}


text:
<f:render section="headline" />
<f:render section="content" />


text:
'''
    :codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''

# Import Python Libs
from __future__ import absolute_import

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
    MagicMock,
    patch,
    NO_MOCK,
    NO_MOCK_REASON
)

ensure_in_syspath('../../')

# Import Salt Libs
from salt.states import win_dns_client

# Globals
win_dns_client.__salt__ = {}
win_dns_client.__opts__ = {}

@skipIf(NO_MOCK, NO_MOCK_REASON)
class WinDnsClientTestCase(TestCase):
    '''
        Validate the win_dns_client state
    '''
    def test_dns_exists(self):
        '''
            Test to configure the DNS server list in the specified interface
        '''
        ret = {'name': 'salt',
               'changes': {},
               'result': False,
               'comment': ''}
        with patch.dict(win_dns_client.__opts__, {"test": False}):
            ret.update({'changes': {'Servers Added': [],
                                    'Servers Removed': [],
                                    'Servers Reordered': []},
                        'comment': 'servers entry is not a list !'})
            self.assertDictEqual(win_dns_client.dns_exists('salt'), ret)

            mock = MagicMock(return_value=[2, 'salt'])
            with patch.dict(win_dns_client.__salt__,
                            {'win_dns_client.get_dns_servers': mock}):
                ret.update({'changes': {}, 'comment': "[2, 'salt'] are already"
                            " configured", 'result': True})
                self.assertDictEqual(win_dns_client.dns_exists('salt',
                                                               [2, 'salt']),
                                     ret)

                mock = MagicMock(side_effect=[False, True, True])
                with patch.dict(win_dns_client.__salt__,
                                {'win_dns_client.add_dns': mock}):
                    ret.update({'comment': 'Failed to add 1 as DNS'
                                ' server number 1', 'result': False})
                    self.assertDictEqual(win_dns_client.dns_exists('salt',
                                                                   [1, 'salt']
                                                                   ), ret)

                    mock = MagicMock(return_value=False)
                    with patch.dict(win_dns_client.__salt__,
                                    {'win_dns_client.rm_dns': mock}):
                        ret.update({'changes': {'Servers Added': ['a'],
                                                'Servers Removed': [],
                                                'Servers Reordered': []},
                                    'comment': 'Failed to remove 2 from DNS'
                                    ' server list'})
                        self.assertDictEqual(win_dns_client.dns_exists('salt',
                                                                       ['a'],
                                                                       'a',
                                                                       1),
                                             ret)

                    ret.update({'comment': 'DNS Servers have been updated',
                                'result': True})
                    self.assertDictEqual(win_dns_client.dns_exists('salt',
                                                                   ['a']), ret)

    def test_dns_dhcp(self):
        '''
            Test to configure the DNS server list from DHCP Server
        '''
        ret = {'name': 'salt',
               'changes': {},
               'result': True,
               'comment': ''}
        mock = MagicMock(side_effect=['dhcp', 'salt', 'salt'])
        with patch.dict(win_dns_client.__salt__,
                        {'win_dns_client.get_dns_config': mock}):
            ret.update({'comment': 'Local Area Connection already configured'
                        ' with DNS from DHCP'})
            self.assertDictEqual(win_dns_client.dns_dhcp('salt'), ret)

            with patch.dict(win_dns_client.__opts__, {"test": True}):
                ret.update({'comment': '', 'result': None,
                            'changes': {'dns': 'configured from DHCP'}})
                self.assertDictEqual(win_dns_client.dns_dhcp('salt'), ret)

            with patch.dict(win_dns_client.__opts__, {"test": False}):
                mock = MagicMock(return_value=True)
                with patch.dict(win_dns_client.__salt__,
                                {'win_dns_client.dns_dhcp': mock}):
                    ret.update({'result': True})
                    self.assertDictEqual(win_dns_client.dns_dhcp('salt'), ret)

    def test_primary_suffix(self):
        '''
            Test to configure the global primary DNS suffix of a DHCP client.
        '''
        ret = {'name': 'salt',
               'changes': {},
               'result': False,
               'comment': ''}
        ret.update({'comment': "'updates' must be a boolean value"})
        self.assertDictEqual(win_dns_client.primary_suffix('salt', updates='a'
                                                           ), ret)

        mock = MagicMock(side_effect=['a', False, 'b', False])
        with patch.dict(win_dns_client.__salt__, {'reg.read_key': mock}):
            ret.update({'comment': 'No changes needed', 'result': True})
            self.assertDictEqual(win_dns_client.primary_suffix('salt', 'a'),
                                 ret)

            mock = MagicMock(return_value=True)
            with patch.dict(win_dns_client.__salt__, {'reg.set_key': mock}):
                ret.update({'changes': {'new': {'suffix': 'a'},
                                        'old': {'suffix': 'b'}},
                            'comment': 'Updated primary DNS suffix (a)'})
                self.assertDictEqual(win_dns_client.primary_suffix('salt',
                                                                   'a'), ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(WinDnsClientTestCase, needs_daemon=False)


text:
using System.Linq;
using System.Xml.Linq;
using FluentAssertions;
using Xunit;

namespace Rocks.Helpers.Tests
{
	public class XmlExtensionsTests
	{
		[Fact]
		public void GetElement_OneName_Exists_Returns ()
		{
			// arrange
			var root = XElement.Parse ("<root></root>");

			// act
			var result = root.GetElement ("a");

			// assert
			result.Should ().Be (root.Elements ().First ());
		}

		[Fact]
		public void GetElement_TwoNames_Exists_Returns ()
		{
			// arrange
			var root = XElement.Parse ("<root></root>");

			// act
			var result = root.GetElement ("a", "b");

			// assert
			result.Should ().Be (root.Elements ().First ().Elements ().First ());
		}

		[Fact]
		public void GetElement_OneName_NotExists_Creates ()
		{
			// arrange
			var root = XElement.Parse ("<root />");

			// act
			var result = root.GetElement ("a");

			// assert
			result.Name.LocalName.Should ().Be ("a");
			root.Elements ().First ().Should ().Be (result);
			root.ToString (SaveOptions.DisableFormatting).Should ().Be ("<root></root>");
		}

		[Fact]
		public void GetElement_TwoNames_NotExists_Creates ()
		{
			// arrange
			var root = XElement.Parse ("<root />");

			// act
			var result = root.GetElement ("a", "b");

			// assert
			result.Name.LocalName.Should ().Be ("b");
			root.Elements ().First ().Elements ().First ().Should ().Be (result);
			root.ToString (SaveOptions.DisableFormatting).Should ().Be ("<root></root>");
		}

		[Fact]
		public void GetValue_NullElement_NoName_ReturnsNull ()
		{
			// arrange

			// act
			var result = ((XElement) null).GetValue ();

			// assert
			result.Should ().BeNull ();
		}

		[Fact]
		public void GetValue_Exists_NoName_ReturnsValue ()
		{
			// arrange
			var root = XElement.Parse ("<root>a</root>");

			// act
			var result = root.GetValue ();

			// assert
			result.Should ().Be ("a");
		}

		[Fact]
		public void GetValue_NullElement_WithName_ReturnsNull ()
		{
			// arrange

			// act
			var result = ((XElement) null).GetValue ("a");

			// assert
			result.Should ().BeNull ();
		}

		[Fact]
		public void GetValue_Exists_WithName_ReturnsValue ()
		{
			// arrange
			var root = XElement.Parse ("<root>b</root>");

			// act
			var result = root.GetValue ("a");

			// assert
			result.Should ().Be ("b");
		}
	}
}


text:
'use strict';

/*
 * Utilities for working with Glimmer VM's subpackages.
 */

const fs = require('fs');
const glob = require('glob');
const path = require('path');
const DAGMap = require('dag-map').default;

/**
 * The Package class represents a logical subpackage in the Glimmer VM monorepo.
 * It contains utility methods for querying and rewriting a package's
 * `package.json` file.
 */
class Package {
  constructor(name, cwd, siblingPackages) {
    this.name = name;
    this.absolutePath = path.resolve(cwd, name);
    this.siblingPackages = siblingPackages;
    try {
      this.pkg = require(this.packageJSONPath);
    } catch (e) {
      this.pkg = { name };
    }
  }

  get version() {
    return this.pkg.version;
  }

  get private() {
    return this.pkg.private;
  }

  get relativePath() {
    return path.relative(process.cwd(), this.absolutePath);
  }

  get allDependencies() {
    return Object.assign({}, this.pkg.devDependencies, this.pkg.dependencies);
  }

  /**
   * The list of a package's dependencies that are internal to the same
   * monorepo.
   */
  get internalDependencies() {
    let siblings = this.siblingPackages;
    return Object.keys(this.allDependencies).filter((dep) => siblings.includes(dep));
  }

  get packageJSONPath() {
    return path.join(this.absolutePath, 'package.json');
  }

  get isPublishable() {
    return !this.pkg.private;
  }

  updateDependencies(newVersion) {
    this._updateDependencies(this.pkg.dependencies, newVersion);
    this._updateDependencies(this.pkg.devDependencies, newVersion);
  }

  get simpleHTMLTokenizerVersion() {
    return this.pkg.dependencies && this.pkg.dependencies['simple-html-tokenizer'];
  }

  set simpleHTMLTokenizerVersion(value) {
    if (this.pkg.dependencies) {
      this.pkg.dependencies['simple-html-tokenizer'] = value;
    }
  }

  updateSimpleHTMLTokenizer(newVersion) {
    let version = this.simpleHTMLTokenizerVersion;
    if (version && version !== newVersion) {
      console.log(`updating simple-html-tokenizer dep in ${this.relativePath} to ${newVersion}`);
      this.simpleHTMLTokenizerVersion = newVersion;
    }
  }

  _updateDependencies(deps, newVersion) {
    if (!deps) {
      return;
    }

    Object.keys(deps).forEach((dep) => {
      if (this.siblingPackages.indexOf(dep) >= 0) {
        deps[dep] = `^${newVersion}`;
      }
    });
  }

  savePackageJSON() {
    fs.writeFileSync(this.packageJSONPath, JSON.stringify(this.pkg, null, 2) + '\n');
  }
}

const PACKAGES_GLOB = '@glimmer/*/';

function findPackages(cwd, packagesGlob = PACKAGES_GLOB) {
  let packageNames = glob.sync(packagesGlob, { cwd }).map(trimTrailingSlash);

  if (!packageNames.length) {
    throw new Error(`No packages found in ${cwd}`);
  }

  let packages = packageNames.map((pkg) => new Package(pkg, cwd, packageNames));

  return topsort(packages);
}

function trimTrailingSlash(filePath) {
  return filePath.replace(/\/$/, '');
}

function topsort(packages) {
  let graph = new DAGMap();

  // Get a list of package names discovered in the repo.
  let inRepoDependencies = packages.map((pkg) => pkg.name);

  // For each package, get a list of in-repo packages it depends on, and add
  // them to the graph.
  packages
    .map((pkg) => filterDependencies(pkg))
    .forEach(([pkg, deps]) => {
      graph.add(pkg.name, pkg, null, deps);
    });

  let sorted = [];

  // Get a topographically sorted list of packages.
  graph.each((pkgName, pkg) => sorted.push(pkg));

  return sorted;

  function filterDependencies(pkg) {
    // Merge the package's dependencies and dev dependencies, then filter out
    // any dependencies that we didn't discover in the repo.
    let dependencies = Object.keys(pkg.allDependencies).filter(
      (dep) => inRepoDependencies.indexOf(dep) > -1
    );

    return [pkg, dependencies];
  }
}

const PROJECT_CACHE = [];

/**
 * Represents all of the packages in the monorepo project.
 */
class Project {
  /**
   * Use the static `from()` method to share a cached Project across multiple
   * consumers, so long as the root path is the same.
   */
  static from(rootPath) {
    let absolutePath = path.resolve(rootPath);
    if (PROJECT_CACHE[absolutePath]) {
      return PROJECT_CACHE[absolutePath];
    }

    PROJECT_CACHE[absolutePath] = new Project(rootPath);

    return PROJECT_CACHE[absolutePath];
  }

  constructor(rootPath) {
    this.packages = findPackages(rootPath);
  }

  /**
   * Returns an array of dependencies and devDependencies for every package.
   */
  get dependencies() {
    let deps = [];

    this.packages.forEach((pkg) => {
      deps.push(...Object.keys(pkg.allDependencies));
    });

    // Deduplicate dependencies
    return [...new Set(deps)];
  }
}

module.exports = Project;


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

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>jsonschema2pojo</artifactId>
        <groupId>org.jsonschema2pojo</groupId>
        <version>0.4.14-SNAPSHOT</version>
    </parent>

    <artifactId>jsonschema2pojo-ant</artifactId>

    <name>jsonschema2pojo-ant</name>

    <dependencies>
        <dependency>
            <groupId>org.jsonschema2pojo</groupId>
            <artifactId>jsonschema2pojo-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
        </dependency>
    </dependencies>

</project>


text:
package com.tinkerpop.gremlin.test.filter;

import com.tinkerpop.blueprints.Vertex;
import junit.framework.TestCase;

import java.util.Iterator;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class RangeStepTest extends TestCase {

    public void testCompliance() {
        assertTrue(true);
    }

    public void test_g_v1_out_rangeX0_1X(Iterator<Vertex> pipe) {
        int counter = 0;
        while (pipe.hasNext()) {
            counter++;
            pipe.next();
        }
        assertEquals(counter, 2);
    }

    public void test_g_v1_outXknowsX_outEXcreatedX_rangeX0_0X_inV(Iterator<Vertex> pipe) {
        int counter = 0;
        while (pipe.hasNext()) {
            counter++;
            String name = (String) pipe.next().getProperty("name");
            assertTrue(name.equals("lop") || name.equals("ripple"));
        }
        assertEquals(counter, 1);
    }

    public void test_g_v1_outXknowsX_outXcreatedX_rangeX0_0X(Iterator<Vertex> pipe) {
        this.test_g_v1_outXknowsX_outEXcreatedX_rangeX0_0X_inV(pipe);
    }

    public void test_g_v1_outXcreatedX_inXcreatedX_rangeX1_2X(Iterator<Vertex> pipe) {
        int counter = 0;
        while (pipe.hasNext()) {
            counter++;
            String name = (String) pipe.next().getProperty("name");
            assertTrue(name.equals("marko") || name.equals("josh") || name.equals("peter"));
        }
        assertEquals(counter, 2);
    }

    public void test_g_v1_outXcreatedX_inEXcreatedX_rangeX1_2X_outV(Iterator<Vertex> pipe) {
        this.test_g_v1_outXcreatedX_inXcreatedX_rangeX1_2X(pipe);
    }

}