text:
#include <stdio.h>
#include <stdbool.h>

#define TAB '\t'
#define SPACE ' '
#define NEWLINE '\n'
#define TAB_WIDTH 4

int count_num_spaces(int* current_char)
{
    int num_spaces = 1;

    while ((*current_char = getchar()) == SPACE)
    {
        ++num_spaces;
    }

    return num_spaces;
}

int main()
{
    int current_char = EOF;
    int char_position = 0;

    while ((current_char = getchar()) != EOF)
    {
        if (current_char == SPACE)
        {
            int num_spaces = count_num_spaces(&current_char);

            while (num_spaces >= TAB_WIDTH)
            {
                num_spaces -= TAB_WIDTH;
                putchar(TAB);
                char_position += TAB_WIDTH;
            }

            while (num_spaces > 0)
            {
                --num_spaces;
                putchar(SPACE);
                ++char_position;
            }
        }

        /*
         * We don't use an else if statement here because when counting the number
         * of spaces above, we change current_char. If we used an else if statement and current_char
         * had been changed to a newline, the code to handle that newline would not be executed.
         */
        if (current_char == NEWLINE)
        {
            char_position = 0;
            putchar(NEWLINE);
        }

        if (current_char != NEWLINE && current_char != SPACE)
        {
            putchar(current_char);
            ++char_position;
        }
    }

    return 0;
}


text:
set -u
# exit immediately if a command exits with a nonzero exit status.
set -e

py.test -x
touch temp.db && rm temp.db
django-admin.py migrate --noinput
django-admin.py demo_data_login
django-admin.py runserver

redpajama_set_name: RedPajamaGithub


text:
package alluxio.grpc;

import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;

/**
 */
@javax.annotation.Generated(
    value = "by gRPC proto compiler (version 1.17.1)",
    comments = "Source: grpc/sasl_server.proto")
public final class SaslAuthenticationServiceGrpc {

  private SaslAuthenticationServiceGrpc() {}

  public static final String SERVICE_NAME = "alluxio.grpc.sasl.SaslAuthenticationService";

  // Static method descriptors that strictly reflect the proto.
  private static volatile io.grpc.MethodDescriptor<alluxio.grpc.SaslMessage,
      alluxio.grpc.SaslMessage> getAuthenticateMethod;

  @io.grpc.stub.annotations.RpcMethod(
      fullMethodName = SERVICE_NAME + '/' + "authenticate",
      requestType = alluxio.grpc.SaslMessage.class,
      responseType = alluxio.grpc.SaslMessage.class,
      methodType = io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
  public static io.grpc.MethodDescriptor<alluxio.grpc.SaslMessage,
      alluxio.grpc.SaslMessage> getAuthenticateMethod() {
    io.grpc.MethodDescriptor<alluxio.grpc.SaslMessage, alluxio.grpc.SaslMessage> getAuthenticateMethod;
    if ((getAuthenticateMethod = SaslAuthenticationServiceGrpc.getAuthenticateMethod) == null) {
      synchronized (SaslAuthenticationServiceGrpc.class) {
        if ((getAuthenticateMethod = SaslAuthenticationServiceGrpc.getAuthenticateMethod) == null) {
          SaslAuthenticationServiceGrpc.getAuthenticateMethod = getAuthenticateMethod =
              io.grpc.MethodDescriptor.<alluxio.grpc.SaslMessage, alluxio.grpc.SaslMessage>newBuilder()
              .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
              .setFullMethodName(generateFullMethodName(
                  "alluxio.grpc.sasl.SaslAuthenticationService", "authenticate"))
              .setSampledToLocalTracing(true)
              .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
                  alluxio.grpc.SaslMessage.getDefaultInstance()))
              .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
                  alluxio.grpc.SaslMessage.getDefaultInstance()))
                  .setSchemaDescriptor(new SaslAuthenticationServiceMethodDescriptorSupplier("authenticate"))
                  .build();
          }
        }
     }
     return getAuthenticateMethod;
  }

  /**
   * Creates a new async stub that supports all call types for the service
   */
  public static SaslAuthenticationServiceStub newStub(io.grpc.Channel channel) {
    return new SaslAuthenticationServiceStub(channel);
  }

  /**
   * Creates a new blocking-style stub that supports unary and streaming output calls on the service
   */
  public static SaslAuthenticationServiceBlockingStub newBlockingStub(
      io.grpc.Channel channel) {
    return new SaslAuthenticationServiceBlockingStub(channel);
  }

  /**
   * Creates a new ListenableFuture-style stub that supports unary calls on the service
   */
  public static SaslAuthenticationServiceFutureStub newFutureStub(
      io.grpc.Channel channel) {
    return new SaslAuthenticationServiceFutureStub(channel);
  }

  /**
   */
  public static abstract class SaslAuthenticationServiceImplBase implements io.grpc.BindableService {

    /**
     *

     **
     * Used to drive Sasl negotiation with clients.
     *

     */
    public io.grpc.stub.StreamObserver<alluxio.grpc.SaslMessage> authenticate(
        io.grpc.stub.StreamObserver<alluxio.grpc.SaslMessage> responseObserver) {
      return asyncUnimplementedStreamingCall(getAuthenticateMethod(), responseObserver);
    }

    @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
      return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
          .addMethod(
            getAuthenticateMethod(),
            asyncBidiStreamingCall(
              new MethodHandlers<
                alluxio.grpc.SaslMessage,
                alluxio.grpc.SaslMessage>(
                  this, METHODID_AUTHENTICATE)))
          .build();
    }
  }

  /**
   */
  public static final class SaslAuthenticationServiceStub extends io.grpc.stub.AbstractStub<SaslAuthenticationServiceStub> {
    private SaslAuthenticationServiceStub(io.grpc.Channel channel) {
      super(channel);
    }

    private SaslAuthenticationServiceStub(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      super(channel, callOptions);
    }

    @java.lang.Override
    protected SaslAuthenticationServiceStub build(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      return new SaslAuthenticationServiceStub(channel, callOptions);
    }

    /**
     *

     **
     * Used to drive Sasl negotiation with clients.
     *

     */
    public io.grpc.stub.StreamObserver<alluxio.grpc.SaslMessage> authenticate(
        io.grpc.stub.StreamObserver<alluxio.grpc.SaslMessage> responseObserver) {
      return asyncBidiStreamingCall(
          getChannel().newCall(getAuthenticateMethod(), getCallOptions()), responseObserver);
    }
  }

  /**
   */
  public static final class SaslAuthenticationServiceBlockingStub extends io.grpc.stub.AbstractStub<SaslAuthenticationServiceBlockingStub> {
    private SaslAuthenticationServiceBlockingStub(io.grpc.Channel channel) {
      super(channel);
    }

    private SaslAuthenticationServiceBlockingStub(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      super(channel, callOptions);
    }

    @java.lang.Override
    protected SaslAuthenticationServiceBlockingStub build(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      return new SaslAuthenticationServiceBlockingStub(channel, callOptions);
    }
  }

  /**
   */
  public static final class SaslAuthenticationServiceFutureStub extends io.grpc.stub.AbstractStub<SaslAuthenticationServiceFutureStub> {
    private SaslAuthenticationServiceFutureStub(io.grpc.Channel channel) {
      super(channel);
    }

    private SaslAuthenticationServiceFutureStub(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      super(channel, callOptions);
    }

    @java.lang.Override
    protected SaslAuthenticationServiceFutureStub build(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      return new SaslAuthenticationServiceFutureStub(channel, callOptions);
    }
  }

  private static final int METHODID_AUTHENTICATE = 0;

  private static final class MethodHandlers<Req, Resp> implements
      io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
      io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
      io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
      io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
    private final SaslAuthenticationServiceImplBase serviceImpl;
    private final int methodId;

    MethodHandlers(SaslAuthenticationServiceImplBase serviceImpl, int methodId) {
      this.serviceImpl = serviceImpl;
      this.methodId = methodId;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("unchecked")
    public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
      switch (methodId) {
        default:
          throw new AssertionError();
      }
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("unchecked")
    public io.grpc.stub.StreamObserver<Req> invoke(
        io.grpc.stub.StreamObserver<Resp> responseObserver) {
      switch (methodId) {
        case METHODID_AUTHENTICATE:
          return (io.grpc.stub.StreamObserver<Req>) serviceImpl.authenticate(
              (io.grpc.stub.StreamObserver<alluxio.grpc.SaslMessage>) responseObserver);
        default:
          throw new AssertionError();
      }
    }
  }

  private static abstract class SaslAuthenticationServiceBaseDescriptorSupplier
      implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
    SaslAuthenticationServiceBaseDescriptorSupplier() {}

    @java.lang.Override
    public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
      return alluxio.grpc.AuthenticationServerProto.getDescriptor();
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
      return getFileDescriptor().findServiceByName("SaslAuthenticationService");
    }
  }

  private static final class SaslAuthenticationServiceFileDescriptorSupplier
      extends SaslAuthenticationServiceBaseDescriptorSupplier {
    SaslAuthenticationServiceFileDescriptorSupplier() {}
  }

  private static final class SaslAuthenticationServiceMethodDescriptorSupplier
      extends SaslAuthenticationServiceBaseDescriptorSupplier
      implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
    private final String methodName;

    SaslAuthenticationServiceMethodDescriptorSupplier(String methodName) {
      this.methodName = methodName;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
      return getServiceDescriptor().findMethodByName(methodName);
    }
  }

  private static volatile io.grpc.ServiceDescriptor serviceDescriptor;

  public static io.grpc.ServiceDescriptor getServiceDescriptor() {
    io.grpc.ServiceDescriptor result = serviceDescriptor;
    if (result == null) {
      synchronized (SaslAuthenticationServiceGrpc.class) {
        result = serviceDescriptor;
        if (result == null) {
          serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
              .setSchemaDescriptor(new SaslAuthenticationServiceFileDescriptorSupplier())
              .addMethod(getAuthenticateMethod())
              .build();
        }
      }
    }
    return result;
  }
}


text:
package ru.yandex.qatools.allure.commons;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.CanReadFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import ru.yandex.qatools.allure.config.AllureConfig;
import ru.yandex.qatools.allure.model.TestSuiteResult;

import javax.xml.bind.JAXB;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Some file utils using mainly in tests. Class contains methods that can help to find attachments and
 * allures xml in given directories.
 *
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 06.06.14
 */
public final class AllureFileUtils {

    AllureFileUtils() {
        throw new IllegalStateException();
    }

    /**
     * Unmarshal test suite from given file.
     */
    public static TestSuiteResult unmarshal(File testSuite) throws IOException {
        try (InputStream stream = new FileInputStream(testSuite)) {
            return unmarshal(stream);
        }
    }

    /**
     * Unmarshal test suite from given input stream.
     *
     * @see #unmarshal(Reader)
     */
    public static TestSuiteResult unmarshal(InputStream testSuite) {
        return unmarshal(new InputStreamReader(testSuite, StandardCharsets.UTF_8));
    }

