text:
package group.idealworld.dew.devops.it.verify;

import com.ecfront.dew.common.$;
import group.idealworld.dew.devops.it.BasicProcessor;
import org.joox.JOOX;
import org.junit.Assert;
import org.w3c.dom.Document;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * To-do verify.
 *
 * @author gudaoxuri
 */
public class TodoVerify extends BasicProcessor implements Verify {

    @Override
    public void doVerify(String buildPath, String expectedResPath) throws Exception {
        loadConfig();

        // verify parent
        String metaData = $.http.get(itSnapshotRepositoryUrl + "group/idealworld/dew/devops/it/todo-parent/3.0.0-RC2/maven-metadata.xml");
        Document doc = JOOX.builder().parse(new ByteArrayInputStream(metaData.getBytes()));
        String lastUpdateTime = JOOX.$(doc).find("lastUpdated").get(0).getTextContent();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        long offsetMinutes = (System.currentTimeMillis() - sdf.parse(lastUpdateTime).getTime()) / 1000 / 60 / 60;
        Assert.assertTrue("parent | last deploy time check", offsetMinutes < 5);

        // verify common
        metaData = $.http.get(itSnapshotRepositoryUrl + "group/idealworld/dew/devops/it/todo-common/3.0.0-RC2/maven-metadata.xml");
        doc = JOOX.builder().parse(new ByteArrayInputStream(metaData.getBytes()));
        lastUpdateTime = JOOX.$(doc).find("lastUpdated").get(0).getTextContent();
        sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        offsetMinutes = (System.currentTimeMillis() - sdf.parse(lastUpdateTime).getTime()) / 1000 / 60 / 60;
        Assert.assertTrue("common | last deploy time check", offsetMinutes < 5);

    }
}


text:
package com.focusit.jstack;

public class StacktraceItem {
	public String methodFqn;
	public String fileline;

	@Override
	public String toString() {
		return "\t\t"+methodFqn + "("+fileline + ")";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((fileline == null) ? 0 : fileline.hashCode());
		result = prime * result + ((methodFqn == null) ? 0 : methodFqn.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		StacktraceItem other = (StacktraceItem) obj;
		if (fileline == null) {
			if (other.fileline != null)
				return false;
		} else if (!fileline.equals(other.fileline))
			return false;
		if (methodFqn == null) {
			if (other.methodFqn != null)
				return false;
		} else if (!methodFqn.equals(other.methodFqn))
			return false;
		return true;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.everit.authnr.qdsl.util;

import com.querydsl.core.types.Expression;
import com.querydsl.core.types.dsl.BooleanExpression;

/**
 * Utility API to create the permission checks easily for Querydsl based SQL queries.
 */
public interface AuthnrQdslUtil {

  /**
   * Creates a predicate for a Querydsl based SQL query. If the predicate is appended to the where
   * part of the main query, the results will be filtered based on authorization. The
   * authorizedResourceId must be provided by the implementation, that is typically the same as the
   * authenticated resourceId.

   *

   * E.g.: Users and books are resources. Users can view and edit books. To list the books that the
   * currently authenticated user can view or edit, the following code snippet should be used:
   *
   *

   * QBook book = QBook.book;
   * BooleanExpression authrPredicate =
   *         authnrQdslUtil.authorizationPredicate(book.resourceId, "read", "edit");
   *
   * SQLQuery query = new SQLQuery(connection, configuration);
   *
   * return query.from(book)...where(authrPredicate)...list(...);
   *

   *
   * @param targetResourceId
   *          Expression that provides the resource that the permission is defined on. This
   * @param actions
   *          If the authorized resource has permission to do any of the actions on the target
   *          resource record (directly or by inheritance), the result will provide
   *          true.
   * @return An expression that can be used as a predicate in the main query.
   * @throws NullPointerException
   *           if the targetResourceId parameter is null, the actions parameter is null or the
   *           actions array contains null value.
   * @throws IllegalArgumentException
   *           if the actions parameter is a zero length array.
   */
  BooleanExpression authorizationPredicate(Expression<Long> targetResourceId, String... actions);

}


text:
package net.aichler.jupiter.internal;

import org.junit.Test;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @author Michael Aichler
 */
public class ColorTest {

    @Test
    public void colorNoneShouldNotFormatAnything() {

        String expected = "Some string";
        String actual = Color.NONE.format(expected);

        assertThat(actual, equalTo(expected));
    }

    @Test
    public void shouldFormatWithColor() {

        String value = "Some string";
        String expected = "\u001B[37mSome string\u001B[0m";

        assertThat(Color.WHITE.format(value), equalTo(expected));
    }

    @Test
    public void shouldFilterColors() {

        String value = "\u001B[37mSome string\u001B[0m";
        String expected = "Some string";

        assertThat(Color.filter(value), equalTo(expected));
    }

    @Test
    public void toStringShouldReturnAnsiSequence() {

        assertThat(Color.BLACK.toString(), equalTo("\u001B[30m"));
    }

    @Test
    public void toStringOfColorNoneShouldReturnEmptyString() {

        assertThat(Color.NONE.toString(), equalTo(""));
    }
}


text:
<?php

namespace Drupal\content_translation\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;

/**
 * Access check for entity translation CRUD operation.
 */
class ContentTranslationManageAccessCheck implements AccessInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Constructs a ContentTranslationManageAccessCheck object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->languageManager = $language_manager;
  }

  /**
   * Checks translation access for the entity and operation on the given route.
   *
   * @param \Symfony\Component\Routing\Route $route
   *   The route to check against.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The parametrized route.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The currently logged in account.
   * @param string $source
   *   (optional) For a create operation, the language code of the source.
   * @param string $target
   *   (optional) For a create operation, the language code of the translation.
   * @param string $language
   *   (optional) For an update or delete operation, the language code of the
   *   translation being updated or deleted.
   * @param string $entity_type_id
   *   (optional) The entity type ID.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    if ($entity = $route_match->getParameter($entity_type_id)) {
      $operation = $route->getRequirement('_access_content_translation_manage');
      $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
      $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);

      if (in_array($operation, ['update', 'delete'])) {
        // Translation operations cannot be performed on the default
        // translation.
        if ($language->getId() == $entity->getUntranslated()->language()->getId()) {
          return AccessResult::forbidden()->addCacheableDependency($entity);
        }
        // Editors have no access to the translation operations, as entity
        // access already grants them an equal or greater access level.
        $templates = ['update' => 'edit-form', 'delete' => 'delete-form'];
        if ($entity->access($operation) && $entity_type->hasLinkTemplate($templates[$operation])) {
          return AccessResult::forbidden()->cachePerPermissions();
        }
      }

      if ($account->hasPermission('translate any entity')) {
        return AccessResult::allowed()->cachePerPermissions();
      }

      switch ($operation) {
        case 'create':
          /** @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */
          $handler = $this->entityTypeManager->getHandler($entity->getEntityTypeId(), 'translation');
          $translations = $entity->getTranslationLanguages();
          $languages = $this->languageManager->getLanguages();
          $source_language = $this->languageManager->getLanguage($source) ?: $entity->language();
          $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
          $is_new_translation = ($source_language->getId() != $target_language->getId()
            && isset($languages[$source_language->getId()])
            && isset($languages[$target_language->getId()])
            && !isset($translations[$target_language->getId()]));
          return AccessResult::allowedIf($is_new_translation)->cachePerPermissions()->addCacheableDependency($entity)
            ->andIf($handler->getTranslationAccess($entity, $operation));

        case 'delete':
          // @todo Remove this in https://www.drupal.org/node/2945956.
          /** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
          $delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
          $access = $this->checkAccess($entity, $language, $operation);
          return $delete_access->andIf($access);

        case 'update':
          return $this->checkAccess($entity, $language, $operation);
      }
    }

    // No opinion.
    return AccessResult::neutral();
  }

  /**
   * Performs access checks for the specified operation.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity being checked.
   * @param \Drupal\Core\Language\LanguageInterface $language
   *   For an update or delete operation, the language code of the translation
   *   being updated or deleted.
   * @param string $operation
   *   The operation to be checked.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   An access result object.
   */
  protected function checkAccess(ContentEntityInterface $entity, LanguageInterface $language, $operation) {
    /** @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */
    $handler = $this->entityTypeManager->getHandler($entity->getEntityTypeId(), 'translation');
    $translations = $entity->getTranslationLanguages();
    $languages = $this->languageManager->getLanguages();
    $has_translation = isset($languages[$language->getId()])
      && $language->getId() != $entity->getUntranslated()->language()->getId()
      && isset($translations[$language->getId()]);
    return AccessResult::allowedIf($has_translation)->cachePerPermissions()->addCacheableDependency($entity)
      ->andIf($handler->getTranslationAccess($entity, $operation));
  }

}


text:
{% extends 'main/main_base.html' %}
{% set page='explore' %}
{% block page_title %}
Configuring discussion for {{ event.title }} | Air Mozilla
{% endblock %}

{% block site_css %}
  {{ super() }}
  {% compress css %}
  <link href="{{ static('main/css/edit.css') }}" rel="stylesheet" type="text/css">
  <link href="{{ static('main/css/discussion.css') }}" rel="stylesheet" type="text/css">
  {% endcompress %}
{% endblock %}

{% block site_js %}
  {{ super() }}
  {% compress js %}

  {% endcompress %}
{% endblock %}

{% block sidebar %}{% endblock %}

{% block content_main %}

Configuring discussion for
      "{{ event.title }}"

« Go back to event

    {% if invalid_form(form) %}

Form errors!

The submitted form contains errors preventing it from completing the request.

        Review the form and look for error messages in red.

    {% endif %}

    <form method="post" class="form-horizontal event-discussion" enctype="multipart/form-data">{{ csrf() }}

        {{ bootstrapform(form) }}

