text:
package io.cattle.platform.iaas.api.auth.integration.ldap.OpenLDAP;

import io.cattle.platform.archaius.util.ArchaiusUtil;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicLongProperty;
import com.netflix.config.DynamicStringProperty;

public class OpenLDAPConstants {

    public static final String NAME = "openldap";
    public static final String USER_SCOPE = NAME + "_user";
    public static final String GROUP_SCOPE = NAME + "_group";

    public static final String CONFIG = NAME + "config";
    public static final String LDAP_ACCESS_TOKEN = NAME + "AccessToken";
    public static final String LDAP_JWT = NAME + "Jwt";

    //Names for Settings in cattle.
    public static final String SETTING_BASE = "api.auth.ldap.openldap.";
    public static final String ACCESS_MODE_SETTING = SETTING_BASE + "access.mode";
    public static final String DOMAIN_SETTING = SETTING_BASE + "domain";
    public static final String LOGIN_DOMAIN_SETTING = SETTING_BASE + "login.domain";
    public static final String PORT_SETTING = SETTING_BASE + "port";
    public static final String USER_SEARCH_FIELD_SETTING = SETTING_BASE + "user.search.field";
    public static final String SERVICE_ACCOUNT_USERNAME_SETTING = SETTING_BASE + "service.account.user";
    public static final String GROUP_SEARCH_FIELD_SETTING = SETTING_BASE + "group.search.field";
    public static final String USER_OBJECT_CLASS_SETTING = SETTING_BASE + "user.object.class";
    public static final String USER_NAME_FIELD_SETTING = SETTING_BASE + "user.name.field";
    public static final String GROUP_OBJECT_CLASS_SETTING = SETTING_BASE + "group.object.class";
    public static final String USER_LOGIN_FIELD_SETTING = SETTING_BASE + "user.login.field";
    public static final String USER_DISABLED_BIT_MASK_SETTING = SETTING_BASE + "user.enabled.mask.bit";
    public static final String SERVER_SETTING = SETTING_BASE + "server";
    public static final String SERVICE_ACCOUNT_PASSWORD_SETTING = SETTING_BASE + "service.account.password";
    public static final String USER_ENABLED_ATTRIBUTE_SETTING = SETTING_BASE + "user.enabled.attribute";
    public static final String GROUP_NAME_FIELD_SETTING = SETTING_BASE + "group.name.field";
    public static final String USER_MEMBER_ATTRIBUTE_SETTING = SETTING_BASE + "user.member.attribute";
    public static final String GROUP_USER_MAPPING_ATTRIBUTE_SETTING = SETTING_BASE + "group.member.mapping.attribute";
    public static final String TLS_SETTING = SETTING_BASE + "tls";
    public static final String TIMEOUT_SETTING = SETTING_BASE + "connection.timeout";
    public static final String GROUP_DN_FIELD_SETTING = SETTING_BASE + "group.dn.field";
    public static final String GROUP_MEMBER_USER_ATTRIBUTE_SETTING = SETTING_BASE + "group.member.user.attribute";

    public static final Set<String> SCOPES = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList(
                    USER_SCOPE,
                    GROUP_SCOPE
            )));

    public static final DynamicStringProperty ACCESS_MODE = ArchaiusUtil.getString(ACCESS_MODE_SETTING);
    public static final DynamicStringProperty LDAP_DOMAIN = ArchaiusUtil.getString(DOMAIN_SETTING);
    public static final DynamicStringProperty LDAP_LOGIN_DOMAIN = ArchaiusUtil.getString(LOGIN_DOMAIN_SETTING);
    public static final DynamicIntProperty LDAP_PORT = ArchaiusUtil.getInt(PORT_SETTING);
    public static final DynamicStringProperty LDAP_SERVER = ArchaiusUtil.getString(SERVER_SETTING);
    public static final DynamicStringProperty SERVICE_ACCOUNT_PASSWORD = ArchaiusUtil.getString(SERVICE_ACCOUNT_PASSWORD_SETTING);
    public static final DynamicStringProperty SERVICE_ACCOUNT_USER = ArchaiusUtil.getString(SERVICE_ACCOUNT_USERNAME_SETTING);

    public static final String TOKEN_CREATOR = NAME + "TokenCreator";
    public static final DynamicBooleanProperty TLS_ENABLED = ArchaiusUtil.getBoolean(TLS_SETTING);
    public static final DynamicStringProperty USER_SEARCH_FIELD = ArchaiusUtil.getString(USER_SEARCH_FIELD_SETTING);
    public static final DynamicStringProperty USER_LOGIN_FIELD = ArchaiusUtil.getString(USER_LOGIN_FIELD_SETTING);
    public static final DynamicStringProperty GROUP_SEARCH_FIELD = ArchaiusUtil.getString(GROUP_SEARCH_FIELD_SETTING);
    public static final DynamicStringProperty GROUP_MEMBER_MAPPING_ATTRIBUTE = ArchaiusUtil.getString(GROUP_USER_MAPPING_ATTRIBUTE_SETTING);
    public static final DynamicStringProperty USER_OBJECT_CLASS = ArchaiusUtil.getString(USER_OBJECT_CLASS_SETTING);
    public static final DynamicIntProperty USER_DISABLED_BIT_MASK = ArchaiusUtil.getInt(USER_DISABLED_BIT_MASK_SETTING);
    public static final DynamicStringProperty USER_ENABLED_ATTRIBUTE = ArchaiusUtil.getString(USER_ENABLED_ATTRIBUTE_SETTING);
    public static final String MANAGER = NAME + "Manager";

    /* * All of these
           * Fields Should be configurable. Make them configurable in ldap config. and used in appropriate places.
           * Add the member attributes and memberOf attributes. Make Comma separated list of ous that are allowed as setting.
           * This setting will be iterated on every login request/ search for results. We only support direct membership currently.
        * */
    public static final DynamicStringProperty USER_NAME_FIELD = ArchaiusUtil.getString(USER_NAME_FIELD_SETTING);
    public static final DynamicStringProperty GROUP_NAME_FIELD = ArchaiusUtil.getString(GROUP_NAME_FIELD_SETTING);
    public static final String OBJECT_CLASS = "objectClass";
    public static final DynamicStringProperty GROUP_OBJECT_CLASS = ArchaiusUtil.getString(GROUP_OBJECT_CLASS_SETTING);

    public static final DynamicStringProperty USER_MEMBER_ATTRIBUTE = ArchaiusUtil.getString(USER_MEMBER_ATTRIBUTE_SETTING);
    public static final DynamicLongProperty CONNECTION_TIMEOUT = ArchaiusUtil.getLong(TIMEOUT_SETTING);
    public static final DynamicStringProperty GROUP_DN_FIELD = ArchaiusUtil.getString(GROUP_DN_FIELD_SETTING);
    public static final DynamicStringProperty GROUP_MEMBER_USER_ATTRIBUTE = ArchaiusUtil.getString(GROUP_MEMBER_USER_ATTRIBUTE_SETTING);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <jdbc:embedded-database type="H2" id="dataSource" />

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven />

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="org.springframework.flex.integration.domain" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

</beans>

redpajama_set_name: RedPajamaGithub


text:
<?php

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;

AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="language" content="ru" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>

    <?php $this->beginBody() ?>

        <?php $this->beginContent('@app/views/layouts/top_sidebar.php'); ?>

        <?php $this->endContent(); ?>

                                <?= Breadcrumbs::widget(['links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],]) ?>

                                <?= $content ?>

                            <?php if(!Yii::$app->user->isGuest)

                            {

                                $this->beginContent('@app/views/layouts/left_sidebar.php');
                                $this->endContent();
                            }

                                else {

                                }

                            ?>

© Copyright My Company <?= date('Y') ?>

<?php $this->endBody() ?>

<?php $this->endPage() ?>


text:
package com.pack.colorchat.impl;

import com.pack.colorchat.service.ChatService;
import com.pack.colorchat.model.Message;
import com.pack.colorchat.model.User;
import org.springframework.stereotype.Component;

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

@Component
public class ChatServiceJavaImpl implements ChatService {

    private List<Message> messages = Collections.synchronizedList(new ArrayList<>());

    public void addMessage(User user, String text) {
        messages.add(new Message(user, text));
    }

    public List<Message> getMessages() {
        return messages;
    }
}


text:
from test_support import verify
import Cookie
from test_support import verify, verbose
import doctest

# Currently this only tests SimpleCookie

cases = [
    ('chips=ahoy; vienna=finger', {'chips':'ahoy', 'vienna':'finger'}),
    ('keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;";',
     {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'}),

    # Check illegal cookies that have an '=' char in an unquoted value
    ('keebler=E=mc2;', {'keebler' : 'E=mc2'})
    ]

for data, dict in cases:
    C = Cookie.SimpleCookie() ; C.load(data)
    print repr(C)
    print str(C)
    for k, v in dict.items():
        print ' ', k, repr( C[k].value ), repr(v)
        verify(C[k].value == v)
        print C[k]

C = Cookie.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')

verify(C['Customer'].value == 'WILE_E_COYOTE')
verify(C['Customer']['version'] == '1')
verify(C['Customer']['path'] == '/acme')

print C.output(['path'])
print C.js_output()
print C.js_output(['path'])

# Try cookie with quoted meta-data
C = Cookie.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
verify(C['Customer'].value == 'WILE_E_COYOTE')
verify(C['Customer']['version'] == '1')
verify(C['Customer']['path'] == '/acme')

print "If anything blows up after this line, it's from Cookie's doctest."
doctest.testmod(Cookie)


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :sidebar
  #after_filter :store_location

  layout :layout_by_resource

  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = "Sie haben leider keine Berechtigung diese Seite zu sehen"

    if user_signed_in?
      redirect_to root_url
    else
      session['user_return_to'] = request.fullpath
      redirect_to new_user_session_path
    end
  end

  # def store_location
  #   if request.fullpath != "/login" && request.fullpath != "/logout" && !request.xhr?
  #     session['user_return_to'] = request.fullpath
  #   end
  # end

  # def after_sign_in_path_for(resource)
  #   if params[:modal]
  #     url = request.env['HTTP_REFERER']
  #     # TODO: Sanitize the url
  #     # URI(url).host == params[:domain]
  #     url || root_path
  #   else
  #     session['user_return_to'] || super
  #   end
  # end

  def layout_by_resource
    if devise_controller?
      "layout_devise"
    elsif params[:controller] == "pages" && params[:action] == "start" or params[:controller] == "quarters" && params[:action] == "show"
      "start"
    else
      "application"
    end
  end

  def all_quarters
    @all_quarters ||= Quarter.all
  end
  helper_method :all_quarters

  def ensure_valid_recaptcha
    if !current_user
      if !verify_recaptcha
        redirect_to :back, :flash => { :error => "Der SPAM-Schutz Test wurde leider nicht bestanden." }
      end
    end
  end
end


text:
package org.camunda.bpm.engine.impl.batch;

import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.db.DbEntity;
import org.camunda.bpm.engine.impl.db.entitymanager.OptimisticLockingListener;
import org.camunda.bpm.engine.impl.db.entitymanager.OptimisticLockingResult;
import org.camunda.bpm.engine.impl.db.entitymanager.operation.DbEntityOperation;
import org.camunda.bpm.engine.impl.db.entitymanager.operation.DbOperation;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.jobexecutor.JobDeclaration;
import org.camunda.bpm.engine.impl.persistence.entity.ByteArrayEntity;
import org.camunda.bpm.engine.impl.persistence.entity.ByteArrayManager;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.impl.persistence.entity.JobManager;
import org.camunda.bpm.engine.impl.persistence.entity.MessageEntity;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.impl.util.JsonUtil;
import com.google.gson.JsonElement;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Common methods for batch job handlers based on list of ids, providing serialization, configuration instantiation, etc.
 *
 * @author Askar Akhmerov
 */
public abstract class AbstractBatchJobHandler<T extends BatchConfiguration> implements BatchJobHandler<T>, OptimisticLockingListener {

  public abstract JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration();

  @Override
  public boolean createJobs(BatchEntity batch) {
    T configuration = readConfiguration(batch.getConfigurationBytes());
    String deploymentId = null;

    DeploymentMappings idMappings = configuration.getIdMappings();
    boolean deploymentAware = idMappings != null && !idMappings.isEmpty();

    List<String> ids = configuration.getIds();

    if (deploymentAware) {
      sanitizeMappings(idMappings, ids);
      DeploymentMapping mappingToProcess = idMappings.get(0);
      ids = mappingToProcess.getIds(ids);
      deploymentId = mappingToProcess.getDeploymentId();
    }

    int batchJobsPerSeed = batch.getBatchJobsPerSeed();
    int invocationsPerBatchJob = batch.getInvocationsPerBatchJob();

    int numberOfItemsToProcess = Math.min(invocationsPerBatchJob * batchJobsPerSeed, ids.size());

    // view of process instances to process
    List<String> processIds = ids.subList(0, numberOfItemsToProcess);
    createJobEntities(batch, configuration, deploymentId, processIds, invocationsPerBatchJob);
    if (deploymentAware) {
      if (ids.isEmpty()) {
        // all ids of the deployment are handled
        idMappings.remove(0);
      } else {
        idMappings.get(0).removeIds(numberOfItemsToProcess);
      }
    }

    // update batch configuration
    batch.setConfigurationBytes(writeConfiguration(configuration));

    return deploymentAware ? idMappings.isEmpty() : ids.isEmpty();
  }

  @Override
  public final void execute(final BatchJobConfiguration configuration,
                            final ExecutionEntity execution,
                            final CommandContext commandContext,
                            final String tenantId) {

    // load handler config
    String byteArrayId = configuration.getConfigurationByteArrayId();
    ByteArrayEntity byteArray = commandContext.getDbEntityManager().selectById(ByteArrayEntity.class, byteArrayId);
    byte[] configurationByteArray = byteArray.getBytes();
    T batchConfiguration = readConfiguration(configurationByteArray);

    // load batch
    String batchId = batchConfiguration.getBatchId();
    final BatchEntity batch = commandContext.getBatchManager().findBatchById(batchId);

    // set executionStartTime & fire historic update event
    if (batch != null && batch.getExecutionStartTime() == null) {
      // batches with multiple jobs could trigger an OptimisticLockingException, register listener to ignore that
      commandContext.getDbEntityManager().registerOptimisticLockingListener(this);

      final Date executionStartTime = ClockUtil.now();
      batch.setExecutionStartTime(executionStartTime);
      batch.fireHistoricUpdateEvent();
    }

    executeHandler(batchConfiguration, execution, commandContext, tenantId);

    commandContext.getByteArrayManager().delete(byteArray);
  }

  protected abstract void executeHandler(final T configuration,
                                         final ExecutionEntity execution,
                                         final CommandContext commandContext,
                                         final String tenantId);

  protected void sanitizeMappings(DeploymentMappings idMappings, List<String> ids) {
    // for mixed version SeedJob execution, there might be ids that have been processed
    // without updating the mappings, this is corrected here,
    // see https://jira.camunda.com/browse/CAM-11188
    int elementsToRemove = idMappings.getOverallIdCount() - ids.size();
    if (elementsToRemove > 0) {
      for (Iterator<DeploymentMapping> iterator = idMappings.iterator(); iterator.hasNext();) {
        DeploymentMapping deploymentMapping = iterator.next();
        if (deploymentMapping.getCount() <= elementsToRemove) {
          iterator.remove();
          elementsToRemove -= deploymentMapping.getCount();
          if (elementsToRemove == 0) {
            break;
          }
        } else {
          deploymentMapping.removeIds(elementsToRemove);
          break;
        }
      }
    }
  }

  protected void createJobEntities(BatchEntity batch, T configuration, String deploymentId,
      List<String> processIds, int invocationsPerBatchJob) {

    if (processIds == null || processIds.isEmpty()) {
      return;
    }

    CommandContext commandContext = Context.getCommandContext();
    ByteArrayManager byteArrayManager = commandContext.getByteArrayManager();
    JobManager jobManager = commandContext.getJobManager();

    int createdJobs = 0;
    while (!processIds.isEmpty()) {
      int lastIdIndex = Math.min(invocationsPerBatchJob, processIds.size());
      // view of process instances for this job
      List<String> idsForJob = processIds.subList(0, lastIdIndex);

      T jobConfiguration = createJobConfiguration(configuration, idsForJob);

      jobConfiguration.setBatchId(batch.getId());

      ByteArrayEntity configurationEntity = saveConfiguration(byteArrayManager, jobConfiguration);

      JobEntity job = createBatchJob(batch, configurationEntity);
      job.setDeploymentId(deploymentId);
      postProcessJob(configuration, job, jobConfiguration);
      jobManager.insertAndHintJobExecutor(job);

      idsForJob.clear();
      createdJobs++;
    }

    // update created jobs for batch
    batch.setJobsCreated(batch.getJobsCreated() + createdJobs);
  }

  protected abstract T createJobConfiguration(T configuration, List<String> processIdsForJob);

  protected void postProcessJob(T configuration, JobEntity job, T jobConfiguration) {
    // do nothing as default
  }

  protected JobEntity createBatchJob(BatchEntity batch, ByteArrayEntity configuration) {
    BatchJobContext creationContext = new BatchJobContext(batch, configuration);
    return getJobDeclaration().createJobInstance(creationContext);
  }

  @Override
  public void deleteJobs(BatchEntity batch) {
    List<JobEntity> jobs = Context.getCommandContext()
        .getJobManager()
        .findJobsByJobDefinitionId(batch.getBatchJobDefinitionId());

    for (JobEntity job : jobs) {
      job.delete();
    }
  }

  @Override
  public BatchJobConfiguration newConfiguration(String canonicalString) {
    return new BatchJobConfiguration(canonicalString);
  }

  @Override
  public void onDelete(BatchJobConfiguration configuration, JobEntity jobEntity) {
    String byteArrayId = configuration.getConfigurationByteArrayId();
    if (byteArrayId != null) {
      Context.getCommandContext().getByteArrayManager()
          .deleteByteArrayById(byteArrayId);
    }
  }

  protected ByteArrayEntity saveConfiguration(ByteArrayManager byteArrayManager, T jobConfiguration) {
    ByteArrayEntity configurationEntity = new ByteArrayEntity();
    configurationEntity.setBytes(writeConfiguration(jobConfiguration));
    byteArrayManager.insert(configurationEntity);
    return configurationEntity;
  }

  @Override
  public byte[] writeConfiguration(T configuration) {
    JsonElement jsonObject = getJsonConverterInstance().toJsonObject(configuration);

    return JsonUtil.asBytes(jsonObject);
  }

  @Override
  public T readConfiguration(byte[] serializedConfiguration) {
    return getJsonConverterInstance().toObject(JsonUtil.asObject(serializedConfiguration));
  }

  protected abstract AbstractBatchConfigurationObjectConverter<T> getJsonConverterInstance();

  @Override
  public Class<? extends DbEntity> getEntityType() {
    return BatchEntity.class;
  }

  @Override
  public OptimisticLockingResult failedOperation(final DbOperation operation) {
    if (operation instanceof DbEntityOperation) {
      return OptimisticLockingResult.IGNORE;
    }
    return OptimisticLockingResult.THROW;
  }

}


text:
package com.alibaba.nacos.config.server.controller;

import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.service.datasource.DataSourceService;
import com.alibaba.nacos.core.cluster.MemberLookup;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class HealthControllerTest {

    @InjectMocks
    HealthController healthController;

    @Mock
    DataSourceService dataSourceService;

    private MockMvc mockmvc;

    @Mock
    private ServerMemberManager memberManager;

    @Mock
    private ServletContext servletContext;

    @Mock
    private MemberLookup memberLookup;

    @Before
    public void setUp() {
        EnvUtil.setEnvironment(new StandardEnvironment());
        Map<String, Object> infos = new HashMap<>();
        infos.put("addressServerHealth", true);
        when(memberLookup.info()).thenReturn(infos);
        when(memberManager.getLookup()).thenReturn(memberLookup);
        when(servletContext.getContextPath()).thenReturn("/nacos");
        ReflectionTestUtils.setField(healthController, "memberManager", memberManager);
        ReflectionTestUtils.setField(healthController, "dataSourceService", dataSourceService);
        mockmvc = MockMvcBuilders.standaloneSetup(healthController).build();
    }

    @Test
    public void testGetHealth() throws Exception {

        when(dataSourceService.getHealth()).thenReturn("UP");
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH);
        String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString();
        Assert.assertEquals("UP", actualValue);

    }
}


text:
def longest_string(list_of_words)
  # Your code goes here!
  list_of_words.max do |word1, word2|
  	word1.length <=> word2.length
  end
end


text:
                                 Register as Admin of new Community

                                    <form id="register-form" method="post" role="form">

                                            <input type="text" name="first-name" ng-model="fnameAdmin" id="first-name" tabindex="1" class="form-control"
                                                   placeholder="First Name" ng-maxlength=40 value="" required>

                                            <input type="text" name="last-name" id="last-name" ng-model="lnameAdmin" tabindex="2" class="form-control"
                                                   placeholder="Last Name" value="" ng-maxlength=40 required>

                                            <input type="number" name="apt-num" id="apt-num" ng-model="aptnumAdmin" tabindex="3" class="form-control"
                                                   placeholder="Apartment Number" value="" required>

                                            <input type="text" name="username" id="username" ng-model="unameAdmin" tabindex="4" class="form-control"
                                                   placeholder="Username" value="" required>

                                            <input type="email" name="email" id="email" ng-model="emailAdmin" tabindex="5" class="form-control"
                                                   placeholder="Email Address" value="" required>

                                            <input type="password" name="password" ng-model="passAdmin" id="password" tabindex="6"
                                                   class="form-control"
                                                   placeholder="Password" required>

                                            <input type="password" name="confirm-password" ng-model="confirmPassAdmin" id="confirm-password" tabindex="7"
                                                   class="form-control" placeholder="Confirm Password" required>

                                            <input type="text" name="verification-token" ng-model="verificationTokenAdmin" id="verification-token" tabindex="8"
                                                   class="form-control" placeholder="Verification token" required>

                                            <input type="text" name="community-name" ng-model="communityName" id="community-name" tabindex="8"
                                                   class="form-control" placeholder="New community name" required>

                                            <input type="text" name="community-description" ng-model="communityDescription" id="community-description" tabindex="8"
                                                   class="form-control" placeholder="New community description" required>

                                                    <button ng-click="vm.registerAdmin()" name="register-submit" id="register-submit"
                                                            class="form-control btn btn-register">
                                                        Register New Community
                                                    </button>

                                    </form>


text:
{% extends "base.html" %}

{% block title %} Register {% endblock title %}

{% block navbar %}
    {{ block.super }}

register

{% endblock navbar %}

{% block content %}

            <form method="post" action="{% url 'profiles:register' %}" class="form-box">

Register

                    {% csrf_token %}

                        {{ form.email.label_tag }}

                        {{ form.email }}

                        {% if form.email.name in form.errors %}

{{ form.errors.email.0 }}

                        {% endif %}

                        {{ form.username.label_tag }}

                        {{ form.username }}

                        {% if form.username.name in form.errors %}

{{ form.errors.username.0 }}

                        {% endif %}

                        {{ form.password.label_tag }}

                        {{ form.password }}

                        {% if form.password.name in form.errors %}

{{ form.errors.password.0 }}

                        {% endif %}

                    <input type="submit" value="register" class="button green-button tablet-col-1-3 mobile-full" />
                    <input type="hidden" name="next" value="{{ next }}" />

            </form>

{% endblock content %}


text:
using namespace std;

class MyClass {
    protected:
        int value;

    public:
        MyClass(void);
        MyClass(int x);
        friend std::ostream& operator<< ( std::ostream& stream, const MyClass& m) {
            stream << m.value;
            return stream;
        }
};

MyClass::MyClass( void ) {
    value = 0;
}

MyClass::MyClass( int x ) {
    value = x;
}

int main (int argc, char **argv) {

    // The MyClass constructor is used to automatically construct
    // a MyClass object. This is possible because the constructor
    // has not been declared as "explicit". Hence implicit construction
    // is allowed.
    MyClass x = 2;
    cout << x;

}


text:
import { mount } from '@vue/test-utils'
import BInputGroupAppend from './input-group-append'

describe('input-group > input-group-append', () => {
  it('has expected default structure', async () => {
    const wrapper = mount(BInputGroupAppend)

    expect(wrapper.is('div')).toBe(true)
    expect(wrapper.classes()).toContain('input-group-append')
    expect(wrapper.classes().length).toBe(1)
    expect(wrapper.findAll('.input-group-append > *').length).toBe(0)
    expect(wrapper.text()).toEqual('')
  })

  it('renders custom root element when tag prop is set', async () => {
    const wrapper = mount(BInputGroupAppend, {
      propsData: {
        tag: 'span'
      }
    })

    expect(wrapper.is('span')).toBe(true)
    expect(wrapper.classes()).toContain('input-group-append')
    expect(wrapper.classes().length).toBe(1)
    expect(wrapper.findAll('.input-group-append > *').length).toBe(0)
    expect(wrapper.text()).toEqual('')
  })

  it('renders content of default slot', async () => {
    const wrapper = mount(BInputGroupAppend, {
      slots: {
        default: 'foobar'
      }
    })

    expect(wrapper.is('div')).toBe(true)
    expect(wrapper.classes()).toContain('input-group-append')
    expect(wrapper.classes().length).toBe(1)
    expect(wrapper.text()).toEqual('foobar')
  })

  it('renders child input-group-text when prop is-text set', async () => {
    const wrapper = mount(BInputGroupAppend, {
      propsData: {
        isText: true
      }
    })

    expect(wrapper.is('div')).toBe(true)
    expect(wrapper.classes()).toContain('input-group-append')
    expect(wrapper.classes().length).toBe(1)
    expect(wrapper.findAll('.input-group-text').length).toBe(1)
    expect(wrapper.findAll('.input-group-append > .input-group-text').length).toBe(1)
    expect(wrapper.text()).toEqual('')
  })

  it('renders default slot inside child input-group-text when prop is-text set', async () => {
    const wrapper = mount(BInputGroupAppend, {
      propsData: {
        isText: true
      },
      slots: {
        default: 'foobar'
      }
    })

    expect(wrapper.is('div')).toBe(true)
    expect(wrapper.classes()).toContain('input-group-append')
    expect(wrapper.classes().length).toBe(1)
    expect(wrapper.findAll('.input-group-text').length).toBe(1)
    expect(wrapper.text()).toEqual('foobar')
    expect(wrapper.find('.input-group-text').text()).toEqual('foobar')
  })
})


text:
/**
 * @fileoverview
 * @author Maxence Laurent <maxence.laurent> <gmail.com>
 */
/*global Variable, gameModel, self */

YUI.add("wegas-i18n-mcq-fr", function(Y) {
    Y.Wegas.I18n.register("wegas-i18n-mcq", "fr", {
        mcq: {
            result: "Résultat",
            results: "Résultats",
            noQuestionSelected: "Sélectionnez une question sur la gauche",
            empty: "Aucune question disponible actuellement",
            submit: "valider",
            answered : "répondue",
            unanswered : "",    // Customizable per scenario
            notDone: "",        // Customizable per scenario
            noReply: "Merci de sélectionner une réponse !",
            notEnoughReply: "Merci de sélectionner au moins {{min}} réponses !",
            maximumReached: "Vous ne pouvez pas sélectionner plus de {{max}} réponses",
            conflict: "Votre requête n'a pas été prise en compte car un de vos coéquipiers a tenté la même opération en même temps.<br />",
            possibleChoices: 'Choix à disposition : #'
        }
    });
});


text:
using namespace nspace;

InputHandler * IInputListener::currentHandler()const{
  if(_currentHandler)return _currentHandler;
  Set<InputHandler*> tmp = _handlers;
  tmp.sort([](const InputHandler * a, const InputHandler * b){
    return a->lastChange() > b->lastChange();
  });
  return tmp.first();
}
IInputListener::IInputListener():_currentHandler(0){
}

void IInputListener::setCurrentHandler(InputHandler * handler){
  _currentHandler = handler;
}


text:
die()
{
  echo "ERROR: $@" 1>&2
  exit 1
}

# NOTE: Run this script from the root of the project
scripts_dir=$(dirname $0) # => scripts
working_dir=$(basename `pwd`) # => backend-server-poc
if [[ $working_dir != 'backend-server-poc' ]]; then
  die "You must run this script from the root of the project"
fi

if [[ -x `which astyle` ]]; then
  echo "Astyle detected. Formating source..." 1>&2
else
  die "Astyle NOT detected. Please install Astyle." 1>&2
fi

astyle --recursive --options=.astylerc *.cpp *.h


text:
'use strict';

module.exports = {
	app: {
		title: 'DocumentManagement',
		description: 'Document Management Application with MongoDB, Express, AngularJS, and Node.js',
		keywords: 'Document, Management, MongoDB, Express, AngularJS, Node.js'
	},
	port: process.env.PORT || 8084,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
				'public/lib/ng-table/ng-table.min.css',
				'public/lib/angular-loading-bar/build/loading-bar.min.css',
				'public/lib/angularjs-toaster/toaster.css'
			],
			js: [
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/ng-table/ng-table.min.js',
				'public/lib/angular-loading-bar/build/loading-bar.min.js',
				'public/lib/jquery/dist/jquery.min.js',
				'public/lib/angularjs-toaster/toaster.js',
				'public/lib/bootstrap/js/tooltip.js',
				'public/lib/angular-ckeditor/angular-ckeditor.js'
			]
		},
		css: [
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/services/*.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};


text:
package ru.job4j.generic;

/**
 * @author Alexey Rastorguev (rastorguev00@gmail.com)
 * @version 0.1
 * @since 02.12.2017
 */
public class User extends Base {

}


text:
module ButterCMS
  class ButterResource
    attr_reader :meta, :data

    def initialize(json)
      @json = json
      @data = HashToObject.convert(json["data"])
      @meta = HashToObject.convert(json["meta"]) if json["meta"]

      define_attribute_methods(@data)
    end

    def marshal_dump
      { json: @json, data: @data, meta: @meta }
    end

    def marshal_load(dump)
      @json = dump[:json]
      @data = dump[:data]
      @meta = dump[:meta]

      define_attribute_methods(@data)
    end

    def inspect
      id_string = (self.respond_to?(:id) && !self.id.nil?) ? " id=#{self.id}" : ""
      "#<#{self.class}:0x#{self.object_id.to_s(16)}#{id_string}> JSON: " + JSON.pretty_generate(@json)
    end

    def self.endpoint(id = nil)
      # Append trailing slash when id is added to path because
      # API expects all endpoints to include trailing slashes
      resource_path + (id ? "#{id}/" : '')
    end

    def self.patch_endpoint(id)
      # Append trailing slash when id is added to path because
      # API expects all endpoints to include trailing slashes
      resource_path + "*/#{id}/"
    end

    def self.resource_path
      raise "resource_path must be set"
    end

    def self.all(options = {})
      response = ButterCMS.request(self.endpoint, options)

      self.create_collection(response)
    end

    def self.find(id, options = {})
      response = ButterCMS.request(self.endpoint(id), options)

      self.create_object(response)
    end

    def self.create(options = {})
      options[:method] = 'Post'
      response = ButterCMS.write_request(self.endpoint, options)

      self.create_object(response)
    end

    def self.update(id, options = {})
      options[:method] = 'Patch'
      _endpoint = if resource_path.include?("/pages/")
        self.patch_endpoint(id)
      else
        self.endpoint(id)
      end
      response = ButterCMS.write_request(_endpoint, options)

      self.create_object(response)
    end

    private

    def self.create_collection(response)
      ButterCollection.new(self, response)
    end

    def self.create_object(response)
      self.new(response)
    end

    def define_attribute_methods(methods)
      return unless methods.respond_to?(:each_pair)

      methods.each_pair do |key, value|
        instance_variable_set("@#{key}", value)
        self.class.send(:attr_reader, key)
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textPopup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dip"
            android:layout_marginRight="16dip"
            android:layout_marginTop="4dip"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

</ScrollView>


text:
{% extends "site_base.html" %}

{% load i18n %}
{% load bootstrap %}
{% load boxes_tags %}
{% load cache %}

{% block head_title %}{% trans "Conference Schedule" %}{% endblock %}

{% block page_title %}
    {% trans "Conference Schedule" %}
{% endblock %}

{% block page_content %}

        {% with lang=LANGUAGE_CODE|default:"en"|slice:":2" %}
        {% box "schedule_top-"|add:lang %}
        {% endwith %}
        {% for section in sections %}
            {% cache 600 "schedule-table" section.schedule.section %}
                {% for timetable in section.days %}

{{ timetable.day.date }}

                    {% include "schedule/_grid.html" %}
                {% endfor %}
            {% endcache %}
        {% endfor %}

        {% with lang=LANGUAGE_CODE|default:"en"|slice:":2" %}
        {% box "schedule_bottom-"|add:lang %}
        {% endwith %}

{% endblock %}


text:
Instructions:

If you haven't installed these yet, run:
pip install tornado
pip install easyjson
pip install flask

The summarizer is linked to the Treehacks Slack by default.
To change this, go to slack_listener.py and add your API Access Token
to the connect_to_slack function

To initialize the server for summarization, run
$ python run_server.py

To initialize the server for splitting related messages, run
$ python server/server.py

Server will be listening at port 8889, showing the JSON data of all the groups


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="Date-Revision-yyyymmdd" content="20181214" />
    <meta http-equiv="Content-Language" content="en" />
    <title>Metron – Build Metron Images</title>
    <link rel="stylesheet" href="../../../css/apache-maven-fluido-1.7.min.css" />
    <link rel="stylesheet" href="../../../css/site.css" />
    <link rel="stylesheet" href="../../../css/print.css" media="print" />

Apache/

Metron/

Documentation/

Build Metron Images

| Last Published: 2018-12-14

Version: 0.7.0

User Documentation

Metron

CONTRIBUTING

Upgrading

Analytics

Docker

Performance

Deployment

Kerberos-ambari-setup

Kerberos-manual-setup

Amazon-ec2

Ansible

Development

Other-examples

Ambari

Ansible-docker

Deb-docker

Rpm-docker

Packer-build

Alerts

Config

Rest

Platform

Sensors

Stellar-3rd-party-example

Stellar-common

Stellar-zeppelin

Use-cases

Build Metron Images

Based on the fantastic Bento project developed by Chef.

Images Provided

base-centos-6.7: Centos 6.7 + HDP. Used in the full-dev-platform Vagrant image

Prerequisites

Packer 0.12.2

Virtualbox 5.0.16+ (Tested with 5.0.20)

Build Both Images

Navigate to <your-project-directory>/metron-deployment/packer-build Execute bin/bento build

Packer will build both images and export .box files to the ./builds directory.

Build Single Images

Navigate to your-project-directory/metron-deployment/packer-build

Base Centos (full-dev)

bin/bento build base-centos-6.7.json

Using Your New Box File

Modify the relevant Vagrantfile (full-dev-platform) replacing the lines:

<pre><code>config.vm.box = "<i>box_name</i>"
config.ssh.insert_key = true</code></pre>

with

<pre></code>config.vm.box = "<i>test_box_name</i>"
config.vm.box = "<i>PathToBoxfile/Boxfilename</i>"
config.ssh.insert_key = true</code></pre>

Launch the image as usual.

Node: Vagrant will cache boxes, you can force Vagrant to reload your box by running <tt>vagrant box remove test_box_name</tt> before launching your new image.

© 2015-2016 The Apache Software Foundation. Apache Metron, Metron, Apache, the Apache feather logo,
            and the Apache Metron project logo are trademarks of The Apache Software Foundation.


text:
package com.epam.ta.reportportal.entity.widget.content.healthcheck;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;

/**
 * @author Ivan Budayeu
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ComponentHealthCheckContent implements Serializable {

	@JsonProperty(value = "attributeValue")
	private String attributeValue;

	@JsonProperty(value = "total")
	private Long total;

	@JsonProperty(value = "passingRate")
	private Double passingRate;

	public ComponentHealthCheckContent() {
	}

	public ComponentHealthCheckContent(String attributeValue, Long total, Double passingRate) {
		this.attributeValue = attributeValue;
		this.total = total;
		this.passingRate = passingRate;
	}

	public String getAttributeValue() {
		return attributeValue;
	}

	public void setAttributeValue(String attributeValue) {
		this.attributeValue = attributeValue;
	}

	public Long getTotal() {
		return total;
	}

	public void setTotal(Long total) {
		this.total = total;
	}

	public Double getPassingRate() {
		return passingRate;
	}

	public void setPassingRate(Double passingRate) {
		this.passingRate = passingRate;
	}
}


text:
package io.reflectoring.coderadar.graph.contributor.adapter;

import io.reflectoring.coderadar.contributor.port.driven.RemoveContributorPort;
import io.reflectoring.coderadar.domain.Contributor;
import io.reflectoring.coderadar.graph.contributor.repository.ContributorRepository;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class RemoveContributorAdapter implements RemoveContributorPort {

  private final ContributorRepository contributorRepository;

  @Override
  public void removeContributorFromProject(Contributor contributor, long projectId) {
    contributorRepository.detachContributorFromProject(contributor.getId(), projectId);
  }

  @Override
  public void removeContributorsFromProject(List<Contributor> contributors, long projectId) {
    List<Long> ids = new ArrayList<>(contributors.size());
    contributors.forEach(contributor -> ids.add(contributor.getId()));
    contributorRepository.detachContributorsFromProject(ids, projectId);
  }
}


text:
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable() export class AlertService {
     private subject = new Subject<any>();
     constructor(){}
     confirmThis(message: string,siFn:()=>void,noFn:()=>void){
       this.setConfirmation(message,siFn,noFn);
     }
     thankYouMsg(message: string,okFn:()=>void){
        this.thankYou(message,okFn);
      }
      thankYou(message: string,okFn:()=>void)
      {
        debugger;
        let that = this;
        this.subject.next({ type: "confirm",
        text: message,
        okFn:
        function(){
            that.subject.next(); //this will close the modal
            okFn();
        }
    })

      }
     setConfirmation(message: string,siFn:()=>void,noFn:()=>void) {
         debugger;
       let that = this;
       this.subject.next({ type: "confirm",
                   text: message,
                   siFn:
                   function(){
                       that.subject.next(); //this will close the modal
                       siFn();
                   },
                   noFn:function(){
                       that.subject.next();
                       noFn();
                   }
                });

            }

     getMessage(): Observable<any> {
        return this.subject.asObservable();
      }
     }


text:
package com.gemstone.gemfire.management.internal.cli;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheClosedException;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.execute.Execution;
import com.gemstone.gemfire.cache.execute.Function;
import com.gemstone.gemfire.cache.execute.FunctionService;
import com.gemstone.gemfire.cache.execute.ResultCollector;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.internal.ClassPathLoader;
import com.gemstone.gemfire.internal.cache.execute.AbstractExecution;
import com.gemstone.gemfire.internal.lang.StringUtils;
import com.gemstone.gemfire.internal.util.IOUtils;
import com.gemstone.gemfire.management.DistributedSystemMXBean;
import com.gemstone.gemfire.management.ManagementService;
import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
import com.gemstone.gemfire.management.internal.cli.result.CommandResultException;
import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;

/**
 * This class contains utility methods used by classes used to build the Command
 * Line Interface (CLI).
 *
 * @author Abhishek Chaudhari
 *
 * @since 7.0
 */
public class CliUtil {
  public static final String GFSHVM_IDENTIFIER = "gfsh";
  public static boolean isGfshVM = Boolean.getBoolean(GFSHVM_IDENTIFIER);

  public static final FileFilter JAR_FILE_FILTER = new CustomFileFilter(".jar");

  public static boolean isGfshVM() {
    return isGfshVM;
  }

  public static String cliDependenciesExist(boolean includeGfshDependencies) {
    String jarProductName = null;

    // Parser & CliCommand from Spring Shell
    jarProductName = checkLibraryByLoadingClass("org.springframework.shell.core.Parser", "Spring Shell");
    jarProductName = checkLibraryByLoadingClass("org.springframework.shell.core.annotation.CliCommand", "Spring Shell");
    if (jarProductName != null) {
      return jarProductName;
    }

    // SpringVersion from Spring Core
    jarProductName = checkLibraryByLoadingClass("org.springframework.core.SpringVersion", "Spring Core");
    if (jarProductName != null) {
      return jarProductName;
    }

    if (includeGfshDependencies) {
      // ConsoleReader from jline
      jarProductName = checkLibraryByLoadingClass("jline.ConsoleReader", "JLine");
      if (jarProductName != null) {
        return jarProductName;
      }
    }

    return jarProductName;
  }

  private static String checkLibraryByLoadingClass(String className, String jarProductName) {
    try {
      ClassPathLoader.getLatest().forName(className);
    } catch (ClassNotFoundException e) {
      return jarProductName;
    }

    return null;
  }

  public static Cache getCacheIfExists() {
    Cache cache;
    try {
      cache = CacheFactory.getAnyInstance();
    } catch (CacheClosedException e) {
      //ignore & return null
      cache = null;
    }

    return cache;
  }

  public static byte[][] filesToBytes(String[] fileNames) throws FileNotFoundException, IOException {
    List<byte[]> filesDataList = new ArrayList<byte[]>();

    for (int i = 0; i < fileNames.length; i++) {
      File file = new File(fileNames[i]);

      if (!file.exists()) {
        throw new FileNotFoundException("Could not find "+file.getCanonicalPath());
      }

      if (file.isDirectory()) { //TODO - Abhishek: (1) No recursive search yet. (2) Do we need to check/limit size of the files too?
        File[] childrenFiles = file.listFiles(JAR_FILE_FILTER);
        for (int j = 0; j < childrenFiles.length; j++) {
          //1. add name of the file as bytes at even index
          filesDataList.add(childrenFiles[j].getName().getBytes());
          //2. add file contents as bytes at odd index
          filesDataList.add(toByteArray(new FileInputStream(childrenFiles[j])));
        }
      } else {
        filesDataList.add(file.getName().getBytes());
        filesDataList.add(toByteArray(new FileInputStream(file)));
      }
    }

    byte[][] filesData = new byte[filesDataList.size()][];

    filesData = filesDataList.toArray(filesData);

    return filesData;
  }

  public static byte[] toByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    int n = 0;
    byte[] buffer = new byte[4096];
    while (-1 != (n = input.read(buffer))) {
      output.write(buffer, 0, n);
    }

    return output.toByteArray();
  }

  public static String[] bytesToNames(byte[][] fileData) {
    String[] names = new String[fileData.length / 2];
    for (int i = 0; i < fileData.length; i += 2) {
      names[i / 2] = new String(fileData[i]);
    }

    return names;
  }

  public static byte[][] bytesToData(byte[][] fileData) {
    byte[][] data = new byte[fileData.length / 2][];
    for (int i = 1; i < fileData.length; i += 2) {
      data[i / 2] = fileData[i];
    }

    return data;
  }

  public static void bytesToFiles(byte[][] fileData, String parentDirPath, boolean mkRequireddirs)
      throws FileNotFoundException, IOException, UnsupportedOperationException {
    FileOutputStream fos = null;

    File parentDir = new File(parentDirPath);
    if (mkRequireddirs && !parentDir.exists()) {
      if (!parentDir.mkdirs()) {
        throw new UnsupportedOperationException("Couldn't create required directory structure for "+parentDirPath);
      }
    }
    for (int i = 0; i < fileData.length; i++) {
      if (i%2 == 0) {
        // Expect file name as bytes at even index
        String fileName = new String(fileData[i]);
        fos = new FileOutputStream(new File(parentDir, fileName));
      } else {
        // Expect file contents as bytes at odd index
        fos.write(fileData[i]);
        fos.close();
      }
    }
  }

  public static boolean isValidFileName (String filePath, String extension) {
    boolean isValid = true;

    return isValid;
  }
  public static Set<String> getAllRegionNames() {
    Cache cache = CacheFactory.getAnyInstance();
    Set<String> regionNames = new HashSet<String>();
    Set<Region<?,?>> rootRegions = cache.rootRegions();

    Iterator<Region<?,?>> rootRegionIters = rootRegions.iterator();

    while (rootRegionIters.hasNext()) {
      Region<?,?> rootRegion = rootRegionIters.next();
      regionNames.add(rootRegion.getFullPath().substring(1));

      Set<Region<?, ?>> subRegions = rootRegion.subregions(true);
      Iterator<Region<?,?>> subRegionIters = subRegions.iterator();

      while (subRegionIters.hasNext()) {
        Region<?,?> subRegion = subRegionIters.next();
        regionNames.add(subRegion.getFullPath().substring(1));
      }
    }
    return regionNames;
  }

  public static String convertStringSetToString(Set<String> stringSet, char delimiter) {
    StringBuilder sb = new StringBuilder();
    if (stringSet != null) {
      Iterator<String> iters = stringSet.iterator();

      while (iters.hasNext()) {
        String stringValue = iters.next();
        sb.append(stringValue);
        sb.append(delimiter);
      }
    }
    return sb.toString();
  }

  public static String convertStringListToString(List<String> stringList, char delimiter) {
    StringBuilder sb = new StringBuilder();
    if (stringList != null) {
      Iterator<String> iters = stringList.iterator();

      while (iters.hasNext()) {
        String stringValue = iters.next();
        sb.append(stringValue);
        sb.append(delimiter);
      }
    }
    return sb.toString();
  }

  public static Set<DistributedMember> findAllMatchingMembers(final String groups, final String members) throws CommandResultException {
    Set<DistributedMember> matchingMembers = new HashSet<DistributedMember>();
    Cache cache = CacheFactory.getAnyInstance();

    if ((members != null && !members.isEmpty()) && (groups != null && !groups.isEmpty())) {
      throw new CommandResultException(ResultBuilder.createUserErrorResult(CliStrings.PROVIDE_EITHER_MEMBER_OR_GROUP_MESSAGE));
    }

    if (members != null && !members.isEmpty()) {
      StringTokenizer stringTokenizer = new StringTokenizer(members, ",");
      while (stringTokenizer.hasMoreTokens()) {
        String memberNameOrId = stringTokenizer.nextToken().trim();
        DistributedMember member = getDistributedMemberByNameOrId(memberNameOrId);
        if (member != null) {
          matchingMembers.add(member);
        } else {
          throw new CommandResultException(ResultBuilder.createUserErrorResult(CliStrings.format(
              CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId)));
        }
      }
    } else if (groups != null && !groups.isEmpty()) {
      Set<DistributedMember> allNormalMembers = getAllNormalMembers(cache);
      StringTokenizer stringTokenizer = new StringTokenizer(groups, ",");
      while (stringTokenizer.hasMoreTokens()) {
        String group = stringTokenizer.nextToken().trim();

        Set<DistributedMember> groupMembers = new HashSet<DistributedMember>();
        for (DistributedMember member : allNormalMembers) {
          if (member.getGroups().contains(group)) {
            groupMembers.add(member);
          }
        }

        if (!groupMembers.isEmpty()) {
          matchingMembers.addAll(groupMembers);

        } else {
          throw new CommandResultException(ResultBuilder.createUserErrorResult(CliStrings.format(
              CliStrings.NO_MEMBERS_IN_GROUP_ERROR_MESSAGE, group)));
        }
      }
    } else {
      matchingMembers.addAll(getAllNormalMembers(cache));
      if (matchingMembers.isEmpty()) {
        throw new CommandResultException(ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE));
      }
    }

    return matchingMembers;
  }

  public static DistributedMember getDistributedMemberByNameOrId (String memberNameOrId) {
    DistributedMember memberFound = null;

    if (memberNameOrId != null) {
      Cache cache = CacheFactory.getAnyInstance();
      Set<DistributedMember>memberSet = CliUtil.getAllMembers(cache);
      for (DistributedMember member: memberSet) {
        if (memberNameOrId.equalsIgnoreCase(member.getId()) || memberNameOrId.equals(member.getName())) {
          memberFound = member;
          break;
        }
      }
    }
    return memberFound;
  }

  public static String stackTraceAsString(Throwable e) {
    String stackAsString = "";
    if (e != null) {
      StringWriter writer = new StringWriter();
      PrintWriter pw = new PrintWriter(writer);
      e.printStackTrace(pw);
      stackAsString = writer.toString();
    }
    return stackAsString;
  }

  static class CustomFileFilter implements FileFilter {
    private String extensionWithDot;

    public CustomFileFilter(String extensionWithDot) {
      this.extensionWithDot = extensionWithDot;
    }

    @Override
    public boolean accept(File pathname) {
      String name = pathname.getName();

      return name.endsWith(extensionWithDot);
    }
  }

  public static DeflaterInflaterData compressBytes(byte[] input) {
    Deflater compresser = new Deflater();
    compresser.setInput(input);
    compresser.finish();
    byte[] buffer = new byte[100];
    byte[] result = new byte[0];
    int compressedDataLength = 0;
    int totalCompressedDataLength = 0;
    do {
      byte[] newResult = new byte[result.length + buffer.length];
      System.arraycopy(result, 0, newResult, 0, result.length);

      compressedDataLength = compresser.deflate(buffer);
      totalCompressedDataLength += compressedDataLength;
//      System.out.println(compressedDataLength);
//      System.out.println("uc: b  "+buffer.length);
//      System.out.println("uc: r  "+result.length);
//      System.out.println("uc: nr "+newResult.length);
//      System.out.println();
      System.arraycopy(buffer, 0, newResult, result.length, buffer.length);
      result = newResult;
    } while (compressedDataLength != 0);
    return new DeflaterInflaterData(totalCompressedDataLength, result);
  }

  public static DeflaterInflaterData uncompressBytes(byte[] output, int compressedDataLength) throws DataFormatException {
    Inflater decompresser = new Inflater();
    decompresser.setInput(output, 0, compressedDataLength);
    byte[] buffer = new byte[512];
    byte[] result = new byte[0];
    int bytesRead;
    while (!decompresser.needsInput()) {
      bytesRead = decompresser.inflate(buffer);
      byte[] newResult = new byte[result.length + bytesRead];
      System.arraycopy(result, 0, newResult, 0, result.length);
      System.arraycopy(buffer, 0, newResult, result.length, bytesRead);
      result = newResult;
    }
//    System.out.println(new String(result));
    decompresser.end();

    return new DeflaterInflaterData(result.length, result);
  }

  public static class DeflaterInflaterData implements Serializable {
    private static final long serialVersionUID = 1104813333595216795L;

    private final int dataLength;
    private final byte[] data;
    /**
     * @param dataLength
     * @param data
     */
    public DeflaterInflaterData(int dataLength, byte[] data) {
      this.dataLength = dataLength;
      this.data = data;
    }

    public int getDataLength() {
      return dataLength;
    }

    public byte[] getData() {
      return data;
    }

    @Override
    public String toString() {
      return String.valueOf(dataLength);
    }
  }

  public static void main(String[] args) {
    try {
      byte[][] filesToBytes = filesToBytes(new String[] {"/export/abhishek1/work/aspenmm/GFTryouts/test.json"});

      System.out.println(filesToBytes[1].length);

      DeflaterInflaterData compressBytes = compressBytes(filesToBytes[1]);
      System.out.println(compressBytes);

      DeflaterInflaterData uncompressBytes = uncompressBytes(compressBytes.data, compressBytes.dataLength);
      System.out.println(uncompressBytes);

      System.out.println(new String(uncompressBytes.getData()));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (DataFormatException e) {
      e.printStackTrace();
    }
  }

  public static void main1(String[] args) {
    try {
      byte[][] fileToBytes = filesToBytes(new String[] {"../dumped/source/lib"});

      bytesToFiles(fileToBytes, "../dumped/dest/lib/", true);

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static boolean contains(Object[] array, Object object) {
    boolean contains = false;

    if (array != null && object != null) {
      contains = Arrays.asList(array).contains(object);
    }

    return contains;
  }

  /**
   * Returns a set of all the members of the distributed system excluding locators.
   */
  @SuppressWarnings("unchecked")
  public static Set<DistributedMember> getAllNormalMembers(Cache cache) {
    return new HashSet<DistributedMember>(((InternalDistributedSystem)cache.getDistributedSystem()).getDistributionManager().getNormalDistributionManagerIds());
  }

  /**
   * Returns a set of all the members of the distributed system including locators.
   */
  @SuppressWarnings("unchecked")
  public static Set<DistributedMember> getAllMembers(Cache cache) {
    return new HashSet<DistributedMember>(((InternalDistributedSystem)cache.getDistributedSystem()).getDistributionManager().getDistributionManagerIds());
  }

  @SuppressWarnings("unchecked")
  public static Set<DistributedMember> getAllMembers(InternalDistributedSystem internalDS) {
    return new HashSet<DistributedMember>(internalDS.getDistributionManager().getDistributionManagerIds());
  }

  /**
   * Returns a set of all the members of the distributed system for the given groups.
   */
  public static Set<DistributedMember> getDistributedMembersByGroup(Cache cache,  String[] groups) {
    Set<DistributedMember> groupMembers = new HashSet<DistributedMember>();
    for(String group : groups){
      groupMembers.addAll(((InternalDistributedSystem)cache.getDistributedSystem()).getDistributionManager().getGroupMembers(group));
    }
    return groupMembers;
  }

  /***
   * Executes a function with arguments on a set of members , ignores the departed members.
   * @param function Function to be executed.
   * @param args Arguments passed to the function, pass null if you wish to pass no arguments to the function.
   * @param targetMembers Set of members on which the function is to be executed.
   *
   * @return ResultCollector
   */
  public static ResultCollector<?, ?> executeFunction(final Function function, Object args , final Set<DistributedMember> targetMembers) {
    Execution execution = null;

    if (args != null) {
      execution = FunctionService.onMembers(targetMembers).withArgs(args);
    } else {
      execution = FunctionService.onMembers(targetMembers);
    }

    ((AbstractExecution) execution).setIgnoreDepartedMembers(true);
    return execution.execute(function);
  }

  /***
   * Executes a function with arguments on a member , ignores the departed member.
   * @param function Function to be executed
   * @param args Arguments passed to the function, pass null if you wish to pass no arguments to the function.
   * @param targetMember Member on which the function is to be executed.
   * @return ResultCollector
   */
  public static ResultCollector<?, ?> executeFunction(final Function function, Object args , final DistributedMember targetMember) {
    Execution execution = null;

    if (args != null) {
      execution = FunctionService.onMember(targetMember).withArgs(args);
    } else {
      execution = FunctionService.onMember(targetMember);
    }

    ((AbstractExecution) execution).setIgnoreDepartedMembers(true);
    return execution.execute(function);
  }

  /**
   * Returns a Set of DistributedMember for members that have the specified region.
   * returnAll indicates whether to return all members or only the first member we find.
   *
   * @param region region path for which members that have this region are required
   * @param cache Cache instance to use to find members
   * @param returnAll whether to return all members or only the first member we find. Returns all when true
   * @return a Set of DistributedMember for members that have the specified region.
   */
  public static Set<DistributedMember> getRegionAssociatedMembers(final String region, final Cache cache, boolean returnAll) {
    if (region == null || region.isEmpty()) {
      return null;
    }

    ManagementService managementService = ManagementService.getExistingManagementService(cache);
    DistributedSystemMXBean distributedSystemMXBean = managementService.getDistributedSystemMXBean();
    Set<DistributedMember> matchedMembers = new HashSet<DistributedMember>();

    Set<DistributedMember> allClusterMembers = new HashSet<DistributedMember>();
    allClusterMembers.addAll(cache.getMembers());
    allClusterMembers.add(cache.getDistributedSystem().getDistributedMember());

    for (DistributedMember member : allClusterMembers) {
      try {
        if (distributedSystemMXBean.fetchRegionObjectName(CliUtil.getMemberNameOrId(member), region) != null) {
          matchedMembers.add(member);
        }
      } catch (Exception e) {
        //ignore for now
      }
    }
    return matchedMembers;
  }

  public static String getMemberNameOrId(DistributedMember distributedMember) {
    String nameOrId = null;
    if (distributedMember != null) {
      nameOrId = distributedMember.getName();
      nameOrId = nameOrId != null && !nameOrId.isEmpty() ? nameOrId : distributedMember.getId();
    }
    return nameOrId ;
  }

  public static String collectionToString(Collection<?> col, int newlineAfter) {
    if (col != null) {
      StringBuilder builder = new StringBuilder();
      int lastNewlineAt = 0;

      for (Iterator<?> it = col.iterator(); it.hasNext();) {
        Object object = (Object) it.next();
        builder.append(String.valueOf(object));
        if (it.hasNext()) {
          builder.append(", ");
        }
        if (newlineAfter > 0 && (builder.length() - lastNewlineAt) / newlineAfter >= 1) {
          builder.append(GfshParser.LINE_SEPARATOR);
        }
      }
      return builder.toString();
    } else {
      return "" + null;
    }
  }

  public static <T>String arrayToString(T[] array) {
    if (array != null) {
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < array.length; i++) {
        Object object = (Object) array[i];
        builder.append(String.valueOf(object));
        if (i < array.length - 1) {
          builder.append(", ");
        }
      }
      return builder.toString();
    } else {
      return "" + null;
    }
  }

  public static String decodeWithDefaultCharSet(String urlToDecode) {
    try {
      return URLDecoder.decode(urlToDecode, Charset.defaultCharset().name());
    } catch (UnsupportedEncodingException e) {
      return urlToDecode;
    }
  }

  /**
   * Resolves file system path relative to Gfsh. If the pathname is not specified, then pathname is returned.
   *

   *
   * @param pathname
   *          a String value specifying the file system pathname to resolve.
   * @return a String specifying a path relative to Gfsh.
   */
  // Moved form LauncherLifeCycleCommands @author jblum
  public static String resolvePathname(final String pathname) {
    return (StringUtils.isBlank(pathname) ? pathname : IOUtils.tryGetCanonicalPathElseGetAbsolutePath(new File(pathname)));
  }

}


text:
<!doctype html>
<meta charset=utf-8>
<title>CSS Text test: breaking opportunities at leading spaces with white-space:pre-wrap</title>
<link rel="author" title="Javier Fernandez" href="mailto:jfernandez@igalia.com" />
<link rel="help" href="https://drafts.csswg.org/css-text-3/#white-space-phase-2">
<link rel="help" href="https://drafts.csswg.org/css-text-3/#white-space-property">
<link rel="help" href="https://drafts.csswg.org/css-text-3/#valdef-white-space-pre-wrap">
<link rel="match" href="reference/white-space-break-spaces-005-ref.html">
<meta name="assert" content="Preserved white space at the beginning of the line are breaking opportunities when white-space is pre-wrap.">

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

Test passes if there is a filled green square and no red.

XX
XX

 XX


text:
//-----------------------------------------------------------------------
// <copyright file="AzureNameEncoderFixture.cs" company="Rare Crowds Inc.">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Xml;
using System.Xml.Linq;
using ConcreteDataStore;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ConcreteDataStoreUnitTests
{
    ///
    /// Test fixture for AzureNameEncoder
    ///
    [TestClass]
    public class AzureNameEncoderFixture
    {
        ///
        /// Null returns null
        ///
        [TestMethod]
        public void EncodeAzureNameNull()
        {
            Assert.IsNull(AzureNameEncoder.EncodeAzureName(null));
        }

        ///
        /// Empty returns empty
        ///
        [TestMethod]
        public void EncodeAzureNameEmpty()
        {
            this.AssertEncoding(string.Empty, AzureNameEncoder.EncodeAzureName(string.Empty));
        }

        /// AlphaNumeric names with no special characters should not change.
        [TestMethod]
        public void EncodeAzureNameNoEncodedChars()
        {
            // Contains uppercase letter, lowercase letter, decimal, and other letter.
            // These are the unicode character categories that will not be encoded
            var unencodedName = "aAzZ09\u4e00";
            var encodedName = AzureNameEncoder.EncodeAzureName(unencodedName);
            this.AssertEncoding(unencodedName, encodedName);
        }

        ///
        /// Underscore is allowed by Azure but we use it as a delimiter so make sure
        /// it gets encoded on external names.
        ///
        [TestMethod]
        public void EncodeAzureNameWithUnderscore()
        {
            var unencodedName = "a_b";
            var expectedEncodedName = "a{0}005Fb".FormatInvariant(AzureNameEncoder.AzureEscapeCharacter);
            var encodedName = AzureNameEncoder.EncodeAzureName(unencodedName);
            this.AssertEncoding(expectedEncodedName, encodedName);
        }

        /// Encoding escape char gets double escaped.
        [TestMethod]
        public void EncodeAzureNameWithEscapeCharacter()
        {
            var unencodedName = "a{0}b".FormatInvariant(AzureNameEncoder.AzureEscapeCharacter);
            var expectedEncodedName = "a{0}{1:X4}b"
                .FormatInvariant(AzureNameEncoder.AzureEscapeCharacter, Convert.ToInt32(AzureNameEncoder.AzureEscapeCharacter));
            var encodedName = AzureNameEncoder.EncodeAzureName(unencodedName);
            this.AssertEncoding(expectedEncodedName, encodedName);
        }

        /// Non-letter/non-decimal characters are encoded.
        [TestMethod]
        public void EncodeAzureNameNonLetter()
        {
            var unencodedName = "a\u0304 \u9fcf";
            var expectedEncodedName = "a{0}0304{0}0020{0}9FCF".FormatInvariant(AzureNameEncoder.AzureEscapeCharacter);
            var encodedName = AzureNameEncoder.EncodeAzureName(unencodedName);
            this.AssertEncoding(expectedEncodedName, encodedName);
        }

        ///
        /// Surrogate sequences are encoded
        /// (.Net strings with multiple 16-bit char values per unicode text element).
        ///
        [TestMethod]
        public void EncodeAzureNameSurrogateSequence()
        {
            var surrogateSequence = char.ConvertFromUtf32(0x10380);
            var unencodedName = "a" + surrogateSequence;
            var expectedEncodedName = "a{0}D800{0}DF80".FormatInvariant(AzureNameEncoder.AzureEscapeCharacter);
            var encodedName = AzureNameEncoder.EncodeAzureName(unencodedName);
            this.AssertEncoding(expectedEncodedName, encodedName);
        }

        /// Null returns null.
        [TestMethod]
        public void EncodeXmlNameNull()
        {
            Assert.IsNull(AzureNameEncoder.EncodeXmlName(null));
        }

        /// Empty returns empty.
        [TestMethod]
        public void EncodeXmlNameEmpty()
        {
            this.AssertEncoding(string.Empty, AzureNameEncoder.EncodeXmlName(string.Empty));
        }

        /// Single char works.
        [TestMethod]
        public void EncodeXmlNameSingleChar()
        {
            this.AssertEncoding("a", AzureNameEncoder.EncodeXmlName("a"));
        }

        /// Encoding escape char gets double escaped.
        [TestMethod]
        public void EncodeXmlNameWithEscapeCharacter()
        {
            var unencodedName = "a{0}b".FormatInvariant(AzureNameEncoder.XmlEscapeCharacter);
            var expectedEncodedName = "a{0}{1:X4}b"
                .FormatInvariant(AzureNameEncoder.XmlEscapeCharacter, Convert.ToInt32(AzureNameEncoder.XmlEscapeCharacter));
            var encodedName = AzureNameEncoder.EncodeXmlName(unencodedName);
            this.AssertEncoding(expectedEncodedName, encodedName);
        }

        /// The encoded name is a valid xml element name.
        [TestMethod]
        public void EncodeXmlName()
        {
            // \u0b83 is not a valid first char but won't be encoded otherwise.
            // \u16a0 should get encoded regardless
            var unencodedName = "\u0b83\u0b83\u16a0";
            var expectedEncodedName = "{0}0B83\u0b83{0}16A0".FormatInvariant(AzureNameEncoder.XmlEscapeCharacter);

            try
            {
                // The unencoded name should cause an xml exception
                new XElement(unencodedName, "somevalue");
                Assert.Fail();
            }
            catch (XmlException)
            {
            }

            var encodedName = AzureNameEncoder.EncodeXmlName(unencodedName);

            // The encoded name should not cause an xml exception
            var element = new XElement(encodedName, "somevalue");
            this.AssertEncoding(expectedEncodedName, element.Name.ToString());
        }

        /// The Azure encoded name can be xml encoded correctly.
        [TestMethod]
        public void EncodeXmlNameFromAzureEncodedName()
        {
            var surrogateSequence = char.ConvertFromUtf32(0x10380);
            var unencodedName = "\u0b83\u0b83\u16a0aAzZ_09\u4e00\u0304 \u9fcf" + surrogateSequence;
            var expectedFullyEncodedName = "{0}0B83\u0b83{0}16A0aAzZ{1}005F09\u4e00{1}0304{1}0020{1}9FCF{1}D800{1}DF80"
                .FormatInvariant(AzureNameEncoder.XmlEscapeCharacter, AzureNameEncoder.AzureEscapeCharacter);

            var azureEncodedName = AzureNameEncoder.EncodeAzureName(unencodedName);

            try
            {
                // The azure only encoded name should cause an xml exception
                new XElement(azureEncodedName, "somevalue");
                Assert.Fail();
            }
            catch (XmlException)
            {
            }

            var xmlEncodedName = AzureNameEncoder.EncodeXmlName(azureEncodedName);

            // The encoded name should not cause an xml exception
            var element = new XElement(xmlEncodedName, "somevalue");
            this.AssertEncoding(expectedFullyEncodedName, element.Name.ToString());
        }

        ///
        /// Null returns null
        ///
        [TestMethod]
        public void UNEncodeNameNull()
        {
            Assert.IsNull(AzureNameEncoder.UnencodeName(null, AzureNameEncoder.AzureEscapeCharacter));
        }

        ///
        /// Empty returns empty
        ///
        [TestMethod]
        public void UNEncodeNameEmpty()
        {
            this.AssertEncoding(string.Empty, AzureNameEncoder.UnencodeName(string.Empty, AzureNameEncoder.AzureEscapeCharacter));
        }

        /// AlphaNumeric names with no special characters should not change.
        [TestMethod]
        public void UNEncodeNameNoEncodedChars()
        {
            var encodedName = "aAzZ09\u4e00";
            var unencodedName = AzureNameEncoder.UnencodeName(encodedName, AzureNameEncoder.AzureEscapeCharacter);
            this.AssertEncoding(encodedName, unencodedName);
        }

        /// Encoding escape char gets double escaped.
        [TestMethod]
        public void UNEncodeNameThatEscapesTheEscapeCharacter()
        {
            var expectedUnencodedName = "a{0}b".FormatInvariant(AzureNameEncoder.AzureEscapeCharacter);
            var encodedName = "a{0}{1:X4}b"
                .FormatInvariant(AzureNameEncoder.AzureEscapeCharacter, Convert.ToInt32(AzureNameEncoder.AzureEscapeCharacter));
            var unencodedName = AzureNameEncoder.UnencodeName(encodedName, AzureNameEncoder.AzureEscapeCharacter);
            this.AssertEncoding(expectedUnencodedName, unencodedName);
        }

        ///
        /// Surrogate sequences are encoded
        /// (.Net strings with multiple 16-bit char values per unicode text element).
        ///
        [TestMethod]
        public void UNEncodeAzureNameSurrogateSequence()
        {
            var surrogateSequence = char.ConvertFromUtf32(0x10380);
            var expectedUnencodedName = "a" + surrogateSequence;
            var encodedName = "a{0}D800{0}DF80".FormatInvariant(AzureNameEncoder.AzureEscapeCharacter);
            var unencodedName = AzureNameEncoder.UnencodeAzureName(encodedName);
            this.AssertEncoding(expectedUnencodedName, unencodedName);
        }

        ///
        /// The strings are identical on a character level after roundtripping through
        /// Azure and Xml encoding.
        ///
        [TestMethod]
        public void RoundtripFullyEncoded()
        {
            var surrogateSequence = char.ConvertFromUtf32(0x10380);
            var unencodedName = "\u0b83\u0b83\u16a0aAzZ_09\u4e00\u0304 \u9fcf" + surrogateSequence;
            var expectedFullyEncodedName = "{0}0B83\u0b83{0}16A0aAzZ{1}005F09\u4e00{1}0304{1}0020{1}9FCF{1}D800{1}DF80"
                .FormatInvariant(AzureNameEncoder.XmlEscapeCharacter, AzureNameEncoder.AzureEscapeCharacter);

            var azureEncodedName = AzureNameEncoder.EncodeAzureName(unencodedName);
            var xmlEncodedName = AzureNameEncoder.EncodeXmlName(azureEncodedName);
            var xmlRountTripName = AzureNameEncoder.UnencodeXmlName(xmlEncodedName);
            var roundtripName = AzureNameEncoder.UnencodeAzureName(xmlRountTripName);

            this.AssertEncoding(expectedFullyEncodedName, xmlEncodedName);
            this.AssertEncoding(unencodedName, roundtripName);
        }

        /// Ordinal string compare of two strings.
        /// <param name="s1">first string.</param>
        /// <param name="s2">second string.</param>
        private void AssertEncoding(string s1, string s2)
        {
            Assert.AreEqual(0, string.CompareOrdinal(s1, s2));
        }
    }
}


text:
package io.github.giovibal.mqtt;

import java.nio.ByteBuffer;

/**
 * So how do we work around this lack of unsigned types? Well, you're probably
 * not going to like this... The answer is, you use the signed types that are
 * larger than the original unsigned type. I.e. use a short to hold an unsigned
 * byte, use a long to hold an unsigned int. (And use a char to hold an unsigned
 * short.). Yeah, this kinda sucks because now you're using twice as much
 * memory, but there really is no other solution. (Also bear in mind, access to
 * longs is not guaranteed to be atomic - although if you're using multiple
 * threads, you really should be using synchronization anyway.)
 */
public class ConversionUtility {
	final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

	public static byte[] fromHexString(String hex) {
		hex = hex.replaceAll("[^A-Fa-f0-9]", "");
		final int len = hex.length();

		int block = 2;
		int rest = (block - (len % (block)));
		rest = rest == block ? 0 : rest;

		byte[] out = null;
		if (len > 1) {
			out = new byte[(len + rest) / (2)];

			int counter = 0;

			for (int i = 0; i < len; i += (2)) {
				int h = hexToBin(hex.charAt(i));
				int l = hexToBin(hex.charAt(i + 1));
				if (h == -1 || l == -1) {
					throw new IllegalArgumentException("contains illegal character for hexBinary: " + hex);
				}
				out[counter++] = (byte) (h * 16 + l);
			}
		}
		return out;
	}

	@Deprecated
	public static byte[] fromHexString(String hex, String hexSeparator) {
		return fromHexString(hex);
	}

	public static String getHex(byte b) {
		return getHex(b, true);
	}

	public static String getHex(byte b, boolean prefix) {
		return String.format(prefix ? "%#04x" : "%02x", b);
	}

	public static String getHex(byte[] ba) {
		return getHex(ba, 0, ba.length);
	}

	public static String getHex(byte[] ba, int offset, int length) {
		return getHex(ba, offset, length, true);
	}

	public static String getHex(byte[] ba, int offset, int length, boolean prefix) {
		return (prefix ? "0x" : "") + toHexString(ba, offset, length, "");
	}

	public static String getHex(char b) {
		return getHex(b, true);
	}

	public static String getHex(char b, boolean prefix) {
		return String.format(prefix ? "%#04x" : "%02x", b);
	}

	public static String getHex(double b) {
		return getHex(b, true);
	}

	public static String getHex(double b, boolean prefix) {
		return String.format(prefix ? "%#018x" : "%016x", b);
	}

	public static String getHex(float b) {
		return getHex(b, true);
	}

	public static String getHex(float b, boolean prefix) {
		return String.format(prefix ? "%#010x" : "%08x", b);
	}

	public static String getHex(int b) {
		return getHex(b, true);
	}

	public static String getHex(int b, boolean prefix) {
		return String.format(prefix ? "%#010x" : "%08x", b);
	}

	public static String getHex(long b) {
		return getHex(b, true);
	}

	public static String getHex(long b, boolean prefix) {
		return String.format(prefix ? "%#018x" : "%016x", b);
	}

	public static String getHex(short b) {
		return getHex(b, true);
	}

	public static String getHex(short b, boolean prefix) {
		return String.format(prefix ? "%#06x" : "%04x", b);
	}

	public static String getUnsigned(byte b) {
		int result = b & 0xFF;
		return Integer.toString(result);
	}

	public static String getUnsigned(int b) {
		long result = b & 0xFFFFFFFF;
		return Long.toString(result);
	}

	public static String getUnsigned(short b) {
		int result = b & 0xFFFF;
		return Integer.toString(result);
	}

	private static int hexToBin(char ch) {
		if ('0' <= ch && ch <= '9') {
			return ch - '0';
		}
		else if ('A' <= ch && ch <= 'F') {
			return ch - 'A' + 10;
		}
		else if ('a' <= ch && ch <= 'f') {
			return ch - 'a' + 10;
		}
		return -1;
	}

	public static String toHexString(byte[] aByteArray) {
		return toHexString(aByteArray, 0, aByteArray.length, "");
	}

	public static String toHexString(byte[] bytes, int length, int offset, String separator) {
		char[] hexChars = new char[bytes.length * (2 + separator.length()) - separator.length()];
		char[] separatorChars = separator.toCharArray();
		int v;
		int step = 2 + separatorChars.length;

		for (int j = 0; j < bytes.length; j++) {
			v = bytes[j] & 0xFF;

			hexChars[j * step] = hexArray[v >>> 4];
			hexChars[j * step + 1] = hexArray[v & 0x0F];

			if (bytes.length - j > 1) {
				for (int s = 0; s < separatorChars.length; s++) {
					hexChars[j * step + 2 + s] = separatorChars[s];
				}
			}
		}

		return new String(hexChars);
	}

	public static String toHexString(byte[] aByteArray, String hexSeparator) {
		return toHexString(aByteArray, 0, aByteArray.length, hexSeparator);
	}

	public static String toHexString(ByteBuffer aByteBuffer) {
		return toHexString(aByteBuffer.array(), aByteBuffer.position(), aByteBuffer.capacity(), "");
	}

	public static String toHexString(ByteBuffer aByteBuffer, String hexSeparator) {
		return toHexString(aByteBuffer.array(), aByteBuffer.position(), aByteBuffer.capacity(), hexSeparator);
	}

	public static short unsigned(byte b) {
		short result = (short) (b & 0xFF);
		return result;
	}

	public static long unsigned(int b) {
		long result = (long)(b & 0xFFFFFFFFL);
		return result;
	}

	public static int unsigned(short b) {
		int result = b & 0xFFFF;
		return result;
	}

}


text:
package org.jboss.resteasy.cdi.test.intf.ejb;

public interface FooLocal2
{
   void foo2();
}


text:
  this.Config = {
    name: 'Bit Tiger',
    title: function() {
      return TAPi18n.__('configTitle');
    },
    subtitle: function() {
      return TAPi18n.__('configSubtitle');
    },
    logo: function() {
      return '<b>2' + this.name + '</b>';
    },
    footer: function() {
      return this.name + ' - Copyright ' + new Date().getFullYear();
    },
    emails: {
      from: 'noreply@' + Meteor.absoluteUrl()
    },
    blog: 'http://bittiger.io',
    about: 'http://bittiger.io',
    username: false,
    homeRoute: '/dashboard',
    socialMedia: [['https://www.facebook.com/steve.kehoe.98', 'facebook'], ['https://twitter.com/sjkdev1523', 'twitter'], ['https://github.com/oohaysmlm', 'github']]
  };

  Avatar.options = {
    customImageProperty: 'profile.picture'
  };

  Meteor.startup(function() {
    if (Meteor.isClient) {
      return TAPi18n.setLanguage('en');
    }
  });


text:
<?php

namespace Laravel\Scout\Console;

use Exception;
use Illuminate\Console\Command;
use Laravel\Scout\EngineManager;

class IndexCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'scout:index
            {name : The name of the index}
            {--k|key= : The name of the primary key}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create an index';

    /**
     * Execute the console command.
     *
     * @param  \Laravel\Scout\EngineManager  $manager
     * @return void
     */
    public function handle(EngineManager $manager)
    {
        $engine = $manager->engine();

        try {
            $options = [];

            if ($this->option('key')) {
                $options = ['primaryKey' => $this->option('key')];
            }

            $engine->createIndex($this->argument('name'), $options);

            $this->info('Index ["'.$this->argument('name').'"] created successfully.');
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }
}


text:
namespace policy {
namespace prefs {

// Non-specific prefs.
extern const char kStoreLogStatesAcrossReboots[];

}  // namespace prefs
}  // namespace policy

#endif  // CHROME_BROWSER_ASH_POLICY_CORE_POLICY_PREF_NAMES_H_


text:
#ifndef THRIFT_LIB_CPP_PROTOCOL_TNEUTRONIUMPROTOCOL_H_
#define THRIFT_LIB_CPP_PROTOCOL_TNEUTRONIUMPROTOCOL_H_

#include <thrift/lib/cpp/protocol/TProtocol.h>
#include <thrift/lib/cpp/protocol/TVirtualProtocol.h>
#include <thrift/lib/cpp/protocol/neutronium/Encoder.h>
#include <thrift/lib/cpp/protocol/neutronium/Decoder.h>

namespace apache { namespace thrift { namespace protocol {

class TNeutroniumProtocol
  : public TVirtualProtocol<TNeutroniumProtocol> {

 public:
  TNeutroniumProtocol(const neutronium::Schema* schema,
                      neutronium::InternTable* internTable,
                      folly::IOBuf* buf)
    : TVirtualProtocol<TNeutroniumProtocol>(nullptr),
      enc_(schema, internTable, buf),
      dec_(schema, internTable, buf) {
  }

  void setRootType(int64_t rootType) {
    enc_.setRootType(rootType);
    dec_.setRootType(rootType);
  }

  uint32_t writeMessageBegin(const std::string& name,
                             const TMessageType messageType,
                             const int32_t seqid) {
    LOG(FATAL) << "Message encoding / decoding not implemented";
    return 0;
  }

  uint32_t writeMessageEnd() {
    LOG(FATAL) << "Message encoding / decoding not implemented";
    return 0;
  }

  uint32_t writeStructBegin(const char* name) {
    enc_.writeStructBegin(name);
    return 0;
  }

  uint32_t writeStructEnd() {
    enc_.writeStructEnd();
    return enc_.bytesWritten();
  }

  uint32_t writeFieldBegin(const char* name,
                           const TType fieldType,
                           const int16_t fieldId) {
    enc_.writeFieldBegin(name, fieldType, fieldId);
    return 0;
  }

  uint32_t writeFieldEnd() {
    enc_.writeFieldEnd();
    return 0;
  }

  uint32_t writeFieldStop() {
    enc_.writeFieldStop();
    return 0;
  }

  uint32_t writeMapBegin(const TType keyType,
                         const TType valType,
                         const uint32_t size) {
    enc_.writeMapBegin(keyType, valType, size);
    return 0;
  }

  uint32_t writeMapEnd() {
    enc_.writeMapEnd();
    return 0;
  }

  uint32_t writeListBegin(const TType elemType, const uint32_t size) {
    enc_.writeListBegin(elemType, size);
    return 0;
  }

  uint32_t writeListEnd() {
    enc_.writeListEnd();
    return 0;
  }

  uint32_t writeSetBegin(const TType elemType, const uint32_t size) {
    enc_.writeSetBegin(elemType, size);
    return 0;
  }

  uint32_t writeSetEnd() {
    enc_.writeSetEnd();
    return 0;
  }

  uint32_t writeBool(const bool value) {
    enc_.writeBool(value);
    return 0;
  }

  uint32_t writeByte(const int8_t byte) {
    enc_.writeByte(byte);
    return 0;
  }

  uint32_t writeI16(const int16_t i16) {
    enc_.writeI16(i16);
    return 0;
  }

  uint32_t writeI32(const int32_t i32) {
    enc_.writeI32(i32);
    return 0;
  }

  uint32_t writeI64(const int64_t i64) {
    enc_.writeI64(i64);
    return 0;
  }

  uint32_t writeDouble(const double dub) {
    enc_.writeDouble(dub);
    return 0;
  }

  template <typename StrType>
  uint32_t writeString(const StrType& str) {
    enc_.writeString(str);
    return 0;
  }

  uint32_t writeBinary(const std::string& str) {
    enc_.writeBinary(str);
    return 0;
  }

  /**
   * Reading functions
   */

  uint32_t readMessageBegin(std::string& name,
                            TMessageType& messageType,
                            int32_t& seqid) {
    LOG(FATAL) << "Message encoding / decoding not implemented";
    return 0;
  }

  uint32_t readMessageEnd() {
    LOG(FATAL) << "Message encoding / decoding not implemented";
    return 0;
  }

  uint32_t readStructBegin(std::string& name) {
    dec_.readStructBegin();
    return 0;
  }

  uint32_t readStructEnd() {
    dec_.readStructEnd();
    return dec_.bytesRead();
  }

  uint32_t readFieldBegin(std::string& name,
                          TType& fieldType,
                          int16_t& fieldId) {
    dec_.readFieldBegin(fieldType, fieldId);
    return 0;
  }

  uint32_t readFieldEnd() {
    dec_.readFieldEnd();
    return 0;
  }

  uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size,
                        bool& sizeUnknown) {
    dec_.readMapBegin(keyType, valType, size, sizeUnknown);
    return 0;
  }

  uint32_t readMapEnd() {
    dec_.readMapEnd();
    return 0;
  }

  uint32_t readListBegin(TType& elemType, uint32_t& size, bool& sizeUnknown) {
    dec_.readListBegin(elemType, size, sizeUnknown);
    return 0;
  }

  uint32_t readListEnd() {
    dec_.readListEnd();
    return 0;
  }

  uint32_t readSetBegin(TType& elemType, uint32_t& size, bool& sizeUnknown) {
    dec_.readSetBegin(elemType, size, sizeUnknown);
    return 0;
  }

  uint32_t readSetEnd() {
    dec_.readSetEnd();
    return 0;
  }

  uint32_t readBool(bool& value) {
    dec_.readBool(value);
    return 0;
  }
  // Provide the default readBool() implementation for std::vector<bool>
  using TVirtualProtocol<TNeutroniumProtocol>::readBool;

  uint32_t readByte(int8_t& byte) {
    dec_.readByte(byte);
    return 0;
  }

  uint32_t readI16(int16_t& i16) {
    dec_.readI16(i16);
    return 0;
  }

  uint32_t readI32(int32_t& i32) {
    dec_.readI32(i32);
    return 0;
  }

  uint32_t readI64(int64_t& i64) {
    dec_.readI64(i64);
    return 0;
  }

  uint32_t readDouble(double& dub) {
    dec_.readDouble(dub);
    return 0;
  }

  template<typename StrType>
  uint32_t readString(StrType& str) {
    dec_.readString(str);
    return 0;
  }

  uint32_t readBinary(std::string& str) {
    dec_.readBinary(str);
    return 0;
  }

 private:
  neutronium::Encoder enc_;
  neutronium::Decoder dec_;
};

class Neutronium {
 public:
  explicit Neutronium(const neutronium::Schema* schema,
                      neutronium::InternTable* internTable,
                      folly::IOBuf* buf)
    : proto_(schema, internTable, buf) {
  }

  template <class T>
  uint32_t serialize(const T& obj) {
    proto_.setRootType(T::_reflection_id);
    return obj.write(&proto_);
  }

  template <class T>
  uint32_t deserialize(T& obj) {
    proto_.setRootType(T::_reflection_id);
    return obj.read(&proto_);
  }

 private:
  TNeutroniumProtocol proto_;
};

}}}  // apache::thrift::protocol

#endif /* THRIFT_LIB_CPP_PROTOCOL_TNEUTRONIUMPROTOCOL_H_ */


text:
package io.aeron.archive;

import io.aeron.Aeron;
import org.agrona.concurrent.UnsafeBuffer;

abstract class AbstractListRecordingsSession implements Session
{
    protected static final int MAX_SCANS_PER_WORK_CYCLE = 256;

    protected final UnsafeBuffer descriptorBuffer;
    protected final Catalog catalog;
    protected final ControlSession controlSession;
    protected final ControlResponseProxy proxy;
    protected final long correlationId;
    protected boolean isDone = false;

    AbstractListRecordingsSession(
        final long correlationId,
        final Catalog catalog,
        final ControlResponseProxy proxy,
        final ControlSession controlSession,
        final UnsafeBuffer descriptorBuffer)
    {
        this.correlationId = correlationId;
        this.controlSession = controlSession;
        this.catalog = catalog;
        this.proxy = proxy;
        this.descriptorBuffer = descriptorBuffer;
    }

    public void abort()
    {
        isDone = true;
    }

    public boolean isDone()
    {
        return isDone;
    }

    public long sessionId()
    {
        return Aeron.NULL_VALUE;
    }

    public int doWork()
    {
        int workCount = 0;

        if (!isDone)
        {
            workCount += sendDescriptors();
        }

        return workCount;
    }

    public void close()
    {
        controlSession.activeListing(null);
    }

    protected abstract int sendDescriptors();
}