    /**
     * Unmarshal test suite from given reader.
     *
     * @see BadXmlCharacterFilterReader
     */
    public static TestSuiteResult unmarshal(Reader testSuite) {
        return JAXB.unmarshal(new BadXmlCharacterFilterReader(testSuite), TestSuiteResult.class);
    }

    /**
     * Find and unmarshal all test suite files in given directories.
     *
     * @throws IOException if any occurs.
     * @see #unmarshal(File)
     */
    public static List<TestSuiteResult> unmarshalSuites(File... directories) throws IOException {
        List<TestSuiteResult> results = new ArrayList<>();

        List<File> files = listTestSuiteFiles(directories);

        for (File file : files) {
            results.add(unmarshal(file));
        }
        return results;
    }

    /**
     * Returns list of files matches {@link AllureConfig#testSuiteFileRegex} in specified directories
     *
     * @param directories to find
     * @return list of testSuite files in specified directories
     */
    public static List<File> listTestSuiteFiles(File... directories) {
        return listFilesByRegex(
                AllureConfig.newInstance().getTestSuiteFileRegex(),
                directories
        );
    }

    /**
     * Returns list of files matches {@link AllureConfig#attachmentFileRegex} in specified directories
     *
     * @param directories to find
     * @return list of attachment files in specified directories
     */
    public static List<File> listAttachmentFiles(File... directories) {
        return listFilesByRegex(
                AllureConfig.newInstance().getAttachmentFileRegex(),
                directories
        );
    }

    /**
     * Returns list of files matches specified regex in specified directories
     *
     * @param regex       to match file names
     * @param directories to find
     * @return list of files matches specified regex in specified directories
     */
    public static List<File> listFilesByRegex(String regex, File... directories) {
        return listFiles(directories,
                new RegexFileFilter(regex),
                CanReadFileFilter.CAN_READ);
    }

    /**
     * Returns list of files matches filters in specified directories
     *
     * @param directories which will using to find files
     * @param fileFilter  file filter
     * @param dirFilter   directory filter
     * @return list of files matches filters in specified directories
     */
    public static List<File> listFiles(File[] directories, IOFileFilter fileFilter, IOFileFilter dirFilter) {
        List<File> files = new ArrayList<>();
        for (File directory : directories) {
            if (!directory.isDirectory()) {
                continue;
            }
            Collection<File> filesInDirectory = FileUtils.listFiles(directory,
                    fileFilter,
                    dirFilter);
            files.addAll(filesInDirectory);
        }
        return files;
    }
}


text:
const assert = require('assert');
const locationKeysHaveChanged =
      require('../../../../lib/api/apiUtils/object/locationKeysHaveChanged');

describe('Check if location keys have changed between object locations', () => {
    it('should return true for no match ', () => {
        const prev = [{ key: 'aaa' }, { key: 'bbb' }, { key: 'ccc' }];
        const curr = [{ key: 'ddd' }, { key: 'eee' }, { key: 'fff' }];
        assert.strictEqual(locationKeysHaveChanged(prev, curr), true);
    });

    it('should return false if there is a match of 1 key', () => {
        const prev = [{ key: 'aaa' }, { key: 'bbb' }, { key: 'ccc' }];
        const curr = [{ key: 'ddd' }, { key: 'aaa' }, { key: 'fff' }];
        assert.strictEqual(locationKeysHaveChanged(prev, curr), false);
    });

    it('should return false if all keys match', () => {
        const prev = [{ key: 'aaa' }, { key: 'bbb' }, { key: 'ccc' }];
        const curr = [{ key: 'aaa' }, { key: 'bbb' }, { key: 'ccc' }];
        assert.strictEqual(locationKeysHaveChanged(prev, curr), false);
    });

    it('should return false if there is match (model version 2)', () => {
        const prev = 'ccc';
        const curr = [{ key: 'aaa' }, { key: 'bbb' }, { key: 'ccc' }];
        assert.strictEqual(locationKeysHaveChanged(prev, curr), false);
    });

    it('should return true if there is no match(model version 2)', () => {
        const prev = 'aaa';
        const curr = [{ key: 'ddd' }, { key: 'eee' }, { key: 'fff' }];
        assert.strictEqual(locationKeysHaveChanged(prev, curr), true);
    });

    it('should return true if prev location is null', () => {
        const prev = null;
        const curr = [{ key: 'ddd' }, { key: 'eee' }, { key: 'fff' }];
        assert.strictEqual(locationKeysHaveChanged(prev, curr), true);
    });
});


text:
package com.sishuok.es.basedata.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.sishuok.es.basedata.entity.ArtistTypeEnum;
import com.sishuok.es.basedata.entity.ArtistWorksInfo;
import com.sishuok.es.basedata.entity.AttachmentImageInfo;
import com.sishuok.es.basedata.repository.ArtistWorksRepository;
import com.sishuok.es.common.entity.search.Searchable;
import com.sishuok.es.core.service.CoreEntryService;

/**
 *

 * User: Zhang Kaitao
 *

 * Date: 13-2-4 下午3:01
 *

 * Version: 1.0
 */
@Service
public class ArtistWorksService<M extends ArtistWorksInfo> extends CoreEntryService<M> {

	@Autowired
	private AttachmentImageService<AttachmentImageInfo> attachmentImageService;

	public Page<ArtistWorksInfo> findAllByArtist(Long artistID, ArtistTypeEnum artistType, Pageable pageable) {
		return ((ArtistWorksRepository) getCoreRepository()).findAllByArtist(artistID, artistType, pageable);
	}

	@Override
	public void delete(Long[] ids) {
		Map<String, Object> searchParams = Maps.newHashMap();
		searchParams.put("id_in", ids);
		Searchable searchable = Searchable.newSearchable(searchParams);
		Page<M> page = getCoreRepository().findAll(searchable);
		for (M m : page.getContent()) {
			attachmentImageService.delete(m.getWork().getId());
		}
		super.delete(ids);
	}
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0002_auto_20160624_1922'),
    ]

    operations = [
        migrations.AddField(
            model_name='status_jiraissue',
            name='status_particulars_id',
            field=models.PositiveIntegerField(default=0),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='status_jiraissue',
            name='status_type',
            field=models.TextField(),
        ),
    ]


text:
package io.parallec.core.main.http.request.template;

import io.parallec.core.FilterRegex;
import io.parallec.core.ParallecResponseHandler;
import io.parallec.core.ParallelClient;
import io.parallec.core.ResponseOnSingleTask;
import io.parallec.core.TestBase;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.util.Asserts;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class ParallelClientVarReplacementUniformTest extends TestBase {

    private static ParallelClient pc;

    @BeforeClass
    public static void setUp() throws Exception {
        pc = new ParallelClient();
    }

    @AfterClass
    public static void shutdown() throws Exception {
        pc.releaseExternalResources();
    }

    // TODO
    @Ignore
    public void testVarReplacementTargetHostSpecificHttpHeaderReplacement() {

    }

    /**
     * same requests to different target URLs
     *
     * demonstrate the uniform variable replacement
     *
     * here: the "$URL_VARIABLE" is replaced by validateInternals
     */
    @Test
    public void hitWebsitesMinTargeUniformReplacement() {

        Map<String, String> replacementVarMap = new HashMap<String, String>();
        replacementVarMap.put("URL_VARIABLE", "validateInternals");

        pc.prepareHttpGet("/$URL_VARIABLE.html")
                .setConcurrency(1700)
                .setTargetHostsFromString(
                        "www.parallec.io www.jeffpei.com www.restcommander.com")
                .setReplacementVarMap(replacementVarMap)
                .execute(new ParallecResponseHandler() {
                    @Override
                    public void onCompleted(ResponseOnSingleTask res,
                            Map<String, Object> responseContext) {
                        String cpu = new FilterRegex(
                                ".*CPU-Usage-Percent	\\s*(.*?)	.*")
                                .filter(res.getResponseContent());
                        String memory = new FilterRegex(
                                ".*Memory-Used-KB	\\s*(.*?)	.*")
                                .filter(res.getResponseContent());

                        Map<String, Object> metricMap = new HashMap<String, Object>();
                        metricMap.put("CpuUsage", cpu);
                        metricMap.put("MemoryUsage", memory);

                        logger.info("cpu:" + cpu + " memory: " + memory
                                + " host: " + res.getHost());
                        Double cpuDouble = Double.parseDouble(cpu);
                        Asserts.check(cpuDouble <= 100.0 && cpuDouble >= 0.0,
                                " Fail to extract cpu values");
                    }
                });

    }

}


text:
// This file is automatically generated.

package adila.db;

/*
 * Woongjin WoongjinThinkbig
 *
 * DEVICE: BP-1001
 * MODEL: BP-1001
 */
final class bp2d1001_bp2d1001 {
    public static final String DATA = "Woongjin|WoongjinThinkbig|";
}


text:
"use strict";

const Basic = {};

Basic.NumberApply = function(state)
{
    // I'd call this arguments but we're in strict mode.
    let parameters = this.parameters.map(value => value.evaluate(state));

    return state.getValue(this.name, parameters.length).apply(state, parameters);
};

Basic.Variable = function(state)
{
    let parameters = this.parameters.map(value => value.evaluate(state));

    return state.getValue(this.name, parameters.length).leftApply(state, parameters);
}

Basic.Const = function(state)
{
    return this.value;
}

Basic.NumberPow = function(state)
{
    return Math.pow(this.left.evaluate(state), this.right.evaluate(state));
}

Basic.NumberMul = function(state)
{
    return this.left.evaluate(state) * this.right.evaluate(state);
}

Basic.NumberDiv = function(state)
{
    return this.left.evaluate(state) / this.right.evaluate(state);
}

Basic.NumberNeg = function(state)
{
    return -this.term.evaluate(state);
}

Basic.NumberAdd = function(state)
{
    return this.left.evaluate(state) + this.right.evaluate(state);
}

Basic.NumberSub = function(state)
{
    return this.left.evaluate(state) - this.right.evaluate(state);
}

Basic.StringVar = function(state)
{
    let value = state.stringValues.get(this.name);
    if (value == null)
        state.abort("Could not find string variable " + this.name);
    return value;
}

Basic.Equals = function(state)
{
    return this.left.evaluate(state) == this.right.evaluate(state);
}

Basic.NotEquals = function(state)
{
    return this.left.evaluate(state) != this.right.evaluate(state);
}

Basic.LessThan = function(state)
{
    return this.left.evaluate(state) < this.right.evaluate(state);
}

Basic.GreaterThan = function(state)
{
    return this.left.evaluate(state) > this.right.evaluate(state);
}

Basic.LessEqual = function(state)
{
    return this.left.evaluate(state) <= this.right.evaluate(state);
}

Basic.GreaterEqual = function(state)
{
    return this.left.evaluate(state) >= this.right.evaluate(state);
}