            <button type="submit" class="btn btn-primary submit" name="submit">
                Save
            </button>
            <button class="btn cancel" name="cancel">Cancel</button>

                Saving saving saving...

    </form>

{% endblock %}


text:
using namespace mindscape;

void Fighter::hit(engine::GameObject *killer, int lost_hp){
  hitpoints -= lost_hp;
  if(hitpoints <= 0)
    die(killer);
}

void Fighter::heal(int p_hitpoints){
  hitpoints += p_hitpoints;
  if(hitpoints > max_hitpoints)
    hitpoints = max_hitpoints;
}

int Fighter::get_hp(){
  return hitpoints;
}

void Fighter::set_hp(int hp){
  hitpoints = hp;
}

bool Fighter::is_life_full(){
  return hitpoints == max_hitpoints;
}

bool Fighter::is_alive(){
  return hitpoints > 0;
}


text:
<link rel="stylesheet" type="text/css" href="css/diQuery-collapsiblePanel.css">
<link rel="stylesheet" type="text/css" href="css/style.css">

Catalogue Browser

        <form>
            <select id="examples"></select>
            URL: <input type="text" id="url" size=80 value="http://dev.1248.io:8001/cats" />
            Key <input type="password" id="key" size=40 value="" />
            <input type="button" id="go" value="Go/Refresh" />
        </form>

        <input type="button" id="back" value="Back" />
        <input type="button" id="newcat" value="Create new catalogue"/>


text:
from __future__ import absolute_import, division, print_function

import itertools

from cryptography import utils
from cryptography.exceptions import UnsupportedAlgorithm, InvalidTag
from cryptography.hazmat.backends.interfaces import (
    CipherBackend, HashBackend, HMACBackend
)
from cryptography.hazmat.primitives import interfaces
from cryptography.hazmat.primitives.ciphers.algorithms import (
    AES, Blowfish, Camellia, TripleDES, ARC4,
)
from cryptography.hazmat.primitives.ciphers.modes import (
    CBC, CTR, ECB, OFB, CFB, GCM,
)
from cryptography.hazmat.bindings.openssl.binding import Binding

@utils.register_interface(CipherBackend)
@utils.register_interface(HashBackend)
@utils.register_interface(HMACBackend)
class Backend(object):
    """
    OpenSSL API binding interfaces.
    """

    def __init__(self):
        self._binding = Binding()
        self._ffi = self._binding.ffi
        self._lib = self._binding.lib

        self._lib.OpenSSL_add_all_algorithms()
        self._lib.SSL_load_error_strings()

        self._cipher_registry = {}
        self._register_default_ciphers()

    def openssl_version_text(self):
        """
        Friendly string name of linked OpenSSL.

        Example: OpenSSL 1.0.1e 11 Feb 2013
        """
        return self._ffi.string(self._lib.OPENSSL_VERSION_TEXT).decode("ascii")

    def create_hmac_ctx(self, key, algorithm):
        return _HMACContext(self, key, algorithm)

    def hash_supported(self, algorithm):
        digest = self._lib.EVP_get_digestbyname(algorithm.name.encode("ascii"))
        return digest != self._ffi.NULL

    def hmac_supported(self, algorithm):
        return self.hash_supported(algorithm)

    def create_hash_ctx(self, algorithm):
        return _HashContext(self, algorithm)

    def cipher_supported(self, cipher, mode):
        try:
            adapter = self._cipher_registry[type(cipher), type(mode)]
        except KeyError:
            return False
        evp_cipher = adapter(self, cipher, mode)
        return self._ffi.NULL != evp_cipher

    def register_cipher_adapter(self, cipher_cls, mode_cls, adapter):
        if (cipher_cls, mode_cls) in self._cipher_registry:
            raise ValueError("Duplicate registration for: {0} {1}".format(
                cipher_cls, mode_cls)
            )
        self._cipher_registry[cipher_cls, mode_cls] = adapter

    def _register_default_ciphers(self):
        for cipher_cls, mode_cls in itertools.product(
            [AES, Camellia],
            [CBC, CTR, ECB, OFB, CFB],
        ):
            self.register_cipher_adapter(
                cipher_cls,
                mode_cls,
                GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
            )
        for mode_cls in [CBC, CFB, OFB]:
            self.register_cipher_adapter(
                TripleDES,
                mode_cls,
                GetCipherByName("des-ede3-{mode.name}")
            )
        for mode_cls in [CBC, CFB, OFB, ECB]:
            self.register_cipher_adapter(
                Blowfish,
                mode_cls,
                GetCipherByName("bf-{mode.name}")
            )
        self.register_cipher_adapter(
            ARC4,
            type(None),
            GetCipherByName("rc4")
        )
        self.register_cipher_adapter(
            AES,
            GCM,
            GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
        )

    def create_symmetric_encryption_ctx(self, cipher, mode):
        return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)

    def create_symmetric_decryption_ctx(self, cipher, mode):
        return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT)

    def _handle_error(self, mode):
        code = self._lib.ERR_get_error()
        if not code and isinstance(mode, GCM):
            raise InvalidTag
        assert code != 0
        lib = self._lib.ERR_GET_LIB(code)
        func = self._lib.ERR_GET_FUNC(code)
        reason = self._lib.ERR_GET_REASON(code)
        return self._handle_error_code(lib, func, reason)

    def _handle_error_code(self, lib, func, reason):
        if lib == self._lib.ERR_LIB_EVP:
            if func == self._lib.EVP_F_EVP_ENCRYPTFINAL_EX:
                if reason == self._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
                    raise ValueError(
                        "The length of the provided data is not a multiple of "
                        "the block length"
                    )
            elif func == self._lib.EVP_F_EVP_DECRYPTFINAL_EX:
                if reason == self._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
                    raise ValueError(
                        "The length of the provided data is not a multiple of "
                        "the block length"
                    )

        raise SystemError(
            "Unknown error code from OpenSSL, you should probably file a bug."
        )

class GetCipherByName(object):
    def __init__(self, fmt):
        self._fmt = fmt

    def __call__(self, backend, cipher, mode):
        cipher_name = self._fmt.format(cipher=cipher, mode=mode).lower()
        return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii"))

@utils.register_interface(interfaces.CipherContext)
@utils.register_interface(interfaces.AEADCipherContext)
@utils.register_interface(interfaces.AEADEncryptionContext)
class _CipherContext(object):
    _ENCRYPT = 1
    _DECRYPT = 0

    def __init__(self, backend, cipher, mode, operation):
        self._backend = backend
        self._cipher = cipher
        self._mode = mode
        self._operation = operation
        self._tag = None

        if isinstance(self._cipher, interfaces.BlockCipherAlgorithm):
            self._block_size = self._cipher.block_size
        else:
            self._block_size = 1

        ctx = self._backend._lib.EVP_CIPHER_CTX_new()
        ctx = self._backend._ffi.gc(
            ctx, self._backend._lib.EVP_CIPHER_CTX_free
        )

        registry = self._backend._cipher_registry
        try:
            adapter = registry[type(cipher), type(mode)]
        except KeyError:
            raise UnsupportedAlgorithm(
                "cipher {0} in {1} mode is not supported "
                "by this backend".format(
                    cipher.name, mode.name if mode else mode)
            )

        evp_cipher = adapter(self._backend, cipher, mode)
        if evp_cipher == self._backend._ffi.NULL:
            raise UnsupportedAlgorithm(
                "cipher {0} in {1} mode is not supported "
                "by this backend".format(
                    cipher.name, mode.name if mode else mode)
            )

        if isinstance(mode, interfaces.ModeWithInitializationVector):
            iv_nonce = mode.initialization_vector
        elif isinstance(mode, interfaces.ModeWithNonce):
            iv_nonce = mode.nonce
        else:
            iv_nonce = self._backend._ffi.NULL
        # begin init with cipher and operation type
        res = self._backend._lib.EVP_CipherInit_ex(ctx, evp_cipher,
                                                   self._backend._ffi.NULL,
                                                   self._backend._ffi.NULL,
                                                   self._backend._ffi.NULL,
                                                   operation)
        assert res != 0
        # set the key length to handle variable key ciphers
        res = self._backend._lib.EVP_CIPHER_CTX_set_key_length(
            ctx, len(cipher.key)
        )
        assert res != 0
        if isinstance(mode, GCM):
            res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
                ctx, self._backend._lib.EVP_CTRL_GCM_SET_IVLEN,
                len(iv_nonce), self._backend._ffi.NULL
            )
            assert res != 0
            if operation == self._DECRYPT:
                res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
                    ctx, self._backend._lib.EVP_CTRL_GCM_SET_TAG,
                    len(mode.tag), mode.tag
                )
                assert res != 0

        # pass key/iv
        res = self._backend._lib.EVP_CipherInit_ex(
            ctx,
            self._backend._ffi.NULL,
            self._backend._ffi.NULL,
            cipher.key,
            iv_nonce,
            operation
        )
        assert res != 0
        # We purposely disable padding here as it's handled higher up in the
        # API.
        self._backend._lib.EVP_CIPHER_CTX_set_padding(ctx, 0)
        self._ctx = ctx

    def update(self, data):
        buf = self._backend._ffi.new("unsigned char[]",
                                     len(data) + self._block_size - 1)
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherUpdate(self._ctx, buf, outlen, data,
                                                  len(data))
        assert res != 0
        return self._backend._ffi.buffer(buf)[:outlen[0]]

    def finalize(self):
        buf = self._backend._ffi.new("unsigned char[]", self._block_size)
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
        if res == 0:
            self._backend._handle_error(self._mode)

        if (isinstance(self._mode, GCM) and
           self._operation == self._ENCRYPT):
            block_byte_size = self._block_size // 8
            tag_buf = self._backend._ffi.new(
                "unsigned char[]", block_byte_size
            )
            res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
                self._ctx, self._backend._lib.EVP_CTRL_GCM_GET_TAG,
                block_byte_size, tag_buf
            )
            assert res != 0
            self._tag = self._backend._ffi.buffer(tag_buf)[:]

        res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
        assert res == 1
        return self._backend._ffi.buffer(buf)[:outlen[0]]

    def authenticate_additional_data(self, data):
        outlen = self._backend._ffi.new("int *")
        res = self._backend._lib.EVP_CipherUpdate(
            self._ctx, self._backend._ffi.NULL, outlen, data, len(data)
        )
        assert res != 0

    @property
    def tag(self):
        return self._tag