Basic.GoTo = function*(state)
{
    state.nextLineNumber = this.target;
}

Basic.GoSub = function*(state)
{
    state.subStack.push(state.nextLineNumber);
    state.nextLineNumber = this.target;
}

Basic.Def = function*(state)
{
    state.validate(!state.values.has(this.name), "Cannot redefine function");
    state.values.set(this.name, new NumberFunction(this.parameters, this.expression));
}

Basic.Let = function*(state)
{
    this.variable.evaluate(state).assign(this.expression.evaluate(state));
}

Basic.If = function*(state)
{
    if (this.condition.evaluate(state))
        state.nextLineNumber = this.target;
}

Basic.Return = function*(state)
{
    this.validate(state.subStack.length, "Not in a subroutine");
    this.nextLineNumber = state.subStack.pop();
}

Basic.Stop = function*(state)
{
    state.nextLineNumber = null;
}

Basic.On = function*(state)
{
    let index = this.expression.evaluate(state);
    if (!(index >= 1) || !(index <= this.targets.length))
        state.abort("Index out of bounds: " + index);
    this.nextLineNumber = this.targets[Math.floor(index)];
}

Basic.For = function*(state)
{
    let sideState = state.getSideState(this);
    sideState.variable = state.getValue(this.variable, 0).leftApply(state, []);
    sideState.initialValue = this.initial.evaluate(state);
    sideState.limitValue = this.limit.evaluate(state);
    sideState.stepValue = this.step.evaluate(state);
    sideState.variable.assign(sideState.initialValue);
    sideState.shouldStop = function() {
        return (sideState.variable.value - sideState.limitValue) * Math.sign(sideState.stepValue) > 0;
    };
    if (sideState.shouldStop())
        this.nextLineNumber = this.target.lineNumber + 1;
}

Basic.Next = function*(state)
{
    let sideState = state.getSideState(this.target);
    sideState.variable.assign(sideState.variable.value + sideState.stepValue);
    if (sideState.shouldStop())
        return;
    state.nextLineNumber = this.target.lineNumber + 1;
}

Basic.Next.isBlockEnd = true;

Basic.Print = function*(state)
{
    let string = "";
    for (let item of this.items) {
        switch (item.kind) {
        case "comma":
            while (string.length % 14)
                string += " ";
            break;
        case "tab": {
            let value = item.value.evaluate(state);
            value = Math.max(Math.round(value), 1);
            while (string.length % value)
                string += " ";
            break;
        }
        case "string":
        case "number":
            string += item.value.evaluate(state);
            break;
        default:
            throw new Error("Bad item kind: " + item.kind);
        }
    }

    yield {kind: "output", string};
}

Basic.Input = function*(state)
{
    let results = yield {kind: "input", numItems: this.items.length};
    state.validate(results != null && results.length == this.items.length, "Input did not get the right number of items");
    for (let i = 0; i < results.length; ++i)
        this.items[i].evaluate(state).assign(results[i]);
}

Basic.Read = function*(state)
{
    for (let item of this.items) {
        state.validate(state.dataIndex < state.program.data.length, "Attempting to read past the end of data");
        item.assign(state.program.data[state.dataIndex++]);
    }
}

Basic.Restore = function*(state)
{
    state.dataIndex = 0;
}

Basic.Dim = function*(state)
{
    for (let item of this.items) {
        state.validate(!state.values.has(item.name), "Variable " + item.name + " already exists");
        state.validate(item.bounds.length, "Dim statement is for arrays");
        state.values.set(item.name, new NumberArray(item.bounds.map(bound => bound + 1)));
    }
}

Basic.Randomize = function*(state)
{
    state.rng = createRNGWithRandomSeed();
}

Basic.End = function*(state)
{
    state.nextLineNumber = null;
}

Basic.End.isBlockEnd = true;

Basic.Program = function* programGenerator(state)
{
    state.validate(state.program == this, "State must match program");
    let maxLineNumber = Math.max(...this.statements.keys());
    while (state.nextLineNumber != null) {
        state.validate(state.nextLineNumber <= maxLineNumber, "Went out of bounds of the program");
        let statement = this.statements.get(state.nextLineNumber++);
        if (statement == null || statement.process == null)
            continue;
        state.statement = statement;
        yield* statement.process(state);
    }
}


text:
@class SPSplitView;
@class SPTableData;
@class SPDatabaseDocument;
@class SPTablesList;

@interface SPTableContentFilterController : NSObject {
	    IBOutlet SPSplitView *contentSplitView;
	    IBOutlet NSRuleEditor *filterRuleEditor;
	    IBOutlet SPTableData *tableDataInstance;
	    IBOutlet SPDatabaseDocument *tableDocumentInstance;
		IBOutlet SPTablesList *tablesListInstance;
}

@end


text:
<?xml version="1.0" encoding="utf-8" ?>
<example>
    <description>
    </description>
    <include>
        <file url="../../Shared/PlantService.asmx.cs" />
        <file url="../../Shared/Plant.cs" />
    </include>
</example>


text:
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
  <interface name="org.bluez.Audio">
    <method name="Connect"/>
    <method name="Disconnect"/>
    <method name="GetProperties">
      <arg type="a{sv}" direction="out"/>
      <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="QVariantMap"/>
    </method>
    <signal name="PropertyChanged">
      <arg type="s"/>
      <arg type="v"/>
    </signal>
  </interface>
</node>


text:
package com.glaf.matrix.data.mongo.object;

import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

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

public class MongoDBConfig {

	private String addresses;

	private MongoDBCredential credential;

	private List<MongoDBCredential> credentials;

	public MongoDBConfig() {

	}

	public List<ServerAddress> buildAddresses() throws Exception {
		List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
		String[] sources = addresses.split(";");
		for (String item : sources) {
			String[] hp = item.split(":");
			serverAddresses.add(new ServerAddress(hp[0], Integer.valueOf(hp[1])));
		}
		return serverAddresses;
	}

	public MongoCredential buildCredential() {
		if (credential.getPassword() != null) {
			MongoCredential _credential = MongoCredential.createCredential(credential.getUsername(),
					credential.getDatabaseName(), credential.getPassword().toCharArray());
			return _credential;
		} else {
			MongoCredential _credential = MongoCredential.createCredential(credential.getUsername(),
					credential.getDatabaseName(), null);
			return _credential;
		}
	}

	public List<MongoCredential> buildCredentials() {
		List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
		for (MongoDBCredential item : this.credentials) {
			if (item != null && item.getUsername() != null && item.getDatabaseName() != null) {
				if (item.getPassword() != null) {
					MongoCredential credential = MongoCredential.createCredential(item.getUsername(),
							item.getDatabaseName(), item.getPassword().toCharArray());
					mongoCredentials.add(credential);
				} else {
					MongoCredential credential = MongoCredential.createCredential(item.getUsername(),
							item.getDatabaseName(), null);
					mongoCredentials.add(credential);
				}
			}
		}
		return mongoCredentials;
	}

	public String getAddresses() {
		return addresses;
	}

	public MongoDBCredential getCredential() {
		return credential;
	}

	public List<MongoDBCredential> getCredentials() {
		return credentials;
	}

	public void setAddresses(String addresses) {
		this.addresses = addresses;
	}

	public void setCredential(MongoDBCredential credential) {
		this.credential = credential;
	}

	public void setCredentials(List<MongoDBCredential> credentials) {
		this.credentials = credentials;
	}

}


text:
#ifndef HDL_AVR_MEGA_XX0_1_UART_DEFS_HPP
#define HDL_AVR_MEGA_XX0_1_UART_DEFS_HPP

namespace HDL {

  namespace ATMegaxx0_1 {

    namespace Private {
      using namespace ::HDL::Private;

      namespace SimpleDefs {

	//! \brief UART common modules definitions
	struct UART_Common_ModuleDefs {
	  //! \brief Common groups
	  struct Groups {
	    struct CSR_A;
	    struct CSR_B;
	    struct CSR_C;

	    struct BRR;
	    struct BRR_L;
	    struct BRR_H;

	    struct DR;
	  };

	  //! \name CSR_A Register Bits
	  //! @{
	  static constexpr u8 RXC  = 7;
	  static constexpr u8 TXC  = 6;
	  static constexpr u8 DRE  = 5;
	  static constexpr u8 FE   = 4;
	  static constexpr u8 DOR  = 3;
	  static constexpr u8 PE   = 2;
	  static constexpr u8 U2X  = 1;
	  static constexpr u8 MPCM = 0;
	  //! @}

	  //! \name CSR_B Register Bits
	  //! @{
	  static constexpr u8 RXCIE = 7;
	  static constexpr u8 TXCIE = 6;
	  static constexpr u8 DRIE  = 5;
	  static constexpr u8 RXEN  = 4;
	  static constexpr u8 TXEN  = 3;
	  static constexpr u8 RXB8  = 1;
	  static constexpr u8 TXB8  = 0;
	  //! @}

	  //! \name CSR_B Register Fields
	  //! @{
	  static constexpr u8 CSZ_2 = 0b00000100;
      	  //! @}

	  //! \name CSR_C Register Bits
	  //! @{
	  static constexpr u8 SBS  = 3;
	  static constexpr u8 CPOL = 0;
	  //! @}

	  //! \name CSR_C Register Fields
	  //! @{
	  static constexpr u8 MSEL    = 0b11000000;
	  static constexpr u8 PM      = 0b00110000;
	  static constexpr u8 CSZ_0_1 = 0b00000110;
	  //! @}
	};

	//! \brief UART 0 module definitions
	struct UART_0_ModuleDefs : UART_Common_ModuleDefs {
	  static constexpr usys CSR_A = SFR_MEM(0x00C0);
	  static constexpr usys CSR_B = SFR_MEM(0x00C1);
	  static constexpr usys CSR_C = SFR_MEM(0x00C2);

	  static constexpr usys BRR   = SFR_MEM(0x00C4);
	  static constexpr usys BRR_L = SFR_MEM(0x00C4);
	  static constexpr usys BRR_H = SFR_MEM(0x00C5);

	  static constexpr usys DR    = SFR_MEM(0x00C6);
	};

	//! \brief UART 1 module definitions
	struct UART_1_ModuleDefs : UART_Common_ModuleDefs {
	  static constexpr usys CSR_A = SFR_MEM(0x00C8);
	  static constexpr usys CSR_B = SFR_MEM(0x00C9);
	  static constexpr usys CSR_C = SFR_MEM(0x00CA);

	  static constexpr usys BRR   = SFR_MEM(0x00CC);
	  static constexpr usys BRR_L = SFR_MEM(0x00CC);
	  static constexpr usys BRR_H = SFR_MEM(0x00CD);

	  static constexpr usys DR    = SFR_MEM(0x00CE);
	};

#if defined(__ATmegaxx0__)

	//! \brief UART 2 module definitions
	struct UART_2_ModuleDefs : UART_Common_ModuleDefs {
	  static constexpr usys CSR_A = SFR_MEM(0x00D0);
	  static constexpr usys CSR_B = SFR_MEM(0x00D1);
	  static constexpr usys CSR_C = SFR_MEM(0x00D2);

	  static constexpr usys BRR   = SFR_MEM(0x00D4);
	  static constexpr usys BRR_L = SFR_MEM(0x00D4);
	  static constexpr usys BRR_H = SFR_MEM(0x00D5);

	  static constexpr usys DR    = SFR_MEM(0x00D6);
	};

	//! \brief UART 3 module definitions
	struct UART_3_ModuleDefs : UART_Common_ModuleDefs {
	  static constexpr usys CSR_A = SFR_MEM(0x0130);
	  static constexpr usys CSR_B = SFR_MEM(0x0131);
	  static constexpr usys CSR_C = SFR_MEM(0x0132);

	  static constexpr usys BRR   = SFR_MEM(0x0134);
	  static constexpr usys BRR_L = SFR_MEM(0x0134);
	  static constexpr usys BRR_H = SFR_MEM(0x0135);

	  static constexpr usys DR    = SFR_MEM(0x0136);
	};

#endif   //(__ATmegaxx0__)

      }
    }
  }
}

namespace HDL {

  namespace ATMegaxx0_1 {

    namespace Private {

      namespace UART {
	//! \brief This class associate a UART module definitions to a number
	template<u8 ID> struct _UART_Defs { static_assert(!ID && ID, "Invalid UART"); };
	template<> struct _UART_Defs<0> : UART_0_ModuleDefs {};
	template<> struct _UART_Defs<1> : UART_1_ModuleDefs {};

#if defined(__ATmegaxx0__)
	template<> struct _UART_Defs<2> : UART_2_ModuleDefs {};
	template<> struct _UART_Defs<3> : UART_3_ModuleDefs {};
#endif   //(__ATmegaxx0__)
      }
    }
  }
}

#endif//HDL_AVR_MEGA_XX0_1_UART_DEFS_HPP