@utils.register_interface(interfaces.HashContext)
class _HashContext(object):
    def __init__(self, backend, algorithm, ctx=None):
        self.algorithm = algorithm

        self._backend = backend

        if ctx is None:
            ctx = self._backend._lib.EVP_MD_CTX_create()
            ctx = self._backend._ffi.gc(ctx,
                                        self._backend._lib.EVP_MD_CTX_destroy)
            evp_md = self._backend._lib.EVP_get_digestbyname(
                algorithm.name.encode("ascii"))
            if evp_md == self._backend._ffi.NULL:
                raise UnsupportedAlgorithm(
                    "{0} is not a supported hash on this backend".format(
                        algorithm.name)
                )
            res = self._backend._lib.EVP_DigestInit_ex(ctx, evp_md,
                                                       self._backend._ffi.NULL)
            assert res != 0

        self._ctx = ctx

    def copy(self):
        copied_ctx = self._backend._lib.EVP_MD_CTX_create()
        copied_ctx = self._backend._ffi.gc(
            copied_ctx, self._backend._lib.EVP_MD_CTX_destroy
        )
        res = self._backend._lib.EVP_MD_CTX_copy_ex(copied_ctx, self._ctx)
        assert res != 0
        return _HashContext(self._backend, self.algorithm, ctx=copied_ctx)

    def update(self, data):
        res = self._backend._lib.EVP_DigestUpdate(self._ctx, data, len(data))
        assert res != 0

    def finalize(self):
        buf = self._backend._ffi.new("unsigned char[]",
                                     self.algorithm.digest_size)
        res = self._backend._lib.EVP_DigestFinal_ex(self._ctx, buf,
                                                    self._backend._ffi.NULL)
        assert res != 0
        res = self._backend._lib.EVP_MD_CTX_cleanup(self._ctx)
        assert res == 1
        return self._backend._ffi.buffer(buf)[:]

@utils.register_interface(interfaces.HashContext)
class _HMACContext(object):
    def __init__(self, backend, key, algorithm, ctx=None):
        self.algorithm = algorithm
        self._backend = backend

        if ctx is None:
            ctx = self._backend._ffi.new("HMAC_CTX *")
            self._backend._lib.HMAC_CTX_init(ctx)
            ctx = self._backend._ffi.gc(
                ctx, self._backend._lib.HMAC_CTX_cleanup
            )
            evp_md = self._backend._lib.EVP_get_digestbyname(
                algorithm.name.encode('ascii'))
            if evp_md == self._backend._ffi.NULL:
                raise UnsupportedAlgorithm(
                    "{0} is not a supported hash on this backend".format(
                        algorithm.name)
                )
            res = self._backend._lib.Cryptography_HMAC_Init_ex(
                ctx, key, len(key), evp_md, self._backend._ffi.NULL
            )
            assert res != 0

        self._ctx = ctx
        self._key = key

    def copy(self):
        copied_ctx = self._backend._ffi.new("HMAC_CTX *")
        self._backend._lib.HMAC_CTX_init(copied_ctx)
        copied_ctx = self._backend._ffi.gc(
            copied_ctx, self._backend._lib.HMAC_CTX_cleanup
        )
        res = self._backend._lib.Cryptography_HMAC_CTX_copy(
            copied_ctx, self._ctx
        )
        assert res != 0
        return _HMACContext(
            self._backend, self._key, self.algorithm, ctx=copied_ctx
        )

    def update(self, data):
        res = self._backend._lib.Cryptography_HMAC_Update(
            self._ctx, data, len(data)
        )
        assert res != 0

    def finalize(self):
        buf = self._backend._ffi.new("unsigned char[]",
                                     self.algorithm.digest_size)
        buflen = self._backend._ffi.new("unsigned int *",
                                        self.algorithm.digest_size)
        res = self._backend._lib.Cryptography_HMAC_Final(
            self._ctx, buf, buflen
        )
        assert res != 0
        self._backend._lib.HMAC_CTX_cleanup(self._ctx)
        return self._backend._ffi.buffer(buf)[:]

backend = Backend()


text:
from unittest.mock import patch

import pytest

class TestCurrencyProvider:
    """Test currency provider methods"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency import Provider as CurrencyProvider

        cls.provider = CurrencyProvider
        cls.currencies = cls.provider.currencies
        cls.cryptocurrencies = cls.provider.cryptocurrencies
        cls.currency_codes, cls.currency_names = tuple(zip(*cls.currencies))
        cls.cryptocurrency_codes, cls.cryptocurrency_names = tuple(zip(*cls.cryptocurrencies))

    def test_currency(self, faker, num_samples):
        for _ in range(num_samples):
            cur = faker.currency()
            assert isinstance(cur, tuple)
            assert cur in self.currencies

    def test_currency_code(self, faker, num_samples):
        for _ in range(num_samples):
            code = faker.currency_code()
            assert isinstance(code, str) and code in self.currency_codes

    def test_currency_name(self, faker, num_samples):
        for _ in range(num_samples):
            name = faker.currency_name()
            assert isinstance(name, str) and name in self.currency_names

    def test_currency_symbol_no_code_supplied(self, faker, num_samples):
        for _ in range(num_samples):
            symbol = faker.currency_symbol()
            assert isinstance(symbol, str)
            assert symbol in self.provider.currency_symbols.values()

    @patch("faker.providers.currency.Provider.random_element")
    def test_currency_symbol_with_valid_code(self, mock_random_element, faker):
        symbol = faker.currency_symbol(code="USD")
        assert symbol == "$"
        mock_random_element.assert_not_called()

    @patch("faker.providers.currency.Provider.random_element")
    def test_currency_symbol_with_invalid_code(self, mock_random_element, faker):
        invalid_code = "FTW"
        with pytest.raises(KeyError):
            faker.currency_symbol(code=invalid_code)
        mock_random_element.assert_not_called()

    def test_cryptocurrency(self, faker, num_samples):
        for _ in range(num_samples):
            cur = faker.cryptocurrency()
            assert isinstance(cur, tuple)
            assert cur in self.cryptocurrencies

    def test_cryptocurrency_code(self, faker, num_samples):
        for _ in range(num_samples):
            code = faker.cryptocurrency_code()
            assert isinstance(code, str) and code in self.cryptocurrency_codes

    def test_cryptocurrency_name(self, faker, num_samples):
        for _ in range(num_samples):
            name = faker.cryptocurrency_name()
            assert isinstance(name, str) and name in self.cryptocurrency_names

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestAzAz:
    """Test az_AZ currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.az_AZ import Provider as AzAzCurrencyProvider

        cls.provider = AzAzCurrencyProvider
        cls.currencies = cls.provider.currencies

    def test_currency(self, faker, num_samples):
        for _ in range(num_samples):
            cur = faker.currency()
            assert isinstance(cur, tuple) and cur in self.currencies

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestRuRu:
    """Test ru_RU currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.ru_RU import Provider as RuRuCurrencyProvider

        cls.provider = RuRuCurrencyProvider
        cls.currencies = cls.provider.currencies
        cls.currency_codes, cls.currency_names = tuple(zip(*cls.currencies))

    def test_currency(self, faker, num_samples):
        for _ in range(num_samples):
            cur = faker.currency()
            assert isinstance(cur, tuple) and cur in self.currencies

    def test_currency_name(self, faker, num_samples):
        for _ in range(num_samples):
            name = faker.currency_name()
            assert isinstance(name, str) and name in self.currency_names

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestCsCz:
    """Test cs_CZ currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.cs_CZ import Provider as CsCzCurrencyProvider

        cls.provider = CsCzCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestDeAt:
    """Test de_AT currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.de_AT import Provider as DeAtCurrencyProvider

        cls.provider = DeAtCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestDeDe:
    """Test de_DE currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.de_DE import Provider as DeDeCurrencyProvider

        cls.provider = DeDeCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestEnAu:
    """Test en_AU currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.en_AU import Provider as EnAuCurrencyProvider

        cls.provider = EnAuCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestEnCa:
    """Test en_CA currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.en_CA import Provider as EnCaCurrencyProvider

        cls.provider = EnCaCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestEsEs:
    """Test es_ES currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.es_ES import Provider as EsEsCurrencyProvider

        cls.provider = EsEsCurrencyProvider
        cls.currencies = cls.provider.currencies
        cls.currency_codes, cls.currency_names = tuple(zip(*cls.currencies))

    def test_currency(self, faker, num_samples):
        for _ in range(num_samples):
            cur = faker.currency()
            assert cur in self.currencies

    def test_currency_name(self, faker, num_samples):
        for _ in range(num_samples):
            name = faker.currency_name()
            assert name in self.currency_names

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestFrCa:
    """Test fr_CA currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.fr_CA import Provider as FrCaCurrencyProvider

        cls.provider = FrCaCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestFrFr:
    """Test fr_FR currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.fr_FR import Provider as FrFrCurrencyProvider

        cls.provider = FrFrCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestItIt:
    """Test it_IT currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.it_IT import Provider as ItItCurrencyProvider

        cls.provider = ItItCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestPlPl:
    """Test pl_PL currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.pl_PL import Provider as PlPlCurrencyProvider

        cls.provider = PlPlCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestSkSk:
    """Test sk_SK currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.sk_SK import Provider as SkSkCurrencyProvider

        cls.provider = SkSkCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestSvSe:
    """Test sv_SE currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.sv_SE import Provider as SvSeCurrencyProvider

        cls.provider = SvSeCurrencyProvider
        cls.currencies = cls.provider.currencies
        cls.currency_codes, cls.currency_names = tuple(zip(*cls.currencies))

    def test_currency(self, faker, num_samples):
        for _ in range(num_samples):
            cur = faker.currency()
            assert cur in self.currencies

    def test_currency_name(self, faker, num_samples):
        for _ in range(num_samples):
            name = faker.currency_name()
            assert name in self.currency_names

class TestThTh:
    """Test th_TH currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.th_TH import Provider as ThThCurrencyProvider

        cls.provider = ThThCurrencyProvider
        cls.currencies = cls.provider.currencies
        cls.currency_codes, cls.currency_names = tuple(zip(*cls.currencies))

    def test_currency(self, faker, num_samples):
        for _ in range(num_samples):
            cur = faker.currency()
            assert cur in self.currencies

    def test_currency_name(self, faker, num_samples):
        for _ in range(num_samples):
            name = faker.currency_name()
            assert name in self.currency_names