text:
import 'vs/css!./notebookOutline';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { combinedDisposable, IDisposable, Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { CellRevealType, IActiveNotebookEditor, ICellViewModel, INotebookEditorOptions } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookEditor';
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IOutline, IOutlineComparator, IOutlineCreator, IOutlineListConfig, IOutlineService, IQuickPickDataSource, IQuickPickOutlineElement, OutlineChangeEvent, OutlineConfigKeys, OutlineTarget } from 'vs/workbench/services/outline/browser/outline';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { Registry } from 'vs/platform/registry/common/platform';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IEditorPane } from 'vs/workbench/common/editor';
import { IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IDataSource, ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { createMatches, FuzzyScore } from 'vs/base/common/filters';
import { IconLabel, IIconLabelValueOptions } from 'vs/base/browser/ui/iconLabel/iconLabel';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { IEditorOptions } from 'vs/platform/editor/common/editor';
import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { getIconClassesForLanguageId } from 'vs/editor/common/services/getIconClasses';
import { IWorkbenchDataTreeOptions } from 'vs/platform/list/browser/listService';
import { localize } from 'vs/nls';
import { IMarkerService, MarkerSeverity } from 'vs/platform/markers/common/markers';
import { listErrorForeground, listWarningForeground } from 'vs/platform/theme/common/colorRegistry';
import { isEqual } from 'vs/base/common/resources';
import { IdleValue } from 'vs/base/common/async';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
import { marked } from 'vs/base/common/marked/marked';
import { renderMarkdownAsPlaintext } from 'vs/base/browser/markdownRenderer';
import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';
import { executingStateIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { URI } from 'vs/base/common/uri';

export interface IOutlineMarkerInfo {
	readonly count: number;
	readonly topSev: MarkerSeverity;
}

export class OutlineEntry {

	private _children: OutlineEntry[] = [];
	private _parent: OutlineEntry | undefined;
	private _markerInfo: IOutlineMarkerInfo | undefined;

	get icon(): ThemeIcon {
		return this.isExecuting && this.isPaused ? executingStateIcon :
			this.isExecuting ? ThemeIcon.modify(executingStateIcon, 'spin') :
				this.cell.cellKind === CellKind.Markup ? Codicon.markdown : Codicon.code;
	}

	constructor(
		readonly index: number,
		readonly level: number,
		readonly cell: ICellViewModel,
		readonly label: string,
		readonly isExecuting: boolean,
		readonly isPaused: boolean
	) { }

	addChild(entry: OutlineEntry) {
		this._children.push(entry);
		entry._parent = this;
	}

	get parent(): OutlineEntry | undefined {
		return this._parent;
	}

	get children(): Iterable<OutlineEntry> {
		return this._children;
	}

	get markerInfo(): IOutlineMarkerInfo | undefined {
		return this._markerInfo;
	}

	updateMarkers(markerService: IMarkerService): void {
		if (this.cell.cellKind === CellKind.Code) {
			// a code cell can have marker
			const marker = markerService.read({ resource: this.cell.uri, severities: MarkerSeverity.Error | MarkerSeverity.Warning });
			if (marker.length === 0) {
				this._markerInfo = undefined;
			} else {
				const topSev = marker.find(a => a.severity === MarkerSeverity.Error)?.severity ?? MarkerSeverity.Warning;
				this._markerInfo = { topSev, count: marker.length };
			}
		} else {
			// a markdown cell can inherit markers from its children
			let topChild: MarkerSeverity | undefined;
			for (const child of this.children) {
				child.updateMarkers(markerService);
				if (child.markerInfo) {
					topChild = !topChild ? child.markerInfo.topSev : Math.max(child.markerInfo.topSev, topChild);
				}
			}
			this._markerInfo = topChild && { topSev: topChild, count: 0 };
		}
	}

	clearMarkers(): void {
		this._markerInfo = undefined;
		for (const child of this.children) {
			child.clearMarkers();
		}
	}

	find(cell: ICellViewModel, parents: OutlineEntry[]): OutlineEntry | undefined {
		if (cell.id === this.cell.id) {
			return this;
		}
		parents.push(this);
		for (const child of this.children) {
			const result = child.find(cell, parents);
			if (result) {
				return result;
			}
		}
		parents.pop();
		return undefined;
	}

	asFlatList(bucket: OutlineEntry[]): void {
		bucket.push(this);
		for (const child of this.children) {
			child.asFlatList(bucket);
		}
	}
}

class NotebookOutlineTemplate {

	static readonly templateId = 'NotebookOutlineRenderer';

	constructor(
		readonly container: HTMLElement,
		readonly iconClass: HTMLElement,
		readonly iconLabel: IconLabel,
		readonly decoration: HTMLElement
	) { }
}

class NotebookOutlineRenderer implements ITreeRenderer<OutlineEntry, FuzzyScore, NotebookOutlineTemplate> {

	templateId: string = NotebookOutlineTemplate.templateId;

	constructor(
		@IThemeService private readonly _themeService: IThemeService,
		@IConfigurationService private readonly _configurationService: IConfigurationService,
	) { }

	renderTemplate(container: HTMLElement): NotebookOutlineTemplate {
		container.classList.add('notebook-outline-element', 'show-file-icons');
		const iconClass = document.createElement('div');
		container.append(iconClass);
		const iconLabel = new IconLabel(container, { supportHighlights: true });
		const decoration = document.createElement('div');
		decoration.className = 'element-decoration';
		container.append(decoration);
		return new NotebookOutlineTemplate(container, iconClass, iconLabel, decoration);
	}

	renderElement(node: ITreeNode<OutlineEntry, FuzzyScore>, _index: number, template: NotebookOutlineTemplate, _height: number | undefined): void {
		const options: IIconLabelValueOptions = {
			matches: createMatches(node.filterData),
			labelEscapeNewLines: true,
			extraClasses: []
		};

		if (node.element.cell.cellKind === CellKind.Code && this._themeService.getFileIconTheme().hasFileIcons && !node.element.isExecuting) {
			template.iconClass.className = '';
			options.extraClasses?.push(...getIconClassesForLanguageId(node.element.cell.language ?? ''));
		} else {
			template.iconClass.className = 'element-icon ' + ThemeIcon.asClassNameArray(node.element.icon).join(' ');
		}

		template.iconLabel.setLabel(node.element.label, undefined, options);

		const { markerInfo } = node.element;

		template.container.style.removeProperty('--outline-element-color');
		template.decoration.innerText = '';
		if (markerInfo) {
			const useBadges = this._configurationService.getValue(OutlineConfigKeys.problemsBadges);
			if (!useBadges) {
				template.decoration.classList.remove('bubble');
				template.decoration.innerText = '';
			} else if (markerInfo.count === 0) {
				template.decoration.classList.add('bubble');
				template.decoration.innerText = '\uea71';
			} else {
				template.decoration.classList.remove('bubble');
				template.decoration.innerText = markerInfo.count > 9 ? '9+' : String(markerInfo.count);
			}
			const color = this._themeService.getColorTheme().getColor(markerInfo.topSev === MarkerSeverity.Error ? listErrorForeground : listWarningForeground);
			const useColors = this._configurationService.getValue(OutlineConfigKeys.problemsColors);
			if (!useColors) {
				template.container.style.removeProperty('--outline-element-color');
				template.decoration.style.setProperty('--outline-element-color', color?.toString() ?? 'inherit');
			} else {
				template.container.style.setProperty('--outline-element-color', color?.toString() ?? 'inherit');
			}
		}
	}

	disposeTemplate(templateData: NotebookOutlineTemplate): void {
		templateData.iconLabel.dispose();
	}
}

class NotebookOutlineAccessibility implements IListAccessibilityProvider<OutlineEntry> {
	getAriaLabel(element: OutlineEntry): string | null {
		return element.label;
	}
	getWidgetAriaLabel(): string {
		return '';
	}
}

class NotebookNavigationLabelProvider implements IKeyboardNavigationLabelProvider<OutlineEntry> {
	getKeyboardNavigationLabel(element: OutlineEntry): { toString(): string | undefined } | { toString(): string | undefined }[] | undefined {
		return element.label;
	}
}

class NotebookOutlineVirtualDelegate implements IListVirtualDelegate<OutlineEntry> {

	getHeight(_element: OutlineEntry): number {
		return 22;
	}

	getTemplateId(_element: OutlineEntry): string {
		return NotebookOutlineTemplate.templateId;
	}
}

class NotebookQuickPickProvider implements IQuickPickDataSource<OutlineEntry> {

	constructor(
		private _getEntries: () => OutlineEntry[],
		@IThemeService private readonly _themeService: IThemeService
	) { }

	getQuickPickElements(): IQuickPickOutlineElement<OutlineEntry>[] {
		const bucket: OutlineEntry[] = [];
		for (const entry of this._getEntries()) {
			entry.asFlatList(bucket);
		}
		const result: IQuickPickOutlineElement<OutlineEntry>[] = [];
		const { hasFileIcons } = this._themeService.getFileIconTheme();
		for (const element of bucket) {
			// todo@jrieken it is fishy that codicons cannot be used with iconClasses
			// but file icons can...
			result.push({
				element,
				label: hasFileIcons ? element.label : `$(${element.icon.id}) ${element.label}`,
				ariaLabel: element.label,
				iconClasses: hasFileIcons ? getIconClassesForLanguageId(element.cell.language ?? '') : undefined,
			});
		}
		return result;
	}
}

class NotebookComparator implements IOutlineComparator<OutlineEntry> {

	private readonly _collator = new IdleValue<Intl.Collator>(() => new Intl.Collator(undefined, { numeric: true }));

	compareByPosition(a: OutlineEntry, b: OutlineEntry): number {
		return a.index - b.index;
	}
	compareByType(a: OutlineEntry, b: OutlineEntry): number {
		return a.cell.cellKind - b.cell.cellKind || this._collator.value.compare(a.label, b.label);
	}
	compareByName(a: OutlineEntry, b: OutlineEntry): number {
		return this._collator.value.compare(a.label, b.label);
	}
}

export class NotebookCellOutline extends Disposable implements IOutline<OutlineEntry> {

	private readonly _onDidChange = this._register(new Emitter<OutlineChangeEvent>());

	readonly onDidChange: Event<OutlineChangeEvent> = this._onDidChange.event;

	private _uri: URI | undefined;
	private _entries: OutlineEntry[] = [];
	private _activeEntry?: OutlineEntry;
	private readonly _entriesDisposables = this._register(new DisposableStore());

	readonly config: IOutlineListConfig<OutlineEntry>;
	readonly outlineKind = 'notebookCells';

	get activeElement(): OutlineEntry | undefined {
		return this._activeEntry;
	}

	constructor(
		private readonly _editor: NotebookEditor,
		private readonly _target: OutlineTarget,
		@IInstantiationService instantiationService: IInstantiationService,
		@IThemeService themeService: IThemeService,
		@IEditorService private readonly _editorService: IEditorService,
		@IMarkerService private readonly _markerService: IMarkerService,
		@IConfigurationService private readonly _configurationService: IConfigurationService,
		@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,
	) {
		super();
		const selectionListener = this._register(new MutableDisposable());
		const installSelectionListener = () => {
			const notebookEditor = _editor.getControl();
			if (!notebookEditor?.hasModel()) {
				selectionListener.clear();
			} else {
				selectionListener.value = combinedDisposable(
					notebookEditor.onDidChangeSelection(() => this._recomputeActive()),
					notebookEditor.onDidChangeViewCells(() => this._recomputeState())
				);
			}
		};

		this._register(_editor.onDidChangeModel(() => {
			this._recomputeState();
			installSelectionListener();
		}));

		this._register(_configurationService.onDidChangeConfiguration(e => {
			if (e.affectsConfiguration('notebook.outline.showCodeCells')) {
				this._recomputeState();
			}
		}));

		this._register(themeService.onDidFileIconThemeChange(() => {
			this._onDidChange.fire({});
		}));

		this._register(_notebookExecutionStateService.onDidChangeCellExecution(e => {
			if (!!this._editor.textModel && e.affectsNotebook(this._editor.textModel?.uri)) {
				this._recomputeState();
			}
		}));

		this._recomputeState();
		installSelectionListener();

		const options: IWorkbenchDataTreeOptions<OutlineEntry, FuzzyScore> = {
			collapseByDefault: _target === OutlineTarget.Breadcrumbs,
			expandOnlyOnTwistieClick: true,
			multipleSelectionSupport: false,
			accessibilityProvider: new NotebookOutlineAccessibility(),
			identityProvider: { getId: element => element.cell.id },
			keyboardNavigationLabelProvider: new NotebookNavigationLabelProvider()
		};

		const treeDataSource: IDataSource<this, OutlineEntry> = { getChildren: parent => parent instanceof NotebookCellOutline ? this._entries : parent.children };
		const delegate = new NotebookOutlineVirtualDelegate();
		const renderers = [instantiationService.createInstance(NotebookOutlineRenderer)];
		const comparator = new NotebookComparator();

		this.config = {
			breadcrumbsDataSource: {
				getBreadcrumbElements: () => {
					const result: OutlineEntry[] = [];
					let candidate = this._activeEntry;
					while (candidate) {
						result.unshift(candidate);
						candidate = candidate.parent;
					}
					return result;
				}
			},
			quickPickDataSource: instantiationService.createInstance(NotebookQuickPickProvider, () => this._entries),
			treeDataSource,
			delegate,
			renderers,
			comparator,
			options
		};
	}

	private _recomputeState(): void {
		this._entriesDisposables.clear();
		this._activeEntry = undefined;
		this._entries.length = 0;
		this._uri = undefined;

		const notebookEditorControl = this._editor.getControl();

		if (!notebookEditorControl) {
			return;
		}

		if (!notebookEditorControl.hasModel()) {
			return;
		}

		this._uri = notebookEditorControl.textModel.uri;

		const notebookEditorWidget: IActiveNotebookEditor = notebookEditorControl;

		if (notebookEditorWidget.getLength() === 0) {
			return;
		}

		let includeCodeCells = true;
		if (this._target === OutlineTarget.OutlinePane) {
			includeCodeCells = this._configurationService.getValue<boolean>('notebook.outline.showCodeCells');
		} else if (this._target === OutlineTarget.Breadcrumbs) {
			includeCodeCells = this._configurationService.getValue<boolean>('notebook.breadcrumbs.showCodeCells');
		}

		const focusedCellIndex = notebookEditorWidget.getFocus().start;
		const focused = notebookEditorWidget.cellAt(focusedCellIndex)?.handle;
		const entries: OutlineEntry[] = [];

		for (let i = 0; i < notebookEditorWidget.getLength(); i++) {
			const cell = notebookEditorWidget.cellAt(i);
			const isMarkdown = cell.cellKind === CellKind.Markup;
			if (!isMarkdown && !includeCodeCells) {
				continue;
			}

			// cap the amount of characters that we look at and use the following logic
			// - for MD prefer headings (each header is an entry)
			// - otherwise use the first none-empty line of the cell (MD or code)
			let content = this._getCellFirstNonEmptyLine(cell);
			let hasHeader = false;

			if (isMarkdown) {
				const fullContent = cell.getText().substring(0, 10_000);
				for (const token of marked.lexer(fullContent, { gfm: true })) {
					if (token.type === 'heading') {
						hasHeader = true;
						entries.push(new OutlineEntry(entries.length, token.depth, cell, renderMarkdownAsPlaintext({ value: token.text }).trim(), false, false));
					}
				}
				if (!hasHeader) {
					content = renderMarkdownAsPlaintext({ value: content });
				}
			}

			if (!hasHeader) {
				let preview = content.trim();
				if (preview.length === 0) {
					// empty or just whitespace
					preview = localize('empty', "empty cell");
				}

				const exeState = !isMarkdown && this._notebookExecutionStateService.getCellExecution(cell.uri);
				entries.push(new OutlineEntry(entries.length, 7, cell, preview, !!exeState, exeState ? exeState.isPaused : false));
			}

			if (cell.handle === focused) {
				this._activeEntry = entries[entries.length - 1];
			}

			// send an event whenever any of the cells change
			this._entriesDisposables.add(cell.model.onDidChangeContent(() => {
				this._recomputeState();
				this._onDidChange.fire({});
			}));
		}

		// build a tree from the list of entries
		if (entries.length > 0) {
			const result: OutlineEntry[] = [entries[0]];
			const parentStack: OutlineEntry[] = [entries[0]];

			for (let i = 1; i < entries.length; i++) {
				const entry = entries[i];

				while (true) {
					const len = parentStack.length;
					if (len === 0) {
						// root node
						result.push(entry);
						parentStack.push(entry);
						break;

					} else {
						const parentCandidate = parentStack[len - 1];
						if (parentCandidate.level < entry.level) {
							parentCandidate.addChild(entry);
							parentStack.push(entry);
							break;
						} else {
							parentStack.pop();
						}
					}
				}
			}
			this._entries = result;
		}

		// feature: show markers with each cell
		const markerServiceListener = new MutableDisposable();
		this._entriesDisposables.add(markerServiceListener);
		const updateMarkerUpdater = () => {
			const doUpdateMarker = (clear: boolean) => {
				for (const entry of this._entries) {
					if (clear) {
						entry.clearMarkers();
					} else {
						entry.updateMarkers(this._markerService);
					}
				}
			};
			if (this._configurationService.getValue(OutlineConfigKeys.problemsEnabled)) {
				markerServiceListener.value = this._markerService.onMarkerChanged(e => {
					if (e.some(uri => notebookEditorWidget.getCellsInRange().some(cell => isEqual(cell.uri, uri)))) {
						doUpdateMarker(false);
						this._onDidChange.fire({});
					}
				});
				doUpdateMarker(false);
			} else {
				markerServiceListener.clear();
				doUpdateMarker(true);
			}
		};
		updateMarkerUpdater();
		this._entriesDisposables.add(this._configurationService.onDidChangeConfiguration(e => {
			if (e.affectsConfiguration(OutlineConfigKeys.problemsEnabled)) {
				updateMarkerUpdater();
				this._onDidChange.fire({});
			}
		}));

		this._onDidChange.fire({});
	}

	private _recomputeActive(): void {
		let newActive: OutlineEntry | undefined;
		const notebookEditorWidget = this._editor.getControl();

		if (notebookEditorWidget) {
			if (notebookEditorWidget.hasModel() && notebookEditorWidget.getLength() > 0) {
				const cell = notebookEditorWidget.cellAt(notebookEditorWidget.getFocus().start);
				if (cell) {
					for (const entry of this._entries) {
						newActive = entry.find(cell, []);
						if (newActive) {
							break;
						}
					}
				}
			}
		}
		if (newActive !== this._activeEntry) {
			this._activeEntry = newActive;
			this._onDidChange.fire({ affectOnlyActiveElement: true });
		}
	}

	private _getCellFirstNonEmptyLine(cell: ICellViewModel) {
		const textBuffer = cell.textBuffer;
		for (let i = 0; i < textBuffer.getLineCount(); i++) {
			const firstNonWhitespace = textBuffer.getLineFirstNonWhitespaceColumn(i + 1);
			const lineLength = textBuffer.getLineLength(i + 1);
			if (firstNonWhitespace < lineLength) {
				return textBuffer.getLineContent(i + 1);
			}
		}

		return cell.getText().substring(0, 10_000);
	}

	get isEmpty(): boolean {
		return this._entries.length === 0;
	}

	get uri() {
		return this._uri;
	}

	async reveal(entry: OutlineEntry, options: IEditorOptions, sideBySide: boolean): Promise<void> {
		await this._editorService.openEditor({
			resource: entry.cell.uri,
			options: {
				...options,
				override: this._editor.input?.editorId,
				cellRevealType: CellRevealType.NearTopIfOutsideViewport
			} as INotebookEditorOptions,
		}, sideBySide ? SIDE_GROUP : undefined);
	}

	preview(entry: OutlineEntry): IDisposable {
		const widget = this._editor.getControl();
		if (!widget) {
			return Disposable.None;
		}
		widget.revealInCenterIfOutsideViewport(entry.cell);
		const ids = widget.deltaCellDecorations([], [{
			handle: entry.cell.handle,
			options: { className: 'nb-symbolHighlight', outputClassName: 'nb-symbolHighlight' }
		}]);
		return toDisposable(() => { widget.deltaCellDecorations(ids, []); });

	}

	captureViewState(): IDisposable {
		const widget = this._editor.getControl();
		const viewState = widget?.getEditorViewState();
		return toDisposable(() => {
			if (viewState) {
				widget?.restoreListViewState(viewState);
			}
		});
	}
}

class NotebookOutlineCreator implements IOutlineCreator<NotebookEditor, OutlineEntry> {

	readonly dispose: () => void;

	constructor(
		@IOutlineService outlineService: IOutlineService,
		@IInstantiationService private readonly _instantiationService: IInstantiationService,
	) {
		const reg = outlineService.registerOutlineCreator(this);
		this.dispose = () => reg.dispose();
	}

	matches(candidate: IEditorPane): candidate is NotebookEditor {
		return candidate.getId() === NotebookEditor.ID;
	}

	async createOutline(editor: NotebookEditor, target: OutlineTarget): Promise<IOutline<OutlineEntry> | undefined> {
		return this._instantiationService.createInstance(NotebookCellOutline, editor, target);
	}
}

Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(NotebookOutlineCreator, LifecyclePhase.Eventually);

Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
	id: 'notebook',
	order: 100,
	type: 'object',
	'properties': {
		'notebook.outline.showCodeCells': {
			type: 'boolean',
			default: false,
			markdownDescription: localize('outline.showCodeCells', "When enabled notebook outline shows code cells.")
		},
		'notebook.breadcrumbs.showCodeCells': {
			type: 'boolean',
			default: true,
			markdownDescription: localize('breadcrumbs.showCodeCells', "When enabled notebook breadcrumbs contain code cells.")
		},
	}
});


text:
require 'spec_helper'

describe GmoPayment::Client::Request do
  before { GmoPayment.reset! }
  subject { GmoPayment::Client::Request.new(:entry_tran, args) }

  describe '#called_method' do
    let(:args) { {} }
    it { expect(subject.called_method).to eq(:entry_tran) }
  end

  describe '#missing_items' do
    let(:args) { {} }
    it { expect(subject.missing_items).to be_a(Array) }
  end

  describe '#missing?' do
    context 'with missing items' do
      let(:args) { {} }
      it { expect(subject.missing?).to be(true) }
    end
    context 'with full items' do
      let(:args) do
        [:shop_id, :shop_pass, :order_id, :job_cd].each_with_object({}) do |item, hash|
          item == :job_cd ? hash[item] = 'CHECK' : hash[item] = 'x'
        end
      end
      it { expect(subject.missing?).to be(false) }
    end
  end

  describe '#invalid_items' do
    subject { GmoPayment::Client::Request.new(method, args).invalid_items }
    let(:method) { :entry_tran }
    let(:args) { {} }
    it { is_expected.to be_a(Hash) }
    [:entry_tran, :re_exec_tran, :change_tran].each do |called_method|
      context "with called_method is #{called_method}" do
        let(:method) { called_method }
        context 'with amount + tax <= 9,999,999' do
          let(:args) { { amount: 9_999_998, tax: 1 } }
          it { is_expected.not_to including(:amount) }
          it { is_expected.not_to including(:tax) }
        end
        context 'with amount + tax > 9,999,999' do
          let(:args) { { amount: 9_999_999, tax: 1 } }
          it { is_expected.to including(:amount) }
          it { is_expected.to including(:tax) }
        end
      end
    end
    context 'with called_method is #entry_tran_btc' do
      let(:method) { :entry_tran_btc }
      context 'with amount + tax <= 300,000' do
        let(:args) { { amount: 299_999, tax: 1 } }
        it { is_expected.not_to including(:amount) }
        it { is_expected.not_to including(:tax) }
      end
      context 'with amount + tax > 300,000' do
        let(:args) { { amount: 300_000, tax: 1 } }
        it { is_expected.to including(:amount) }
        it { is_expected.to including(:tax) }
      end
    end
  end

  describe '#invalid?' do
    context 'with invalid items' do
      let(:args) { { shop_id: 'x' * 14 } }
      it { expect(subject.invalid?).to be(true) }
    end
    context 'with all valid items' do
      let(:args) { { shop_id: 'x' * 13 } }
      it { expect(subject.invalid?).to be(false) }
    end
  end

  describe '#body' do
    let(:args) do
      [:shop_id, :shop_pass, :order_id, :job_cd].each_with_object({}) do |item, hash|
        item == :job_cd ? hash[item] = 'CHECK' : hash[item] = 'x'
      end
    end
    it { expect(subject.body).to be_a(String) }
    it { expect(subject.body).to match('ShopID=x') }
    it { expect(subject.body).to match('ShopPass=x') }
    it { expect(subject.body).to match('OrderID=x') }
    it { expect(subject.body).to match('JobCd=CHECK') }
    it 'convert invalid items (like Japanese) to application/x-www-form-urlencoded' do
      args = { client_field_1: '日本語' }
      expect(GmoPayment::Client::Request.new(:exec_tran, args)).not_to match('日本語')
    end
  end
end