class TestRoRo:
    """Test ro_RO currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.ro_RO import Provider as RoRoCurrencyProvider

        cls.provider = RoRoCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestPtBr:
    """Test pt_BR currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.pt_BR import Provider as PtBrCurrencyProvider

        cls.provider = PtBrCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestNlNl:
    """Test nl_NL currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.nl_NL import Provider as NlCurrencyProvider

        cls.provider = NlCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)

class TestElGr:
    """Test nl_NL currency provider"""

    num_samples = 100

    @classmethod
    def setup_class(cls):
        from faker.providers.currency.el_GR import Provider as ElGrCurrencyProvider

        cls.provider = ElGrCurrencyProvider

    def test_pricetag(self, faker, num_samples):
        for _ in range(num_samples):
            pricetag = faker.pricetag()
            assert isinstance(pricetag, str)


text:
module Arel
  class Join
    include Relation

    attr_reader :relation1, :relation2, :predicates

    def initialize(relation1, relation2 = Nil.instance, *predicates)
      @relation1  = relation1
      @relation2  = relation2
      @predicates = predicates
      @attributes = nil
    end

    def name
      relation1.name
    end

    def attributes
      @attributes ||= (relation1.externalize.attributes | relation2.externalize.attributes).bind(self)
    end

    def wheres
      # TESTME bind to self?
      relation1.externalize.wheres
    end

    def ons
      @ons ||= @predicates.collect { |p| p.bind(self) }
    end

    # TESTME
    def externalizable?
      relation1.externalizable? or relation2.externalizable?
    end

    def join?
      true
    end

    def engine
      relation1.engine != relation2.engine ? Memory::Engine.new : relation1.engine
    end

    def table_sql(formatter = Sql::TableReference.new(self))
      relation1.externalize.table_sql(formatter)
    end

    def joins(environment, formatter = Sql::TableReference.new(environment))
      @joins ||= begin
        this_join = [
          join_sql,
          relation2.externalize.table_sql(formatter),
          ("ON" unless predicates.blank?),
          (ons + relation2.externalize.wheres).collect { |p| p.bind(environment.relation).to_sql(Sql::WhereClause.new(environment)) }.join(' AND ')
        ].compact.join(" ")
        [relation1.joins(environment), this_join, relation2.joins(environment)].compact.join(" ")
      end
    end

    def eval
      result = []
      relation1.call.each do |row1|
        relation2.call.each do |row2|
          combined_row = row1.combine(row2, self)
          if predicates.all? { |p| p.eval(combined_row) }
            result << combined_row
          end
        end
      end
      result
    end

    def to_sql(formatter = nil)
      compiler.select_sql
    end
  end

  class InnerJoin < Join
    def join_sql; "INNER JOIN" end
  end

  class OuterJoin < Join
    def join_sql; "LEFT OUTER JOIN" end
  end

  class StringJoin < Join
    def joins(environment, formatter = Sql::TableReference.new(environment))
       [relation1.joins(environment), relation2].compact.join(" ")
    end

    def externalizable?
      relation1.externalizable?
    end

    def attributes
      relation1.externalize.attributes
    end

    def engine
      relation1.engine
    end
  end
end


text:
http request header

    POST /upload?upload_progress_id=12344 HTTP/1.1
    Host: localhost:3000
    Content-Length: 1325
    Origin: http://localhost:3000
    ... other headers ...
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L

    ------WebKitFormBoundaryePkpFF7tjBAqx29L
    Content-Disposition: form-data; name="MAX_FILE_SIZE"

    100000
    ------WebKitFormBoundaryePkpFF7tjBAqx29L
    Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
    Content-Type: application/x-object

    ... contents of file goes here ...
    ------WebKitFormBoundaryePkpFF7tjBAqx29L--

ref: http://stackoverflow.com/questions/8659808/how-does-http-file-upload-work


text:
package org.mapfish.print.map.style.json;

import com.google.common.collect.Maps;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

public class MapfishJsonStyleVersion2Test {
    @Test
    public void testResolveAllValues() throws Exception {
        Map<String, String> values = Maps.newHashMap();
        values.put("val1", "value");
        values.put("val2", "${val1}2");
        values.put("val3", "${val2}--3${val1}");
        values.put("val4", "pre- ${val3} -- ${val1} -- ${val2} -post");
        values.put("val5", "${doesNotExist}");

        Map<String, String> updated = MapfishJsonStyleVersion2.resolveAllValues(values);
        assertEquals(5, updated.size());
        assertEquals("value", updated.get("val1"));
        assertEquals("value2", updated.get("val2"));
        assertEquals("value2--3value", updated.get("val3"));
        assertEquals("pre- value2--3value -- value -- value2 -post", updated.get("val4"));
        assertEquals("${doesNotExist}", updated.get("val5"));
    }

}


text:
#!/usr/bin/env node

'use strict';
//@ts-check

const path = require('path');
const ln = require('./linking');

const root = path.dirname(path.dirname(__dirname));

(async function main() {
	console.log('Symlinking node modules for publish setup');

	// Hard link the client to have a real path from the node_modules folder
	const extensionFolder = path.join(root, 'client-node-tests');
	await ln.tryHardLink(path.join(root, 'client'), path.join(extensionFolder, 'node_modules', 'vscode-languageclient'));
})();


text:
using System.IO;

namespace MattermostCrmService.Wrappers
{
    public class AttachmentFileWrapper
    {
        public Stream FileData { get; set; }
        public string MimeType { get; set; }
    }
}


text:
import {Component, ChangeDetectorRef} from '@angular/core';
import {NgRedux} from '@angular-redux/store';

import {apiSetData2} from '../store/api.Actions';

let ctrlTemplate = `

{{data2.name}}

{{data2.setDateTime}}

Click here to change

  `;

const inLine = ['.hiDiv {text-align: center;}', '.loDiv {color: orange;}', '.newDiv {color: NavajoWhite;}'];

@Component({
  selector: 'app-child',
  template: ctrlTemplate,
  styles: inLine
})
export class AppChild implements OnDestroy {
  constructor(changeDetectorRef, ngRedux) {
    this.changeDetectorRef = changeDetectorRef;
    this.ngRedux = ngRedux;
    this.data2 = this.ngRedux.getState().data2;
    this.unsubscribe = this.ngRedux.subscribe(this.subscribeToRedux2);
    this.divName = 'loDiv';
  }

  changeIt = () => {
    const newData = {
      name: 'Hello Child after dispatch.',
      setDateTime: new Date().toLocaleString()
    };

    this.ngRedux.dispatch(apiSetData2(newData));
    this.divName = this.divName === 'loDiv' ? 'newDiv' : 'loDiv';
  }

  ngOnDestroy() {
    this.unsubscribe();
  }

  subscribeToRedux2 = () => {
    this.data2 = this.ngRedux.getState().data2;
    this.changeDetectorRef.detectChanges();
  }
}
AppChild.parameters = [[ChangeDetectorRef], [NgRedux]];


text:
DOMAIN=`cat /.django`
uwsgi --ini /${DOMAIN}/cfg/django.ini --uid 1000 --gid 1000 &

# start nginx
exec nginx


text:
package com.modinfodesigns.property.transform.string;

import com.modinfodesigns.property.IDataList;

public interface IDataListRenderer
{
  public String renderDataList( IDataList dList );
}


text:
<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "areas".
 *
 * @property integer $id
 * @property string $short_name
 * @property string $full_name
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property Districts[] $districts
 */
class Areas extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'areas';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['short_name', 'full_name'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['short_name', 'full_name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'short_name' => Yii::t('app', 'Area short name'),
            'full_name' => Yii::t('app', 'Area full name'),
            'status' => Yii::t('app', 'Status'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDistricts()
    {
        return $this->hasMany(Districts::className(), ['area_id' => 'id']);
    }

    /**
    * @inheritdoc
    */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }
}


text:
namespace tator { namespace video_annotator {

namespace {
  static const int kMaxBufferSize = 50;
  static const int kTrimBound = kMaxBufferSize / 2;
}

Player::Player()
  : QObject()
  , video_path_()
  , frame_rate_(0.0)
  , stopped_(true)
  , image_()
  , current_speed_(0.0)
  , codec_context_(nullptr)
  , format_context_(nullptr)
  , packet_()
  , stream_index_(-1)
  , frame_(nullptr)
  , frame_rgb_(nullptr)
  , sws_context_(nullptr)
  , delay_(0.0)
  , dec_frame_(0)
  , req_frame_(0)
  , seek_map_()
  , frame_buffer_()
  , frame_mutex_()
  , buffering_(false)
  , condition_() {
  av_register_all();
  av_init_packet(&packet_);
}

Player::~Player() {
  reinit();
  condition_.wakeOne();
}

void Player::loadVideo(QString filename) {
  reinit();
  video_path_ = filename;
  frame_buffer_.clear();
  format_context_ = avformat_alloc_context();
  frame_ = av_frame_alloc();
  frame_rgb_ = av_frame_alloc();
  int status = avformat_open_input(
    &format_context_,
    filename.toStdString().c_str(),
    nullptr,
    nullptr);
  if(status != 0) {
    std::string msg(
        std::string("Failed to load media at ") +
        filename.toStdString() +
        std::string("!"));
    emit error(QString(msg.c_str()));
    return;
  }
  status = avformat_find_stream_info(format_context_, nullptr);
  if(status < 0) {
    std::string msg(
        std::string("Couldn't find stream information for video ") +
        filename.toStdString() +
        std::string("!"));
    emit error(QString(msg.c_str()));
    return;
  }
  stream_index_ = -1;
  status = av_find_best_stream(
      format_context_, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
  if(status < 0) {
    std::string msg(
        std::string("File does not contain a video stream ") +
        filename.toStdString() +
        std::string("!"));
    emit error(QString(msg.c_str()));
    return;
  }
  stream_index_ = status;
  AVStream *stream = format_context_->streams[stream_index_];
  frame_rate_ =
    static_cast<double>(stream->avg_frame_rate.num) /
    static_cast<double>(stream->avg_frame_rate.den);
  uint64_t num_frames_est = format_context_->duration;
  num_frames_est /= AV_TIME_BASE;
  num_frames_est *= frame_rate_;
  emit mediaLoadStart(num_frames_est / 1000);
  AVCodec *codec = avcodec_find_decoder(stream->codecpar->codec_id);
  if(codec == nullptr) {
    std::string msg(
        std::string("Unsupported codec in file ") +
        filename.toStdString() +
        std::string("!"));
    emit error(QString(msg.c_str()));
    return;
  }
  if(codec_context_ != nullptr) {
    avcodec_free_context(&codec_context_);
  }
  codec_context_ = avcodec_alloc_context3(codec);
  if(codec_context_ == nullptr) {
    std::string msg(
        std::string("Failed to allocate codec context for file ") +
        filename.toStdString() +
        std::string("!"));
    emit error(QString(msg.c_str()));
    return;
  }
  status = avcodec_parameters_to_context(codec_context_, stream->codecpar);
  if(status < 0) {
    std::string msg(
        std::string("Failed to copy codec parameters to codec context for ") +
        filename.toStdString() +
        std::string("!"));
    emit error(QString(msg.c_str()));
    return;
  }
  status = avcodec_open2(codec_context_, codec, nullptr);
  if(status < 0) {
    std::string msg(
        std::string("Could not open codec for file ") +
        filename.toStdString() +
        std::string("!"));
    emit error(QString(msg.c_str()));
    return;
  }
  sws_context_ = sws_getContext(
    codec_context_->width,
    codec_context_->height,
    codec_context_->pix_fmt,
    codec_context_->width,
    codec_context_->height,
    AV_PIX_FMT_RGB24,
    SWS_BICUBIC,
    nullptr, nullptr, nullptr);
  seek_map_.clear();
  qint64 frame_index = 0;
  avcodec_flush_buffers(codec_context_);
  while(true) {
    av_packet_unref(&packet_);
    status = av_read_frame(format_context_, &packet_);
    if(status < 0) {
      break;
    }
    if(packet_.stream_index == stream_index_) {
      if(frame_index % 1000 == 0) {
        emit loadProgress(frame_index / 1000);
      }
      int got_picture = 1;
      if(frame_index < 10) {
        status = avcodec_decode_video2(
          codec_context_,
          frame_,
          &got_picture,
          &packet_);
      }
      if(got_picture) {
        seek_map_.left.insert({frame_index, packet_.dts});
        ++frame_index;
      }
    }
  }
  av_seek_frame(
      format_context_,
      stream_index_,
      seek_map_.right.begin()->first,
      AVSEEK_FLAG_BACKWARD);
  current_speed_ = frame_rate_;
  delay_ = 1000000.0 / frame_rate_;
  image_ = QImage(
      codec_context_->width,
      codec_context_->height,
      QImage::Format_RGB32);
  if(frame_rgb_ != nullptr) {
    if(frame_rgb_->data[0] != nullptr) {
      av_freep(&frame_rgb_->data[0]);
    }
  }
  av_image_alloc(
      frame_rgb_->data,
      frame_rgb_->linesize,
      codec_context_->width,
      codec_context_->height,
      AV_PIX_FMT_RGB24,
      1);
  emit mediaLoaded(filename, frame_rate_);
  emit playbackRateChanged(current_speed_);
  emit durationChanged(seek_map_.size());
  emit resolutionChanged(codec_context_->width, codec_context_->height);
}

void Player::play() {
  if(stopped_ == true) {
    stopped_ = false;
  }
  emit stateChanged(stopped_);
  while(stopped_ == false) {
    QTime t;
    t.start();
    setCurrentFrame(req_frame_ + 1);
    emit processedImage(image_, req_frame_);
    double usec = 1000.0 * t.restart();
    processWait(std::round(delay_ - usec));
  }
}

void Player::stop() {
  stopped_ = true;
  emit stateChanged(stopped_);
}

void Player::getOneFrame() {
  QMutexLocker locker(&frame_mutex_);
  bool valid = false;
  int count_errs = 0;
  const int max_errs = 1 << 9;
  int got_picture;
  while(!valid) {
    av_packet_unref(&packet_);
    int status = av_read_frame(format_context_, &packet_);
    if(status == AVERROR(EAGAIN)) {
      continue;
    }
    if(status < 0) {
      stop();
      break;
    }
    if(packet_.stream_index != stream_index_) {
      av_packet_unref(&packet_);
    }
    else {
      auto it = seek_map_.right.find(packet_.dts);
      if(!(it == seek_map_.right.end())) {
        dec_frame_ = it->second;
      }
      status = avcodec_decode_video2(
        codec_context_,
        frame_,
        &got_picture,
        &packet_);
      if(got_picture) {
        sws_scale(
            sws_context_,
            frame_->data,
            frame_->linesize,
            0,
            codec_context_->height,
            frame_rgb_->data,
            frame_rgb_->linesize);
        uint8_t *src = (uint8_t*)(frame_rgb_->data[0]);
        for(int y = 0; y < codec_context_->height; ++y) {
          QRgb *scan_line = (QRgb*)image_.scanLine(y);
          for(int x = 0; x < codec_context_->width; ++x) {
            scan_line[x] = qRgb(src[3*x], src[3*x+1], src[3*x+2]);
          }
          src += frame_rgb_->linesize[0];
        }
        frame_buffer_.insert({dec_frame_, image_});
        if(frame_buffer_.size() > kMaxBufferSize) {
          for(auto buf_it = frame_buffer_.cbegin();
              buf_it != frame_buffer_.cend();) {
            if(qAbs(buf_it->first - req_frame_) > kTrimBound) {
              buf_it = frame_buffer_.erase(buf_it);
            }
            else {
              ++buf_it;
            }
          }
        }
        valid = true;
      }
      else {
        count_errs++;
        if(count_errs > max_errs) {
          break;
        }
      }
    }
  }
}

void Player::speedUp() {
  delay_ /= 2.0;
  if(delay_ < 1.0) delay_ = 1.0;
  current_speed_ *= 2.0;
  emit playbackRateChanged(current_speed_);
}

void Player::slowDown() {
  delay_ *= 2.0;
  current_speed_ /= 2.0;
  emit playbackRateChanged(current_speed_);
}

void Player::nextFrame() {
  setCurrentFrame(req_frame_ + 1);
  emit processedImage(image_, req_frame_);
}

void Player::prevFrame() {
  setCurrentFrame(req_frame_ - 1);
  emit processedImage(image_, req_frame_);
  if(buffering_ == false) {
    buffering_ = true;
    auto buf_it = frame_buffer_.begin();
    if(req_frame_ - buf_it->first < kTrimBound / 2) {
      buffer(req_frame_, 1000);
    }
    buffering_ = false;
  }
}

void Player::setCurrentFrame(qint64 frame_num) {
  qint64 bounded = frame_num < 0 ? 0 : frame_num;
  const qint64 max_frame = seek_map_.left.rbegin()->first;
  bounded = bounded > max_frame ? max_frame : bounded;
  req_frame_ = bounded;
  if(frame_num - dec_frame_ == 1) {
    getOneFrame();
  }
  else {
    buffering_ = true;
    auto buf_it = frame_buffer_.find(frame_num);
    if(buf_it != frame_buffer_.end()) {
      image_ = buf_it->second;
    }
    else {
      buffer(bounded, 0);
    }
    buffering_ = false;
  }
}

void Player::buffer(qint64 frame_num, qint64 wait) {
  qint64 seek_to = frame_num - kTrimBound;
  seek_to = seek_to < 0 ? 0 : seek_to;
  auto it = seek_map_.left.find(seek_to);
  if(it != seek_map_.left.end()) {
    int status = av_seek_frame(
        format_context_,
        stream_index_,
        it->second,
        AVSEEK_FLAG_BACKWARD);
    if(status < 0) {
      emit error("Error seeking to frame!");
      return;
    }
    avcodec_flush_buffers(codec_context_);
    while(true) {
      getOneFrame();
      if(dec_frame_ >= frame_num) {
        break;
      }
      if(wait > 0) {
        processWait(wait);
      }
    }
  }
}

void Player::setFrame(qint64 frame) {
  setCurrentFrame(frame);
  emit processedImage(image_, req_frame_);
}

void Player::processWait(qint64 usec) {
  QTime die_time = QTime::currentTime().addMSecs(usec / 1000);
  QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
  while(QTime::currentTime() < die_time) {
    QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
  }
}

void Player::reinit() {
  QMutexLocker locker(&frame_mutex_);
  if(codec_context_ != nullptr) {
    avcodec_close(codec_context_);
    codec_context_ = nullptr;
  }
  if(format_context_ != nullptr) {
    avformat_close_input(&format_context_);
    format_context_ = nullptr;
  }
  if(frame_rgb_ != nullptr) {
    if(frame_rgb_->data[0] != nullptr) {
      av_freep(&frame_rgb_->data[0]);
    }
    av_frame_free(&frame_rgb_);
    frame_rgb_ = nullptr;
  }
  if(frame_ != nullptr) {
    av_frame_free(&frame_);
    frame_ = nullptr;
  }
  stopped_ = true;
}

#include "moc_player.cpp"

}} // namespace tator::gui


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.05.23 at 02:47:00 PM EDT
//

package oasis.names.tc.xacml._3_0.core.schema.wd_17;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CombinerParametersType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="CombinerParametersType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}CombinerParameter" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CombinerParametersType", propOrder = {
    "combinerParameter"
})
@XmlSeeAlso({
    RuleCombinerParametersType.class,
    PolicySetCombinerParametersType.class,
    PolicyCombinerParametersType.class
})
public class CombinerParametersType {

    @XmlElement(name = "CombinerParameter")
    protected List<CombinerParameterType> combinerParameter;

    /**
     * Gets the value of the combinerParameter property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the combinerParameter property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getCombinerParameter().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CombinerParameterType }
     *
     *
     */
    public List<CombinerParameterType> getCombinerParameter() {
        if (combinerParameter == null) {
            combinerParameter = new ArrayList<CombinerParameterType>();
        }
        return this.combinerParameter;
    }

}


text:
package com.administrator.gdemo.persenter;
//			          _ooOoo_
//	           	     o8888888o
//                   88" . "88
//                   (| -_- |)
//                    O\ = /O
//                ____/`---'\____
//              .   ' \\| |// `.
//               / \\||| : |||// \
//             / _||||| -:- |||||- \
//               | | \\\ - /// | |
//             | \_| ''\---/'' | |
//            \ .-\__ `-` ___/-. /
//          ___`. .' /--.--\ `. . __
//       ."" '< `.___\_<|>_/___.' >'"".
//      | | : `- \`.;`\ _ /`;.`/ - ` : | |
//        \ \ `-. \_ __\ /__ _/ .-` / /
//======`-.____`-.___\_____/___.-`____.-'======
//                   `=---='
//
//.............................................
//               佛祖保佑             永无BUG

import android.content.Context;
import android.view.View;

import com.administrator.gdemo.MainActivity;
import com.administrator.gdemo.config.ModelAction;
import com.administrator.gdemo.config.ViewAction;
import com.administrator.gdemo.model.LoginModel;
import com.administrator.gdemo.view.LoginView;

import fast.glibrary.base.BaseActivity;
import fast.mvp.base.ActionDispatcher;
import fast.mvp.base.BaseModelAction;
import fast.mvp.base.BaseUserAction;
import fast.mvp.base.WorkDoneDispatcher;
import fast.mvp.persenter.GPresenter;

/**
 * Created by Administrator on 2017/2/18.
 * Description:
 * Function:
 */

public class LoginPresenter extends GPresenter {
    private LoginModel mModel;
    private LoginView mView;
    private ActionDispatcher mDispatcher;
    private WorkDoneDispatcher mWorkDone;
    private BaseActivity mActivity;

    public LoginPresenter(BaseActivity context, View view) {
        super(context);
        this.mActivity = context;
        mDispatcher = action -> dispatchUserAction(action);
        mWorkDone = action -> dispatchGModelDone(action);
        mModel = new LoginModel(this);
        mView = new LoginView(view, this);
    }

    @Override
    public void dispatchUserAction(BaseUserAction action) {
        switch (action.mAction) {
            case ViewAction.LoginClick:
                action.setParams(mView.getLoginParams());
                mModel.dispatchUserAction(action);
                break;
        }
    }

    @Override
    public void dispatchGModelDone(BaseModelAction action) {
        switch (action.mAction) {
            case ModelAction.LoginBack:
                mActivity.start(MainActivity.class);
                break;
        }
    }
}


text:
START_ATF_NAMESPACE
    namespace vc_attributes
    {
        namespace atl
        {
            template<>
            struct soap_namespaceAttribute
            {
                const char *value;
            };
        }; // end namespace atl
    }; // end namespace vc_attributes
END_ATF_NAMESPACE


text:
import unittest

from xhttpnode import schema
from xhttpnode.schema import ET

class SchemaTestCase(unittest.TestCase):
    """Test case for the schema module"""

    def test_parse_schema_tree(self):
        #create a simple tree with a single schema node
        element = ET.XML("""
            <xhttp xmlns:xhttp="http://www.xhttp.org/schema" version="1.0">
                <xhttp:schema version="1.0"></xhttp:schema>
                <xhttp:schema version="2.0"></xhttp:schema>
            </xhttp>
        """)
        tree = ET.ElementTree(element=element)
        #get schemas dictionary from the tree
        schemas = schema.parse_schema_tree(tree)

        #there should be only two schemas
        self.assertEqual(len(schemas), 2)
        #schema version 2.0 must be available
        self.assertIn("2.0", schemas)

    def test_parse_schema_element(self):
        #create a schema node with some info
        element = ET.XML("""
            <xhttp xmlns:xhttp="http://www.xhttp.org/schema" version="1.0">
                <xhttp:schema version="1.0">
                    <xhttp:info name="link" value="http://www.xhttp.org"/>
                    <xhttp:info name="service" value="example"/>
                    <xhttp:action name="test2" function="test2">
                        <xhttp:exception code="1" message="Empty"/>
                        <xhttp:argument name="dummy" type="4"/>
                        <xhttp:return type="4"/>
                    </xhttp:action>
                </xhttp:schema>
            </xhttp>
        """)
        schema_tag = schema.ns('schema')
        schema_element_list = list(element.iter(schema_tag))
        #get schema dictionary
        schema_dict = schema.parse_schema_element(schema_element_list[0])

        #check some properties that should be available
        schema_dict_expected = {}
        schema_dict_expected['version'] = "1.0"
        schema_dict_expected['link'] = "http://www.xhttp.org"
        schema_dict_expected['service'] = "example"
        self.assertDictContainsSubset(schema_dict_expected, schema_dict)

        #schema should contain 1 actions
        self.assertEqual(len(schema_dict['actions']), 1)

    def test_parse_action_element(self):
        #create an action node with some info
        element = ET.XML("""
            <xhttp xmlns:xhttp="http://www.xhttp.org/schema" version="1.0">
                <xhttp:action name="test" function="test_fn">
                    <xhttp:exception code="1" message="Empty"/>
                    <xhttp:exception code="99" message="Dummy"/>
                    <xhttp:argument name="dummy" type="4"/>
                    <xhttp:return type="4"/>
                </xhttp:action>
            </xhttp>
        """)
        action_tag = schema.ns('action')
        action_element_list = list(element.iter(action_tag))

        #get action dictionary
        action = schema.parse_action_element(action_element_list[0])

        #check some properties that should be available
        action_expected = {}
        action_expected['name'] = "test"
        action_expected['function'] = "test_fn"
        action_expected['return'] = "4"
        self.assertDictContainsSubset(action_expected, action)

        #there should be 2 exceptions
        self.assertEqual(len(action['exceptions']), 2)
        #dummy exception code must be available
        self.assertIn('99', action['exceptions'])
        #check mandatory exception properties
        first_exception = action['exceptions']['99']
        self.assertIn('code', first_exception)
        self.assertIn('message', first_exception)

        #there should be 1 argument
        self.assertEqual(len(action['args']), 1)
        #dummy argument name must be available
        self.assertIn('dummy', action['args'])
        #check mandatory argument properties
        first_argument = action['args']['dummy']
        self.assertIn('name', first_argument)
        self.assertIn('type', first_argument)


text:
std::map<std::string, EquipmentType> EquipmentProtoFactory::_type;

// Constructor
EquipmentProtoFactory::EquipmentProtoFactory()
{
    _bike = new BikePrototype;
    _treadmill = new TreadmillPrototype;

    _type["bike"] = bike;
    _type["treadmill"] = treadmill;
    _equipmentId = 1;
}

// Destructor
EquipmentProtoFactory::~EquipmentProtoFactory()
{
    delete _bike;
    delete _treadmill;
}

// Get new equipment object. Clone prototype
EquipmentPrototype* EquipmentProtoFactory::getEquipment(EquipmentType type)
{
    EquipmentPrototype* newEquipment;

    switch (type) {
        case bike:
            newEquipment = _bike->clone();
            break;
        case treadmill:
            newEquipment = _treadmill->clone();
            break;
    }

    newEquipment->setId(_equipmentId);
    _equipmentId++;

    return newEquipment;
}

// Get the EquipmentType enum from string, throw an error if can't find it
EquipmentType EquipmentProtoFactory::getEquipmentType(std::string type)
{
    if (_type.find(type) == _type.end()){
        throw 1;
    } else {
        return _type[type];
    }

}

// Get a list of type TODO -- make this dynamic
std::string EquipmentProtoFactory::getTypes()
{
    return "bike, treadmill";
}

void EquipmentProtoFactory::setId(int currentId)
{
    _equipmentId = currentId;
}


text:
package test.junit4;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

public class ClassRuleJUnit4Sample {

    @ClassRule
    public static ExternalResource resource = new ExternalResource() {
        @Override
        protected void before() throws Throwable {
            throw new IllegalArgumentException("before");
        }

        @Override
        protected void after() {
            throw new IllegalArgumentException("after");
        }
    };

    @Test
    public void myTest() {
        System.out.println("yay!");
    }
}


text:
import React from 'react'
import { ContactAdd } from './ContactForm'
import { Contact } from './ContactComponent'

export const Contacts = (props) => (

Contacts

Add

        <ContactAdd />

    <button className='btn btn-default' onClick={props.fetch}>
      Fetch
    </button>

{props.contacts.map(item =>
        <ContactSmall key={item.id} contact={item} onSelect={props.selectContact} />
      )}

      {props.selectedContact &&

        <Contact contact={props.selectedContact} />

}

)

const ContactSmall = (props) => {
  return (
 props.onSelect(props.contact.id)}>
    {`${props.contact.first_name} ${props.contact.last_name}`}

)
}

ContactSmall.propTypes = {
  contact: React.PropTypes.object.isRequired,
  onSelect: React.PropTypes.func.isRequired
}

Contacts.propTypes = {
  contacts    : React.PropTypes.array.isRequired,
  selectedContact: React.PropTypes.object,
  increment   : React.PropTypes.func.isRequired,
  fetch       : React.PropTypes.func.isRequired,
  selectContact: React.PropTypes.func.isRequired
}

export default Contacts


text:
class Node:
    def __init__(self, info):
        self.info = info
        self.left = None
        self.right = None
        self.level = None

    def __str__(self):
        return str(self.info)

class BinarySearchTree:
    def __init__(self):
        self.root = None

    def create(self, val):
        if self.root is None:
            self.root = Node(val)
        else:
            current = self.root

            while True:
                if val < current.info:
                    if current.left:
                        current = current.left
                    else:
                        current.left = Node(val)
                        break
                elif val > current.info:
                    if current.right:
                        current = current.right
                    else:
                        current.right = Node(val)
                        break
                else:
                    break

# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
class Node:
      def __init__(self,info):
          self.info = info
          self.left = None
          self.right = None

       // this is a node of the tree , which contains info as data, left , right
'''

def lca(root, v1, v2):
    if (v1 <= root.info <= v2 or v2 <= root.info <= v1):
        return root
    elif (root.info < v1 and root.info < v2):
        return lca(root.right, v1, v2)
    elif (root.info > v1 and root.info > v2):
        return lca(root.left, v1, v2)

tree = BinarySearchTree()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenopeziza laricina f. laricina

### Remarks
null


text:
namespace blink {

class LayoutBoxModelObjectTest : public RenderingTest {
protected:
    const FloatRect& getScrollContainerRelativeContainingBlockRect(const StickyPositionScrollingConstraints& constraints) const
    {
        return constraints.scrollContainerRelativeContainingBlockRect();
    }

    const FloatRect& getScrollContainerRelativeStickyBoxRect(const StickyPositionScrollingConstraints& constraints) const
    {
        return constraints.scrollContainerRelativeStickyBoxRect();
    }
};

// Verifies that the sticky constraints are correctly computed.
TEST_F(LayoutBoxModelObjectTest, StickyPositionConstraints)
{
    setBodyInnerHTML(""
        "

");
    LayoutBoxModelObject* scroller = toLayoutBoxModelObject(getLayoutObjectByElementId("scroller"));
    scroller->getScrollableArea()->scrollToYOffset(50);
    ASSERT_EQ(50.0, scroller->getScrollableArea()->scrollYOffset());
    LayoutBoxModelObject* sticky = toLayoutBoxModelObject(getLayoutObjectByElementId("sticky"));
    sticky->updateStickyPositionConstraints();
    ASSERT_EQ(scroller->layer(), sticky->layer()->ancestorOverflowLayer());

    const StickyPositionScrollingConstraints& constraints = scroller->getScrollableArea()->stickyConstraintsMap().get(sticky->layer());
    ASSERT_EQ(0.f, constraints.topOffset());

    // The coordinates of the constraint rects should all be with respect to the unscrolled scroller.
    ASSERT_EQ(IntRect(15, 115, 170, 370), enclosingIntRect(getScrollContainerRelativeContainingBlockRect(constraints)));
    ASSERT_EQ(IntRect(15, 115, 100, 100), enclosingIntRect(getScrollContainerRelativeStickyBoxRect(constraints)));
}

// Verifies that the sticky constraints are correctly computed.
TEST_F(LayoutBoxModelObjectTest, StickyPositionPercentageStyles)
{
    setBodyInnerHTML(""
        "

");
    LayoutBoxModelObject* scroller = toLayoutBoxModelObject(getLayoutObjectByElementId("scroller"));
    scroller->getScrollableArea()->scrollToYOffset(50);
    ASSERT_EQ(50.0, scroller->getScrollableArea()->scrollYOffset());
    LayoutBoxModelObject* sticky = toLayoutBoxModelObject(getLayoutObjectByElementId("sticky"));
    sticky->updateStickyPositionConstraints();
    ASSERT_EQ(scroller->layer(), sticky->layer()->ancestorOverflowLayer());

    const StickyPositionScrollingConstraints& constraints = scroller->getScrollableArea()->stickyConstraintsMap().get(sticky->layer());
    ASSERT_EQ(0.f, constraints.topOffset());

    ASSERT_EQ(IntRect(25, 145, 200, 330), enclosingIntRect(getScrollContainerRelativeContainingBlockRect(constraints)));
    ASSERT_EQ(IntRect(25, 145, 100, 100), enclosingIntRect(getScrollContainerRelativeStickyBoxRect(constraints)));
}

// Verifies that the sticky constraints are correct when the sticky position container is also
// the ancestor scroller.
TEST_F(LayoutBoxModelObjectTest, StickyPositionContainerIsScroller)
{
    setBodyInnerHTML(""
        "

");
    LayoutBoxModelObject* scroller = toLayoutBoxModelObject(getLayoutObjectByElementId("scroller"));
    scroller->getScrollableArea()->scrollToYOffset(50);
    ASSERT_EQ(50.0, scroller->getScrollableArea()->scrollYOffset());
    LayoutBoxModelObject* sticky = toLayoutBoxModelObject(getLayoutObjectByElementId("sticky"));
    sticky->updateStickyPositionConstraints();
    ASSERT_EQ(scroller->layer(), sticky->layer()->ancestorOverflowLayer());

    const StickyPositionScrollingConstraints& constraints = scroller->getScrollableArea()->stickyConstraintsMap().get(sticky->layer());
    ASSERT_EQ(IntRect(0, 0, 400, 1100), enclosingIntRect(getScrollContainerRelativeContainingBlockRect(constraints)));
    ASSERT_EQ(IntRect(0, 0, 100, 100), enclosingIntRect(getScrollContainerRelativeStickyBoxRect(constraints)));
}

// Verifies that the sticky constraints are correct when the sticky position object has an
// anonymous containing block.
TEST_F(LayoutBoxModelObjectTest, StickyPositionAnonymousContainer)
{
    setBodyInnerHTML(""
        "

");
    LayoutBoxModelObject* scroller = toLayoutBoxModelObject(getLayoutObjectByElementId("scroller"));
    scroller->getScrollableArea()->scrollToYOffset(50);
    ASSERT_EQ(50.0, scroller->getScrollableArea()->scrollYOffset());
    LayoutBoxModelObject* sticky = toLayoutBoxModelObject(getLayoutObjectByElementId("sticky"));
    sticky->updateStickyPositionConstraints();
    ASSERT_EQ(scroller->layer(), sticky->layer()->ancestorOverflowLayer());

    const StickyPositionScrollingConstraints& constraints = scroller->getScrollableArea()->stickyConstraintsMap().get(sticky->layer());
    ASSERT_EQ(IntRect(15, 115, 170, 370), enclosingIntRect(getScrollContainerRelativeContainingBlockRect(constraints)));
    ASSERT_EQ(IntRect(15, 165, 100, 100), enclosingIntRect(getScrollContainerRelativeStickyBoxRect(constraints)));
}
} // namespace blink


text:
Just run these three commands

    openssl genrsa -out node.key
    openssl req -new -key node.key -out csr.pem
    openssl x509 -req -days 9999 -in csr.pem -signkey node.key -out node.crt
    rm csr.pem

This will create your requred certificates and keys.


text:
set -eu

locks=$(find ./releaselocks -type d -name 'release-*' | sort)
fail=none

for lock in $locks; do
    echo "Testing $lock"
    protolock status --lockdir=${lock} | sort -fd > status && :
    diff status ${lock}/proto.lock.status > diff.out || fail=$lock
    rm status
    if [[ $fail != "none" ]]; then
        echo "Error $fail"
        cat diff.out
        rm diff.out
        exit 1
    fi
    rm diff.out
done


text:
package org.pentaho.big.data.impl.vfs.hdfs;

import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.URLFileName;
import org.apache.commons.vfs2.provider.URLFileNameParser;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.provider.VfsComponentContext;

public class HDFSFileNameParser extends URLFileNameParser {

  private static final HDFSFileNameParser INSTANCE = new HDFSFileNameParser();

  private HDFSFileNameParser() {
    super( -1 );
  }

  public static HDFSFileNameParser getInstance() {
    return INSTANCE;
  }

  @Override public FileName parseUri( VfsComponentContext context, FileName base, String filename )
    throws FileSystemException {
    URLFileName fileNameURLFileName = (URLFileName) super.parseUri( context, base, filename );

    return new URLFileName(
      fileNameURLFileName.getScheme(),
      getHostNameCaseSensitive( filename ),
      fileNameURLFileName.getPort(),
      fileNameURLFileName.getDefaultPort(),
      fileNameURLFileName.getUserName(),
      fileNameURLFileName.getPassword(),
      fileNameURLFileName.getPath(),
      fileNameURLFileName.getType(),
      fileNameURLFileName.getQueryString() );
  }

  /**
   * PDI-15565
   * <p>
   * the same logic as for extracting in org.apache.commons.vfs2.provider.HostFileNameParser.extractToPath
   *
   * @param fileUri file uri for hdfs file
   * @return case sensitive host name
   * @throws FileSystemException when format of url is not correct
   */
  private String getHostNameCaseSensitive( String fileUri ) throws FileSystemException {
    StringBuilder fullNameBuilder = new StringBuilder();
    UriParser.extractScheme( fileUri, fullNameBuilder );
    if ( fullNameBuilder.length() < 2 || fullNameBuilder.charAt( 0 ) != '/' || fullNameBuilder.charAt( 1 ) != '/' ) {
      throw new FileSystemException( "vfs.provider/missing-double-slashes.error", fileUri );
    }
    fullNameBuilder.delete( 0, 2 );
    extractPort( fullNameBuilder, fileUri );
    extractUserInfo( fullNameBuilder );
    return extractHostName( fullNameBuilder );
  }
}


text:
package com.doctorwho.com.primtive;

/**
 *
 * project_name :reflection-util
 * @author doctorWho
 *
 */

public enum Primitive {
	p_byte(byte.class),
	p_char(char.class),
	p_double(double.class),
	p_float(float.class),
	p_int(int.class),
	p_long(long.class),
	p_short(short.class),
	p_boolean(boolean.class);

	private Class<?> classT;
	public Class<?> getPrimitiveClass() {
		return this.classT;
	}

	public static Class<?> getPrimitiveClass(Class<?> classType) {
		Primitive[] primitives = Primitive.values();
		for (Primitive primitive : primitives) {
			if (classType.getName().equals(primitive.getPrimitiveClass().getName()) ) {
				return primitive.getPrimitiveClass();
			}
		}

		return null;
	}

	public static Object newInstance(Class<?> classType,String value) {
		if (classType == byte.class || classType == char.class ) {
			throw new UnsupportedOperationException();
		}

		if (classType == double.class) {
			return Double.parseDouble(value);
		}

		if (classType == float.class) {
			return Float.parseFloat(value);
		}

		if (classType == int.class) {
			return Integer.parseInt(value);
		}

		if (classType == long.class) {
			return Long.parseLong(value);
		}

		if (classType == short.class) {
			return Short.parseShort(value);
		}

		if (classType == boolean.class) {
			if ("1".equals(value)) {
				return true;
			}
			if ("0".equals(value)) {
				return false;
			}
			return Boolean.parseBoolean(value);
		}

		return null;
	}
	private Primitive(Class<?> classt){
		this.classT = classt;
	}
}


text:
<?php

namespace Application\Model;

class Materia{
	public $id;
	public $destaque;
	public $tituloDestaque;
	public $imagemDestaque;
	public $titulo;
	public $imagemMiniatura;
	public $olho;
	public $texto;

	public function exchangeArray($data){
		$this->id = (!empty($data['id'])) ? $data['id'] : null;
		$this->destaque = (!empty($data['destaque'])) ? $data['destaque'] : null;
		$this->tituloDestaque = (!empty($data['tituloDestaque'])) ? $data['tituloDestaque'] : null;
		$this->tituloDestaque_en = (!empty($data['tituloDestaque_en'])) ? $data['tituloDestaque_en'] : null;
		$this->imagemDestaque = (!empty($data['imagemDestaque'])) ? $data['imagemDestaque'] : null;
		$this->titulo = (!empty($data['titulo'])) ? $data['titulo'] : null;
		$this->titulo_en = (!empty($data['titulo_en'])) ? $data['titulo_en'] : null;
		$this->imagemMiniatura = (!empty($data['imagemMiniatura'])) ? $data['imagemMiniatura'] : null;
		$this->olho = (!empty($data['olho'])) ? $data['olho'] : null;
		$this->olho_en = (!empty($data['olho_en'])) ? $data['olho_en'] : null;
		$this->texto = (!empty($data['texto'])) ? $data['texto'] : null;
		$this->texto_en = (!empty($data['texto_en'])) ? $data['texto_en'] : null;
	}
}


text:
define([
    'some/module'
], function (
    someModule
) {
    'use strict';
    //TODO: PM-1234, X-99, PM-42

    /**
     * TODO TK-4711: Give this class a proper name!
     * @constructor
     */
    var Klass = function () {
    };

    Klass.prototype.myMethod = function () {
        // fixme! ABC-13
        return 42;
    };

    /**
     * TODO please fix in ABC-99
     */
    Klass.prototype.whatevs = function () {
    };

    // TODO: give this method a proper name!
    Klass.prototype.foo = function () {
    };

    // TODO ABC-99: what about someModule?!
    return Klass;

    // TODO ABC-1000: This is a story
});


text:
/**
 * PART OF mizraith_DigitalClock package
 *
 * State transition and state machine related functionality.
 * This is where "all" the work is really done.
 */
#include "DigitalClock_StatePackages.h"

#ifndef _mizraith_DigitalClockStateFunctions_H_
#define _mizraith_DigitalClockStateFunctions_H_

#include <Arduino.h>
#include "DigitalClock_Data.h"
#include "DigitalClock_Strings.h"
#include "DigitalClock_Common.h"
#include "DigitalClock_StateTypedefs.h"

namespace mizraith_DigitalClock {

    extern bool DEBUG_STATE_TRANSITIONS;   // Display 'state traces'  over the serial port.  Consumes ~2k of PROGMEM
    const bool DISPLAY_TO_SERIAL = false;  //print out 'display' as we go -- can generate a LOT of chatter, so slow down calls to update()!!!

    void startStateMachine(void);
    void handleEvent(uint8_t, int16_t);           //the main entry point

    void handleSubStateTimeout(uint8_t);

    //expect to be regularly called as a way to let state machine update the displays
    void update( void );

    /* State transition and function declarations */
    //-----main state transitions
    void handleMainState(const struct state *);
    void handleDisplayOptionsState(const struct state *);
    void handleSetTimeState(const struct state *);
    void handleStateWorker(const struct state *, const struct state **, uint8_t );

    void doNothingTransition(const struct state *);
    void startupState(const struct state *);
    void transitionToNormal(const struct state *);
    void transitionToDisplayOptions(const struct state *);
    void transitionToSetTime(const struct state *);

    //-----display option state transitions
    void exitDisplayOptions(const struct state *);

    void transitionToDisplay24Hr(const struct state *);
    void transitionToDisplayC(const struct state *);
    void transitionToDisplayTemp(const struct state *);
    void transitionToDisplayDate(const struct state *);
    void transitionToDisplayDayOfWeek(const struct state *);
    void transitionToDisplayInfo(const struct state *);
    void transitionToDisplayUserString(const struct state *);

    void adjustDisplay24Hr(const struct state *);
    void adjustDisplayC(const struct state *);
    void adjustDisplayTemp(const struct state *);
    void adjustDisplayDate(const struct state *);
    void adjustDisplayDayOfWeek(const struct state *);
    void adjustDisplayInfo(const struct state *);
    void adjustDisplayUserString(const struct state *);

    //-----set time state transitions
    void exitSetTime(const struct state *);

    void transitionToSetMinute(const struct state *);
    void transitionToSetMonth(const struct state *);
    void transitionToSetDay(const struct state *);
    void transitionToSetYear(const struct state *);
    void transitionToSetHour(const struct state *);
    void transitionToSetDayOfWeek(const struct state *);

    void adjustSetMinute(const struct state *);
    void adjustSetHour(const struct state *);
    void adjustSetMonth(const struct state *);
    void adjustSetDay(const struct state *);
    void adjustSetYear(const struct state *);
    void adjustSetDayOfWeek(const struct state *);

    //--------HELPER functions for this test class
    void loadStateVariableFromProgmemAddr( struct state *statescratch, state * StateAddressInProgmem);

    void printStateData(const struct state *);
    bool eventOutOfRange(uint8_t event);
    bool meetsBinaryAdjustmentCriteria(const struct state *s_p);
    bool binaryAdjustmentThresholdReachedThenClearAccumulated( void );
    bool adjustmentThresholdReachedThenClearAccumulated( uint8_t thresh );
    int8_t getAdjustment(const struct state *s_p, uint8_t thresh) ;
}

#endif


text:
let Test = require('../../option_test');

describe('Option `space-before-closing-brace`, detect', function() {
  describe('css', function() {
    it('Should detect no whitespace', function() {
      let test = new Test(this);
      test.shouldDetect(
          ['space-before-closing-brace'],
          'a{top:0}',
          {'space-before-closing-brace': ''}
      );
    });

    it('Should detect no whitespace (2 blocks)', function() {
      let test = new Test(this);
      test.shouldDetect(
          ['space-before-closing-brace'],
          'a{top:0} b { color: tomato; }',
          {'space-before-closing-brace': ''}
      );
    });

    it('Should detect whitespace', function() {
      let test = new Test(this);
      test.shouldDetect(
          ['space-before-closing-brace'],
          'a { top:0 }',
          {'space-before-closing-brace': ' '}
      );
    });

    it('Should detect whitespace (2 blocks)', function() {
      let test = new Test(this);
      test.shouldDetect(
          ['space-before-closing-brace'],
          'a { top:0 } b{color:tomato;}',
          {'space-before-closing-brace': ' '}
      );
    });

    it('Should detect whitespace (mix with block indent)', function() {
      let test = new Test(this);
      test.shouldDetect(
          ['space-before-closing-brace', 'block-indent'],
          'a {\n  top:0\n  }\nb{\n  color:tomato;\n  }',
          {'block-indent': '  ', 'space-before-closing-brace': '\n  '}
      );
    });
  });
});