describe GmoPayment::Client::Request do
  describe 'validation' do
    subject do
      request = GmoPayment::Client::Request.new(method, {})
      request.__send__('validate_valid?', key, value)
    end
    let(:method) { nil }

    describe ':access_id, :access_pass' do
      items = [:access_id, :access_pass]
      it_behaves_like 'validation of length <= n',
        items, 'x', 32
    end

    describe ':amount, :tax' do
      items = [:amount, :tax]
      it_behaves_like 'validation of number',
        items, 7
      it_behaves_like 'validation of length <= n',
        items, '1', 7
    end

    describe ':card_name' do
      items = [:card_name]
      it_behaves_like 'validation of length <= n',
        items, 'x', 10
    end

    describe ':card_no' do
      items = [:card_no]
      it_behaves_like 'validation of number',
        items, 10
      it_behaves_like 'validation of length >= n',
        items, '1', 10
      it_behaves_like 'validation of length <= n',
        items, '1', 16
    end

    describe ':card_pass' do
      items = [:card_pass]
      let(:key) { items.first }
      context 'with a-zA-Z0-9' do
        let(:value) { 'xX9' }
        it { is_expected.to be(true) }
      end
      context 'with not a-zA-Z0-9' do
        let(:value) { '!' }
        it { is_expected.to be(false) }
      end
      it_behaves_like 'validation of length <= n',
        items, 'x', 20
    end

    describe ':card_seq' do
      items = [:card_seq]
      it_behaves_like 'validation of number',
        items, 4
      it_behaves_like 'validation of length <= n',
        items, '1', 4
    end

    describe ':client_field_1, :client_field_2, :client_field_3' do
      items = [:client_field_1, :client_field_2, :client_field_3]
      context 'with not {}|^`~&<>"\'' do
        let(:value) { 'xX 9!' }
        items.each do |key|
          let(:key) { key }
          it { is_expected.to be(true) }
        end
      end
      context 'with {}|^`~&<>"\'' do
        let(:value) { %w({ } | ^ ` ~ & < > " ').sample }
        items.each do |key|
          let(:key) { key }
          it { is_expected.to be(false) }
        end
      end
      it_behaves_like 'validation of length <= n',
        items, 'x', 100
    end

    describe ':client_field_flag, :default_flag, :device_category, :seq_mode, :td_flag' do
      items = [:client_field_flag, :default_flag, :device_category, :seq_mode, :td_flag]
      it_behaves_like 'validation of value including',
        items, ['0', '1']
    end

    describe ':expire' do
      items = [:expire]
      it_behaves_like 'validation of number',
        items, 4
      let(:key) { items.first }
      context 'with length == 4' do
        let(:value) { '1' * 4 }
        it { is_expected.to be(true) }
      end
      context 'with length != 4' do
        let(:value) { '1' * [3, 5].sample }
        it { is_expected.to be(false) }
      end
    end

    describe ':holder_name' do
      items = [:holder_name]
      let(:key) { items.first }
      context 'with a-zA-Z0-9 and space' do
        let(:value) { 'xX 9' }
        it { is_expected.to be(true) }
      end
      context 'with not a-zA-Z0-9 and space' do
        let(:value) { '!' }
        it { is_expected.to be(false) }
      end
      it_behaves_like 'validation of length <= n',
        items, 'x', 50
    end

    describe ':item_code' do
      items = [:item_code]
      it_behaves_like 'validation of number',
        items, 7
      let(:key) { items.first }
      context 'with length == 7' do
        let(:value) { '1' * 7 }
        it { is_expected.to be(true) }
      end
      context 'with length != 7' do
        let(:value) { '1' * [6, 8].sample }
        it { is_expected.to be(false) }
      end
    end

    describe ':item_memo' do
      items = [:item_memo]
      it_behaves_like 'validation of length <= n',
        items, 'x', 128
    end

    describe ':item_name' do
      items = [:item_name]
      it_behaves_like 'validation of length <= n',
        items, 'x', 64
    end

    describe ':job_cd' do
      items = [:job_cd]
      context 'with Client#entry_tran' do
        let(:method) { :entry_tran }
        it_behaves_like 'validation of value including',
          items, ['CHECK', 'CAPTURE', 'AUTH', 'SAUTH']
      end
      context 'with Client#delete_tran' do
        let(:method) { :delete_tran }
        it_behaves_like 'validation of value including',
          items, ['VOID', 'RETURN', 'RETURNX']
      end
      context 'with Client#re_exec_tran' do
        let(:method) { :re_exec_tran }
        it_behaves_like 'validation of value including',
          items, ['CAPTURE', 'AUTH']
      end
      context 'with Client#change_tran' do
        let(:method) { :change_tran }
        it_behaves_like 'validation of value including',
          items, ['CAPTURE', 'AUTH', 'SAUTH']
      end
      context 'with Client#auth_to_sales or the other case' do
        let(:key) { items.first }
        let(:value) { 'SALES' }
        it { is_expected.to be(true) }
      end
    end

    describe ':member_id' do
      items = [:member_id]
      let(:key) { items.first }
      context 'with a-zA-Z0-9 _ - . @' do
        let(:value) { 'xX9_-.@' }
        it { is_expected.to be(true) }
      end
      context 'with not \w - . @' do
        let(:value) { '!' }
        it { is_expected.to be(false) }
      end
      it_behaves_like 'validation of length <= n',
        items, 'x', 60
    end

    describe ':member_name' do
      items = [:member_name]
      let(:key) { items.first }
      context 'with not {}|^`~&<>"\'' do
        let(:value) { 'xX9!' }
        it { is_expected.to be(true) }
      end
      context 'with {}|^`~&<>"\'' do
        let(:value) { %w({ } | ^ ` ~ & < > " ').sample }
        it { is_expected.to be(false) }
      end
      it_behaves_like 'validation of length <= n',
        items, 'x', 255
    end

    describe ':method' do
      items = [:method]
      it_behaves_like 'validation of value including',
        items, ['1', '2', '3', '4', '5']
    end

    describe ':order_id' do
      items = [:order_id]
      let(:key) { items.first }
      context 'with a-zA-Z0-9 and -' do
        let(:value) { 'xX-9' }
        it { is_expected.to be(true) }
      end
      context 'with not a-zA-Z0-9 and -' do
        let(:value) { '!' }
        it { is_expected.to be(false) }
      end
      it_behaves_like 'validation of length <= n',
        items, 'x', 27
    end

    describe ':pay_times' do
      items = [:pay_times]
      it_behaves_like 'validation of number',
        items, 2
      it_behaves_like 'validation of length <= n',
        items, '1', 2
    end

    describe ':pin' do
      items = [:pin]
      it_behaves_like 'validation of length <= n',
        items, 'x', 4
    end

    describe ':ret_url' do
      items = [:ret_url]
      it_behaves_like 'validation of length <= n',
        items, 'x', 256
    end

    describe ':security_code' do
      items = [:security_code]
      it_behaves_like 'validation of number',
        items, 3
      let(:key) { items.first }
      context 'with length 3 or 4' do
        [3, 4].each do |length|
          let(:value) { '1' * length }
          it { is_expected.to be(true) }
        end
      end
      context 'with not length 3 or 4' do
        [2, 5].each do |length|
          let(:value) { '1' * length }
          it { is_expected.to be(false) }
        end
      end
    end

    describe ':shop_id, :site_id' do
      items = [:shop_id, :site_id]
      it_behaves_like 'validation of length <= n',
        items, 'x', 13
    end

    describe ':shop_pass' do
      items = [:shop_pass]
      it_behaves_like 'validation of length <= n',
        items, 'x', 10
    end

    describe ':site_pass' do
      items = [:site_pass]
      it_behaves_like 'validation of length <= n',
        items, 'x', 20
    end

    describe ':td_tenant_name' do
      items = [:td_tenant_name]
      it_behaves_like 'validation of length <= n',
        items, '日', 9
    end

    describe ':timeout' do
      items = [:timeout]
      let(:key) { items.first }
      context 'with under 24 hours' do
        let(:value) { "#{24 * 60 * 60}" }
        it { is_expected.to be(true) }
      end
      context 'with over 24 hours' do
        let(:value) { "#{24 * 60 * 60 + 1}" }
        it { is_expected.to be(false) }
      end
    end

    describe 'the other cases' do
      let(:key) { :acs }
      let(:value) { 'x' }
      it { is_expected.to be(true) }
    end
  end
end


text:
# array_flatten

**Flatten an array, either keeping or discarding content of child arrays.** [View source](https://github.com/Eiskis/Baseline-PHP/blob/master/source/arrays/array_flatten.php)

	function array_flatten (array $array, $removeChildren = false, $preserveKeys = false)

This funtion returns the input `$array` with no child arrays. By default, all keys are discarded (the new returned array will have new indexes) and non-array calues in any child arrays are included on the same level as their parents.

When `$removeChildren` is set to `true`, all child arrays are removed. When `$preserveKeys` is set to `true`, keys in `$array` as well as any child arrays are preserved. Enabling both is a safe way of removing child arrays without losing associations.

**Note!** When preserving keys, it's possible that some values are lost. Some child arrays might include values with the same keys as their children.

## Examples

### Basics

##### Flatten a multi-dimensional array
	array_flatten(array(
		1,
		2,
		array(
			'a',
			'b'
		)
	))
	// Returns array(1, 2, 'a', 'b')

##### Empty child arrays are discarded
	array_flatten(array('value', array()))
	// Returns array('value')

##### Keys are ditched by default
	array_flatten(array(
		'a' => 'val 1',
		'b' => 'val 2',
		'c' => 'val 3'
	))
	/* Returns
	array(
		0 => 'val 1',
		1 => 'val 2',
		2 => 'val 3'
	)
	*/


text:
package org.jetbrains.plugins.scala.failed.annotator

import org.jetbrains.plugins.scala.PerfCycleTests
import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter
import org.junit.experimental.categories.Category

/**
  * User: Dmitry.Naydanov
  * Date: 27.03.16.
  */
@Category(Array(classOf[PerfCycleTests]))
class AlreadyDefinedTest extends ScalaLightCodeInsightFixtureTestAdapter {
  override protected def shouldPass: Boolean = false

  def testSCL2101(): Unit =
    checkTextHasNoErrors(
      """
        |class Some(name: Int) {
        |    def name {""}
        |}
      """.stripMargin)

  def testSCL5789(): Unit =
    checkTextHasNoErrors(
      """
        |class Test {
        |  private[this] val x = 1
        |  def x() = 2
        |}
      """.stripMargin)
}


text:
package com.auth0.lock;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.WindowManager;

import com.auth0.api.callback.AuthenticationCallback;
import com.auth0.api.callback.BaseCallback;
import com.auth0.core.Application;
import com.auth0.core.Token;
import com.auth0.core.UserProfile;
import com.auth0.identity.IdentityProvider;
import com.auth0.identity.IdentityProviderCallback;
import com.auth0.lock.error.ErrorDialogBuilder;
import com.auth0.lock.error.LoginAuthenticationErrorBuilder;
import com.auth0.lock.event.AuthenticationError;
import com.auth0.lock.event.AuthenticationEvent;
import com.auth0.lock.event.ChangePasswordEvent;
import com.auth0.lock.event.EnterpriseAuthenticationRequest;
import com.auth0.lock.event.IdentityProviderAuthenticationEvent;
import com.auth0.lock.event.IdentityProviderAuthenticationRequestEvent;
import com.auth0.lock.event.NavigationEvent;
import com.auth0.lock.event.SignUpEvent;
import com.auth0.lock.event.SocialCredentialEvent;
import com.auth0.lock.event.SystemErrorEvent;
import com.auth0.lock.fragment.LoadingFragment;
import com.auth0.lock.identity.LockIdentityProviderCallback;
import com.auth0.lock.util.ActivityUIHelper;
import com.auth0.lock.util.LockFragmentBuilder;
import com.squareup.otto.Subscribe;

/**
 * Activity that handles DB, Social and Enterprise Authentication.
 * You'll need to declare it in your app's {@code AndroidManifest.xml}:
 *
{@code
 * <activity
 *      android:name="com.auth0.lock.LockActivity"
 *      android:theme="@style/Lock.Theme"
 *      android:screenOrientation="portrait"
 *      android:launchMode="singleTask">
 *      <intent-filter>
 *          <action android:name="android.intent.action.VIEW"/>
 *          <category android:name="android.intent.category.DEFAULT"/>
 *          <category android:name="android.intent.category.BROWSABLE"/>
 *          <data android:scheme="a0YOUR_CLIENT_ID" android:host="YOUR_AUTH0_APP_DOMAIN"/>
 *      </intent-filter>
 * </activity>
 * }

 *
 * Then just start it like any other Android activity:
 *
{@code
 * Intent lockIntent = new Intent(this, LockActivity.class);
 * startActivity(lockIntent);
 * }
 *

 *
 * And finally register listeners in {@link android.support.v4.content.LocalBroadcastManager} for these actions:
 *

 *
Lock.Authentication: Sent on a successful authentication with {@link com.auth0.core.UserProfile} and {@link com.auth0.core.Token}.
 *     Or both {@code null} when {@link Lock#loginAfterSignUp} is {@code false}

 *
Lock.Cancel: Sent when the user's closes the activity by pressing the back button without authenticating. (Only if {@link Lock#closable} is {@code true}

 *
Lock.ChangePassword: Sent when the user changes the password successfully.

 *

 *
 * All these action names are defined in these constants: {@link Lock#AUTHENTICATION_ACTION}, {@link Lock#CANCEL_ACTION} and {@link com.auth0.lock.Lock#CHANGE_PASSWORD_ACTION}.
 */
public class LockActivity extends FragmentActivity {

    public static final String SIGN_UP_MODE_ARGUMENT = "SIGN_UP_MODE";

    private static final String TAG = LockActivity.class.getName();

    LockFragmentBuilder builder;
    Lock lock;

    private ProgressDialog progressDialog;
    private IdentityProvider identity;
    private LocalBroadcastManager broadcastManager;
    private IdentityProviderCallback callback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.com_auth0_activity_lock);
        lock = getLock();
        builder = newFragmentBuilder(getLock());

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.com_auth0_container, new LoadingFragment())
                    .commit();
        }
        broadcastManager = LocalBroadcastManager.getInstance(this);
        callback = new LockIdentityProviderCallback(lock.getBus());
        ActivityUIHelper.configureScreenModeForActivity(this, lock);
        lock.getBus().register(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        lock.resetAllProviders();
    }

    @Override
    protected void onStop() {
        super.onStop();
        lock.resetAllProviders();
    }

    @Override
    protected void onResume() {
        super.onResume();
        final Uri uri = getIntent().getData();
        Log.v(TAG, "Resuming activity with data " + uri);
        if (identity != null) {
            boolean valid = identity.authorize(this, IdentityProvider.WEBVIEW_AUTH_REQUEST_CODE, RESULT_OK, getIntent());
            if (!valid) {
                dismissProgressDialog();
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        ActivityUIHelper.configureScreenModeForActivity(this, lock);
    }

    @Override
    protected void onPause() {
        super.onPause();
        getIntent().setData(null);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.v(TAG, "Received new Intent with URI " + intent.getData());
        identity = lock.getDefaultProvider();
        setIntent(intent);
    }

    @Override
    protected void onDestroy() {
        identity = null;
        dismissProgressDialog();
        this.lock.getBus().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v(TAG, "Child activity result obtained");
        if (identity != null) {
            identity.authorize(this, requestCode, resultCode, data);
        }
        lock.getCredentialStore().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        final double count = getSupportFragmentManager().getBackStackEntryCount();
        if ((!lock.isClosable() && count >= 1) || lock.isClosable()) {
            if (count == 0) {
                broadcastManager.sendBroadcast(new Intent(Lock.CANCEL_ACTION));
            }
            super.onBackPressed();
        }
    }

    @SuppressWarnings("unused")
    @Subscribe public void onApplicationLoaded(Application application) {
        Log.d(TAG, "Application configuration loaded for id " + application.getId());
        Configuration configuration = new Configuration(application, lock.getConnections(), lock.getDefaultDatabaseConnection());
        lock.setConfiguration(configuration);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.com_auth0_container, builder.root())
                .commit();
    }

    @SuppressWarnings("unused")
    @Subscribe public void onAuthentication(AuthenticationEvent event) {
        UserProfile profile = event.getProfile();
        Token token = event.getToken();
        Log.i(TAG, "Authenticated user " + profile.getName());
        Intent result = new Intent(Lock.AUTHENTICATION_ACTION)
                .putExtra(Lock.AUTHENTICATION_ACTION_PROFILE_PARAMETER, profile)
                .putExtra(Lock.AUTHENTICATION_ACTION_TOKEN_PARAMETER, token);
        LocalBroadcastManager.getInstance(this).sendBroadcast(result);
        dismissProgressDialog();
        finish();
    }

    @SuppressWarnings("unused")
    @Subscribe public void onSignUpEvent(SignUpEvent event) {
        Log.i(TAG, "Signed up user " + event.getUsername());
        broadcastManager.sendBroadcast(new Intent(Lock.AUTHENTICATION_ACTION));
        dismissProgressDialog();
        finish();
    }

    @SuppressWarnings("unused")
    @Subscribe public void onResetPassword(ChangePasswordEvent event) {
        Log.d(TAG, "Changed password");
        ErrorDialogBuilder.showAlertDialog(this, event);
        broadcastManager.sendBroadcast(new Intent(Lock.CHANGE_PASSWORD_ACTION));
        getSupportFragmentManager().popBackStack();
    }

    @SuppressWarnings("unused")
    @Subscribe public void onAuthenticationError(AuthenticationError error) {
        Log.e(TAG, "Failed to authenticate user", error.getThrowable());
        if (identity != null) {
            identity.clearSession();
        }
        dismissProgressDialog();
        ErrorDialogBuilder.showAlertDialog(this, error);
    }

    @SuppressWarnings("unused")
    @Subscribe public void onSystemError(SystemErrorEvent event) {
        Log.e(TAG, "Android System error", event.getError());
        dismissProgressDialog();
        event.getErrorDialog().show();
    }

    @SuppressWarnings("unused")
    @Subscribe public void onNavigationEvent(NavigationEvent event) {
        Log.v(TAG, "About to handle navigation " + event);
        if (NavigationEvent.BACK.equals(event)) {
            getSupportFragmentManager().popBackStack();
            return;
        }

        Fragment fragment = null;
        switch (event) {
            case SIGN_UP:
                fragment = builder.signUp();
                break;
            case RESET_PASSWORD:
                fragment = builder.resetPassword();
                break;
        }
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.com_auth0_container, fragment)
                    .addToBackStack(event.name())
                    .commit();
        }
    }

    @SuppressWarnings("unused")
    @Subscribe public void onEnterpriseAuthenticationRequest(EnterpriseAuthenticationRequest event) {
        Fragment fragment = builder.enterpriseLoginWithConnection(event.getConnection());
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.com_auth0_container, fragment)
                .addToBackStack(event.getConnection().getName())
                .commit();
    }

    @SuppressWarnings("unused")
    @Subscribe public void onIdentityProviderAuthentication(IdentityProviderAuthenticationRequestEvent event) {
        Log.v(TAG, "About to authenticate with service " + event.getServiceName());
        identity = lock.providerForName(event.getServiceName());
        identity.setCallback(callback);
        identity.start(this, event, lock.getConfiguration().getApplication());
        progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @SuppressWarnings("unused")
    @Subscribe public void onSocialAuthentication(IdentityProviderAuthenticationEvent event) {
        final Token token = event.getToken();
        lock.getAuthenticationAPIClient()
                .tokenInfo(token.getIdToken())
                .start(new BaseCallback<UserProfile>() {
                    @Override
                    public void onSuccess(UserProfile userProfile) {
                        lock.getBus().post(new AuthenticationEvent(userProfile, token));
                    }

                    @Override
                    public void onFailure(Throwable error) {
                        lock.getBus().post(new LoginAuthenticationErrorBuilder().buildFrom(error));
                    }
                });
    }

    @SuppressWarnings("unused")
    @Subscribe public void onSocialCredentialEvent(SocialCredentialEvent event) {
        Log.v(TAG, "Received social accessToken " + event.getAccessToken());
        lock.getAuthenticationAPIClient()
                .loginWithOAuthAccessToken(event.getAccessToken(), event.getService())
                .addParameters(lock.getAuthenticationParameters())
                .start(new AuthenticationCallback() {
                    @Override
                    public void onSuccess(UserProfile profile, Token token) {
                        lock.getBus().post(new AuthenticationEvent(profile, token));
                    }

                    @Override
                    public void onFailure(Throwable error) {
                        lock.getBus().post(new LoginAuthenticationErrorBuilder().buildFrom(error));
                    }
                });
    }

    private LockFragmentBuilder newFragmentBuilder(Lock lock) {
        final LockFragmentBuilder builder = new LockFragmentBuilder(lock);
        Intent intent = getIntent();
        if (intent != null) {
            Bundle extras = intent.getExtras();
            builder.setSignUpMode(extras != null && extras.getBoolean(SIGN_UP_MODE_ARGUMENT));
        }
        return builder;
    }

    private void dismissProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        progressDialog = null;
    }

    private Lock getLock() {
        if (lock != null) {
            return lock;
        }
        return Lock.getLock(this);
    }
}


text:
package com.google.cloud.logging;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import java.util.logging.Level;

public class LoggingLevelTest {

  @Test
  public void testDebug() {
    LoggingLevel debug = LoggingLevel.DEBUG;
    assertEquals(Severity.DEBUG, debug.getSeverity());
    assertEquals("DEBUG", debug.getName());
    assertTrue(debug.intValue() < Level.FINEST.intValue());
    assertTrue(debug.intValue() > Level.ALL.intValue());
  }

  @Test
  public void testNotice() {
    LoggingLevel notice = LoggingLevel.NOTICE;
    assertEquals(Severity.NOTICE, notice.getSeverity());
    assertEquals("NOTICE", notice.getName());
    assertTrue(notice.intValue() > Level.INFO.intValue());
    assertTrue(notice.intValue() < Level.WARNING.intValue());
  }

  @Test
  public void testError() {
    LoggingLevel error = LoggingLevel.ERROR;
    assertEquals(Severity.ERROR, error.getSeverity());
    assertEquals("ERROR", error.getName());
    assertTrue(error.intValue() > Level.WARNING.intValue());
    assertTrue(error.intValue() < Level.SEVERE.intValue());
  }

  @Test
  public void testCritical() {
    LoggingLevel critical = LoggingLevel.CRITICAL;
    assertEquals(Severity.CRITICAL, critical.getSeverity());
    assertEquals("CRITICAL", critical.getName());
    assertTrue(critical.intValue() > LoggingLevel.SEVERE.intValue());
    assertTrue(critical.intValue() < Level.OFF.intValue());
  }

  @Test
  public void testAlert() {
    LoggingLevel alert = LoggingLevel.ALERT;
    assertEquals(Severity.ALERT, alert.getSeverity());
    assertEquals("ALERT", alert.getName());
    assertTrue(alert.intValue() > LoggingLevel.CRITICAL.intValue());
    assertTrue(alert.intValue() < Level.OFF.intValue());
  }

  @Test
  public void testEmergency() {
    LoggingLevel emergency = LoggingLevel.EMERGENCY;
    assertEquals(Severity.EMERGENCY, emergency.getSeverity());
    assertEquals("EMERGENCY", emergency.getName());
    assertTrue(emergency.intValue() > LoggingLevel.ALERT.intValue());
    assertTrue(emergency.intValue() < Level.OFF.intValue());
  }
}


text:
require File.expand_path('../integration', __FILE__)

module Adapters
  class NetHttpPersistentTest < Faraday::TestCase

    def adapter() :net_http_persistent end

    Integration.apply(self, :NonParallel) do
      def setup
        if defined?(Net::HTTP::Persistent)
          # work around problems with mixed SSL certificates
          # https://github.com/drbrain/net-http-persistent/issues/45
          if Net::HTTP::Persistent.instance_method(:initialize).parameters.first == [:key, :name]
            Net::HTTP::Persistent.new(name: 'Faraday').reconnect_ssl
          else
            Net::HTTP::Persistent.new('Faraday').ssl_cleanup(4)
          end
        end
      end if ssl_mode?
    end

    def test_custom_adapter_config
      url = URI('https://example.com:1234')

      adapter = Faraday::Adapter::NetHttpPersistent.new do |http|
        http.idle_timeout = 123
      end

      http = adapter.net_http_connection(:url => url, :request => {})
      adapter.configure_request(http, {})

      assert_equal 123, http.idle_timeout
    end
  end
end


text:
module ShowHelper
end


text:
'use strict';

var blacklist = [
    'freelist',
    'sys'
];

module.exports = Object.keys(process.binding('natives')).filter(function (el) {
    return !/^_|^internal|\//.test(el) && blacklist.indexOf(el) === -1;
}).sort();


text:
package com.bluelinelabs.conductor.demo.controllers;

import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bluelinelabs.conductor.Controller;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.demo.R;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.support.RouterPagerAdapter;

import java.util.Locale;

import butterknife.BindView;

public class PagerController extends BaseController {

    private int[] PAGE_COLORS = new int[]{R.color.green_300, R.color.cyan_300, R.color.deep_purple_300, R.color.lime_300, R.color.red_300};

    @BindView(R.id.tab_layout) TabLayout tabLayout;
    @BindView(R.id.view_pager) ViewPager viewPager;

    private final RouterPagerAdapter pagerAdapter;

    public PagerController() {
        pagerAdapter = new RouterPagerAdapter(this) {
            @Override
            public void configureRouter(@NonNull Router router, int position) {
                if (!router.hasRootController()) {
                    Controller page = new ChildController(String.format(Locale.getDefault(), "Child #%d (Swipe to see more)", position), PAGE_COLORS[position], true);
                    router.setRoot(RouterTransaction.with(page));
                }
            }

            @Override
            public int getCount() {
                return PAGE_COLORS.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return "Page " + position;
            }
        };
    }

    @NonNull
    @Override
    protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
        return inflater.inflate(R.layout.controller_pager, container, false);
    }

    @Override
    protected void onViewBound(@NonNull View view) {
        super.onViewBound(view);
        viewPager.setAdapter(pagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    protected void onDestroyView(@NonNull View view) {
        if (!getActivity().isChangingConfigurations()) {
            viewPager.setAdapter(null);
        }
        tabLayout.setupWithViewPager(null);
        super.onDestroyView(view);
    }

    @Override
    protected String getTitle() {
        return "ViewPager Demo";
    }

}