text:
require 'spec_helper'

describe BnetScraper::Starcraft2::Profile do
  let(:url) { 'http://us.battle.net/sc2/en/profile/2377239/1/Demon/' }
  let(:profile) { BnetScraper::Starcraft2::Profile.new url: url  }
  subject { profile }

  its(:swarm_levels) { should be_instance_of Hash }
  its(:swarm_levels) { should have_key :zerg }
  its(:swarm_levels) { should have_key :protoss }
  its(:swarm_levels) { should have_key :terran }

  it 'retrieves achievements when first accessed' do
    VCR.use_cassette('demon_achievements') do
      profile.achievements.should have_key(:recent)
      profile.achievements.should have_key(:showcase)
      profile.achievements.should have_key(:progress)
    end
  end

  it 'sends recent_achievements to achievements hash' do
    VCR.use_cassette('demon_achievements') do
      profile.recent_achievements.should == profile.achievements[:recent]
    end
  end

  it 'sends progress_achievements to achievements hash' do
    VCR.use_cassette('demon_achievements') do
      profile.progress_achievements.should == profile.achievements[:progress]
    end
  end

  it 'sends showcase_achievements to achievements hash' do
    VCR.use_cassette('demon_achievements') do
      profile.showcase_achievements.should == profile.achievements[:showcase]
    end
  end

  it 'retrieves match history when first accessed' do
    VCR.use_cassette('demon_match_history') do
      profile.match_history.should have(25).matches
      profile.match_history.first.should be_instance_of BnetScraper::Starcraft2::Match
    end
  end

  context 'campaign completion' do
    before do
      profile.terran_campaign_completion = :brutal
    end

    it 'accepts a campaign and returns a boolean' do
      profile.completed_campaign(:terran).should be_true
    end

    it 'accepts a campaign and a difficulty' do
      profile.completed_campaign(:terran, :hard).should be_true
    end
  end
end


text:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { InterrogationServicesComponent } from './interrogation-services.component';
import { SharedTestingModule } from '../../../shared/shared.module';
import { TranslateService } from '@ngx-translate/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

describe('InterrogationServicesComponent', () => {
    let component: InterrogationServicesComponent;
    let fixture: ComponentFixture<InterrogationServicesComponent>;
    beforeEach(async () => {
        await TestBed.configureTestingModule({
            imports: [SharedTestingModule],
            declarations: [InterrogationServicesComponent],
            providers: [TranslateService],
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(InterrogationServicesComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

redpajama_set_name: RedPajamaGithub


text:
/** Generated by FG **/
@font-face {
	font-family: 'Conv_Octarine-Light';
	src: url('fonts/Octarine-Light.eot');
	src: local('☺'), url('fonts/Octarine-Light.woff') format('woff'), url('fonts/Octarine-Light.ttf') format('truetype'), url('fonts/Octarine-Light.svg') format('svg');
	font-weight: normal;
	font-style: normal;
}


text:
import sys

sys.path.append("..")
from app.constants import ROLE
from flask_sqlalchemy import SQLAlchemy
from app import app
from db_adapters import SQLAlchemyAdapter

db = SQLAlchemy(app)
db_adapter = SQLAlchemyAdapter(db)

class UserMixin(object):
    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_admin_id(self):
        pass

    def get_id(self):
        return unicode(self.get_admin_id())

    def is_admin(self):
        return self.has_roles(ROLE.ADMIN)


text:
package sh.isaac.api.commit;

import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.stream.Stream;
import org.jvnet.hk2.annotations.Contract;
import javafx.collections.ObservableList;
import javafx.collections.ObservableSet;
import javafx.concurrent.Task;
import sh.isaac.api.DatastoreServices;
import sh.isaac.api.alert.AlertObject;
import sh.isaac.api.chronicle.Chronology;
import sh.isaac.api.chronicle.Version;
import sh.isaac.api.externalizable.IsaacExternalizable;
import sh.isaac.api.externalizable.StampAlias;
import sh.isaac.api.externalizable.StampComment;
import sh.isaac.api.identity.IdentifiedObject;
import sh.isaac.api.transaction.Transaction;

/**
 * The Interface CommitService.
 *
 * @author kec
 */
@Contract
public interface CommitService
        extends DatastoreServices {
   /**
    * Adds the alias.  Note, you should only add the alias after
    * the first stamp has been committed, otherwise, your alias comment
    * will be overwritten when the transaction with the first stamp is committed.
    *
    * @param stampSequence the stamp sequence
    * @param stampAlias the stamp alias
    * @param aliasCommitComment the alias commit comment
    */
   void addAlias(int stampSequence, int stampAlias, String aliasCommitComment);

   /**
    * Adds the change checker.
    *
    * @param checker the checker
    */
   void addChangeChecker(ChangeChecker checker);

   /**
    * Due to the use of Weak References in the implementation, you MUST maintain a reference to the change listener that is passed in here,
    * otherwise, it will be rapidly garbage collected, and you will randomly stop getting change notifications!.
    *
    * @param changeListener the change listener
    */
   void addChangeListener(ChronologyChangeListener changeListener);

   void addCommitListener(CommitListener commitListener);
   void removeCommitListener(CommitListener commitListener);

   Task<Void> addUncommitted(Transaction transaction, Version version);

   /**
    * TODO remove and depend on transaction? Make it a private interface or service for transactions?
    *
    * @param transaction
    * @param chronology
    * @return
    */
   Task<Void> addUncommitted(Transaction transaction, Chronology chronology);

   /**
    * Commit all pending changes for the provided EditCoordinate. The caller may
    * chose to block on the returned task if synchronous operation is desired.
    *
    * @param transaction the transaction to determine which changes to
    *                       commit.
    * @param commitComment  comment to associate with the commit.
    * @return task representing the cancel.
    * TODO remove and depend on transaction?
    */
   CommitTask commit(Transaction transaction, String commitComment, ConcurrentSkipListSet<AlertObject> alertCollection);

   CommitTask commit(Transaction transaction, String commitComment,
                     ConcurrentSkipListSet<AlertObject> alertCollection, Instant commitTime);

   /**
    * Import a object and immediately write to the proper service with no checks of any type performed.
    * Semantics and concepts will have their versions  merged with existing versions if they exist.
    *
    * one MUST call {@link CommitService#postProcessImportNoChecks()} when your import batch is complete
    * to ensure data integrity.
    *
    * @param isaacExternalizable the object to be imported.
    */
   void importNoChecks(IsaacExternalizable isaacExternalizable);
   /**
    * Import a object if more than the time of a version has changed,
    * and immediately write to the proper service with no checks other than commit time of any type performed.
    * Semantics and concepts will have their versions  merged with existing versions if they exist.
    *
    * one MUST call {@link CommitService#postProcessImportNoChecks()} when your import batch is complete
    * to ensure data integrity.
    *
    * @param isaacExternalizable the object to be imported.
    * @return The Chronology if the IsaacExternalizable contains a new version.
    */
   Optional<Chronology> importIfContentChanged(IsaacExternalizable isaacExternalizable);

   /**
    * Increment and get sequence.
    *
    * @return the long
    */
   long incrementAndGetSequence();

   /**
    * Runs any update code (such as taxonomy updates) that may need to be done as a result of using
    * {@link #importNoChecks(IsaacExternalizable)}.  There are certain operations that cannot be done
    * during the import, to avoid running into data consistency issues.  This must be called if any call to
    * importNoChecks returns a value greater than 0, implying there is at least one deferred operation.
    */
   void postProcessImportNoChecks();

   /**
    * Removes the change checker.
    *
    * @param checker the checker
    */
   void removeChangeChecker(ChangeChecker checker);

   /**
    * Removes the change listener.
    *
    * @param changeListener the change listener
    */
   void removeChangeListener(ChronologyChangeListener changeListener);

   /**
    * Gets the aliases.
    *
    * @param stampSequence the stamp sequence
    * @return the aliases
    */
   int[] getAliases(int stampSequence);

   /**
    * Gets the comment.
    *
    * @param stampSequence the stamp sequence
    * @return the comment
    */
   Optional<String> getComment(int stampSequence);

   /**
    * This method should NOT be considered part of the public API, and should NOT be used.
    * It is only for internal use when loading from IBDF.
    *
    * Specify comments and stamps during commit.
    *
    * @param stampSequence the stamp sequence
    * @param comment the comment
    */
   void setComment(int stampSequence, String comment);

   /**
    * Gets the commit manager sequence.
    *
    * @return the commit manager sequence
    */
   long getCommitManagerSequence();

   /**
    * Gets the stamp alias stream.
    *
    * @param parallel true to allow parallel, false for single threaded
    * @return the stamp alias stream
    */
   Stream<StampAlias> getStampAliasStream(boolean parallel);

   /**
    * Gets the stamp comment stream.
    *
    * @param parallel true to allow parallel, false for single threaded
    * @return the stamp comment stream
    */
   Stream<StampComment> getStampCommentStream(boolean parallel);

   /**
    * Gets the uncommitted component text summary.
    *
    * @return a summary of the uncommitted components being managed by the commit manager.
    */
   String getUncommittedComponentTextSummary();

   /**
    * Gets the uncommitted concept nids.
    *
    * @return the uncommitted concept nids
    */
   ObservableList<Integer> getUncommittedConceptNids();

   /**
   * Calls {@link #newTransaction(Optional, ChangeCheckerMode)} with {@link ChangeCheckerMode#ACTIVE}
   * @param transactionName name for the transaction
   * @return a new transaction that will perform tests depending on value of performTests.
   */
   default Transaction newTransaction(String transactionName) {
      return newTransaction(Optional.ofNullable(transactionName), ChangeCheckerMode.ACTIVE);
   }

   /**
    * Calls {@link #newTransaction(Optional, ChangeCheckerMode)} with {@link ChangeCheckerMode#ACTIVE} and indexOnCommit=true
    * @param transactionName optional name for the transaction
    * @param changeCheckerMode true if tests should be performed.
    * @return a new transaction that will perform tests depending on value of performTests.
    */
   default Transaction newTransaction(Optional<String> transactionName, ChangeCheckerMode changeCheckerMode) {
       return newTransaction(transactionName, changeCheckerMode, true);
   }

   /**
   * @param transactionName optional name for the transaction
   * @param changeCheckerMode true if tests should be performed.
   * @param indexOnCommit if true, let indexers run after commit, if false, do not index after commit (typical only
   * for a batch operation that handles its own indexing)
   * @return a new transaction that will perform tests depending on value of performTests.
   */
  Transaction newTransaction(Optional<String> transactionName, ChangeCheckerMode changeCheckerMode, boolean indexOnCommit);

   /**
    *
    * @return get a list of pending transactions.
    */
   ObservableSet<Transaction> getPendingTransactionList();

   /**
    * @return a current Instant that can be used as a commit time for a long-lived process, such as
    * wanting to commit the results of a classification process at the time of the stamp position used
    * to determine current axioms.
    */
   Instant getTimeForCommit();

   /**
    * Notify listeners of changes in this commit record.
    * TODO: eliminate this method when import change sets uses a transaction, and a proper commit.
    * @param commitRecord
    */
   void notifyListeners(CommitRecord commitRecord);
}


text:
package trace

import (
	emptypb "github.com/golang/protobuf/ptypes/empty"
	timestamppb "github.com/golang/protobuf/ptypes/timestamp"
	cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v2"
)

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"strings"
	"testing"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"golang.org/x/net/context"
	"google.golang.org/api/option"
	status "google.golang.org/genproto/googleapis/rpc/status"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	gstatus "google.golang.org/grpc/status"
)

var _ = io.EOF
var _ = ptypes.MarshalAny
var _ status.Status

type mockTraceServer struct {
	// Embed for forward compatibility.
	// Tests will keep working if more methods are added
	// in the future.
	cloudtracepb.TraceServiceServer

	reqs []proto.Message

	// If set, all calls return this error.
	err error

	// responses to return if err == nil
	resps []proto.Message
}

func (s *mockTraceServer) BatchWriteSpans(ctx context.Context, req *cloudtracepb.BatchWriteSpansRequest) (*emptypb.Empty, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*emptypb.Empty), nil
}

func (s *mockTraceServer) CreateSpan(ctx context.Context, req *cloudtracepb.Span) (*cloudtracepb.Span, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
		return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
	}
	s.reqs = append(s.reqs, req)
	if s.err != nil {
		return nil, s.err
	}
	return s.resps[0].(*cloudtracepb.Span), nil
}

// clientOpt is the option tests should use to connect to the test server.
// It is initialized by TestMain.
var clientOpt option.ClientOption

var (
	mockTrace mockTraceServer
)

func TestMain(m *testing.M) {
	flag.Parse()

	serv := grpc.NewServer()
	cloudtracepb.RegisterTraceServiceServer(serv, &mockTrace)

	lis, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		log.Fatal(err)
	}
	go serv.Serve(lis)

	conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	clientOpt = option.WithGRPCConn(conn)

	os.Exit(m.Run())
}

func TestTraceServiceBatchWriteSpans(t *testing.T) {
	var expectedResponse *emptypb.Empty = &emptypb.Empty{}

	mockTrace.err = nil
	mockTrace.reqs = nil

	mockTrace.resps = append(mockTrace.resps[:0], expectedResponse)

	var formattedName string = fmt.Sprintf("projects/%s", "[PROJECT]")
	var spans []*cloudtracepb.Span = nil
	var request = &cloudtracepb.BatchWriteSpansRequest{
		Name:  formattedName,
		Spans: spans,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	err = c.BatchWriteSpans(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockTrace.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

}

func TestTraceServiceBatchWriteSpansError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockTrace.err = gstatus.Error(errCode, "test error")

	var formattedName string = fmt.Sprintf("projects/%s", "[PROJECT]")
	var spans []*cloudtracepb.Span = nil
	var request = &cloudtracepb.BatchWriteSpansRequest{
		Name:  formattedName,
		Spans: spans,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	err = c.BatchWriteSpans(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
}
func TestTraceServiceCreateSpan(t *testing.T) {
	var name2 string = "name2-1052831874"
	var spanId2 string = "spanId2-643891741"
	var parentSpanId string = "parentSpanId-1757797477"
	var expectedResponse = &cloudtracepb.Span{
		Name:         name2,
		SpanId:       spanId2,
		ParentSpanId: parentSpanId,
	}

	mockTrace.err = nil
	mockTrace.reqs = nil

	mockTrace.resps = append(mockTrace.resps[:0], expectedResponse)

	var formattedName string = fmt.Sprintf("projects/%s/traces/%s/spans/%s", "[PROJECT]", "[TRACE]", "[SPAN]")
	var spanId string = "spanId-2011840976"
	var displayName *cloudtracepb.TruncatableString = &cloudtracepb.TruncatableString{}
	var startTime *timestamppb.Timestamp = &timestamppb.Timestamp{}
	var endTime *timestamppb.Timestamp = &timestamppb.Timestamp{}
	var request = &cloudtracepb.Span{
		Name:        formattedName,
		SpanId:      spanId,
		DisplayName: displayName,
		StartTime:   startTime,
		EndTime:     endTime,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.CreateSpan(context.Background(), request)

	if err != nil {
		t.Fatal(err)
	}

	if want, got := request, mockTrace.reqs[0]; !proto.Equal(want, got) {
		t.Errorf("wrong request %q, want %q", got, want)
	}

	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
		t.Errorf("wrong response %q, want %q)", got, want)
	}
}

func TestTraceServiceCreateSpanError(t *testing.T) {
	errCode := codes.PermissionDenied
	mockTrace.err = gstatus.Error(errCode, "test error")

	var formattedName string = fmt.Sprintf("projects/%s/traces/%s/spans/%s", "[PROJECT]", "[TRACE]", "[SPAN]")
	var spanId string = "spanId-2011840976"
	var displayName *cloudtracepb.TruncatableString = &cloudtracepb.TruncatableString{}
	var startTime *timestamppb.Timestamp = &timestamppb.Timestamp{}
	var endTime *timestamppb.Timestamp = &timestamppb.Timestamp{}
	var request = &cloudtracepb.Span{
		Name:        formattedName,
		SpanId:      spanId,
		DisplayName: displayName,
		StartTime:   startTime,
		EndTime:     endTime,
	}

	c, err := NewClient(context.Background(), clientOpt)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := c.CreateSpan(context.Background(), request)

	if st, ok := gstatus.FromError(err); !ok {
		t.Errorf("got error %v, expected grpc error", err)
	} else if c := st.Code(); c != errCode {
		t.Errorf("got error code %q, want %q", c, errCode)
	}
	_ = resp
}


text:
import unittest
import random, sys, time, os
sys.path.extend(['.','..','../..','py'])

import h2o, h2o_cmd, h2o_import as h2i, h2o_exec as h2e
import codecs

print 'Maybe h2o is supposed to NA rows if they start with an unmatched "'
print "For now, complain if numRows isn't what I generated"
print
print "We throw in double quotes to terminate the string randomly, along with random within the string"
print "Will this change row/col? not sure. failing on numRows right now"
print "allow for an extra col to be created relative to my one col expectation"

UTF16 = False
UTF8 = False
ASCII = True
UTF8_MULTIBYTE = False

DOUBLE_QUOTE = True
DOUBLE_QUOTE_END_RANDOM = False
RANDOM_EMPTY = True

SINGLE_QUOTE = True

if ASCII:
    # leave DEL (0x7F) out also, in addition to the control chars 0x0-0x1f)
    ordinalChoices = range(0x20, 0x7f) # doesn't include last value
elif UTF8:
    # what about multi-byte UTF8
    ordinalChoices = range(0x0, 0x100) # doesn't include last value
elif DOUBLE_QUOTE:
    # ascii subset
    ordinalChoices = range(0x0, 0x40) # doesn't include last value
else:  # ascii subset?
    ordinalChoices = range(0x0, 0x80) # doesn't include last value

if UTF8_MULTIBYTE:
    # add some UTF8 multibyte, and restrict the choices to make sure we hit these
    ordinalChoices = range(0x0, 0x40) # doesn't include last value ..allow 7f
    ordinalChoices += [0x201c, 0x201d, 0x2018, 0x2019, 6000]

def safe_remove(thing, thingList):
    # remove first occurence if in list
    if thing in thingList:
        thingList.remove(thing)

safe_remove(0x09, ordinalChoices) # is 9 bad..apparently can cause NA

safe_remove(0x00, ordinalChoices) # nul
safe_remove(0x0d, ordinalChoices) # cr
safe_remove(0x0a, ordinalChoices) # lf
safe_remove(0x01, ordinalChoices) # hiveseparator

# smaller range, avoiding 0-1f control chars
safe_remove(0x3b, ordinalChoices) # semicolon
safe_remove(0x20, ordinalChoices) # space
safe_remove(0x22, ordinalChoices) # double quote

if not SINGLE_QUOTE:
    safe_remove(0x27, ordinalChoices) # apostrophe. should be legal if single quotes not enabled
safe_remove(0x2c, ordinalChoices) # comma

safe_remove(0x30, ordinalChoices) # 0
safe_remove(0x31, ordinalChoices) # 1
safe_remove(0x32, ordinalChoices) # 2
safe_remove(0x33, ordinalChoices) # 3
safe_remove(0x34, ordinalChoices) # 4
safe_remove(0x35, ordinalChoices) # 5
safe_remove(0x36, ordinalChoices) # 6
safe_remove(0x37, ordinalChoices) # 7
safe_remove(0x38, ordinalChoices) # 8
safe_remove(0x39, ordinalChoices) # 9

if DOUBLE_QUOTE:
    # ascii subset
    ordinalChoices.append(0x22) # double quote

def generate_random_utf8_string(length=5):
        # want to handle more than 256 numbers
        cList = []
        for i in range(length):
            # to go from hex 'string" to number
            # cint = int('fd9b', 16)
            r = random.choice(ordinalChoices)
            c = unichr(r).encode('utf-8')
            cList.append(c)

        # this is a random byte string now, of type string?
        return "".join(cList)

def write_syn_dataset(csvPathname, rowCount, colCount, SEED):
    r1 = random.Random(SEED)
    if UTF8 or UTF8_MULTIBYTE:
        dsf = codecs.open(csvPathname, encoding='utf-8', mode='w+')
    elif UTF16:
        dsf = codecs.open(csvPathname, encoding='utf-16', mode='w+')
    else:
        dsf = open(csvPathname, "w+")

    for i in range(rowCount):
        if UTF16:
            u = unichr(0x2018) + unichr(6000) + unichr(0x2019)
            rowDataCsv = u
        else: # both ascii and utf-8 go here?
            rowData = []
            for j in range(colCount):
                r = generate_random_utf8_string(length=5)
                rowData.append(r)
            rowDataCsv = ",".join(rowData)

        if UTF16:
            # we're already passing it unicode. no decoding needed
            print "utf16:", repr(rowDataCsv), type(rowDataCsv)
            decoded = rowDataCsv
        else:
            print "str:", repr(rowDataCsv), type(rowDataCsv)
            decoded = rowDataCsv.decode('utf-8')
            # this has the right length..multibyte utf8 are decoded
            print "utf8:" , repr(decoded), type(decoded)

        # TEMP: always end every line with a double quote. This might complete some double quote starters
        # so that means the # of cols will be wrong? maybe allow it to be 1 more below
        # dsf.write(rowDataCsv + "\n")
        # maybe do it randomly

        # random empty lines, plus DOUBLE_QUOTE_END_RANDOM will have random just double quote lines
        if RANDOM_EMPTY and (random.randint(0,1)==1):
            decoded = ""

        if DOUBLE_QUOTE_END_RANDOM and (random.randint(0,1)==1):
            dsf.write(decoded + '"' + "\n")
        else:
            dsf.write(decoded + "\n")

    dsf.close()

class Basic(unittest.TestCase):
    def tearDown(self):
        h2o.check_sandbox_for_errors()

    @classmethod
    def setUpClass(cls):
        global SEED
        SEED = h2o.setup_random_seed()
        h2o.init(2,java_heap_GB=1,use_flatfile=True)

    @classmethod
    def tearDownClass(cls):
        h2o.tear_down_cloud()

    def test_parse_rand_utf8_just_double_quote(self):
        SYNDATASETS_DIR = h2o.make_syn_dir()
        tryList = [
            (1000, 1, 'cA', 120),
            (1000, 1, 'cG', 120),
            (1000, 1, 'cH', 120),
            ]

        print "What about messages to log (INFO) about unmatched quotes (before eol)"
        # got this ..trying to avoid for now
        # Exception: rjson error in parse: Argument 'source_key' error: Parser setup appears to be broken, got AUTO

        print "what we used"
        print "ordinalChoices:", ordinalChoices
        for (rowCount, colCount, hex_key, timeoutSecs) in tryList:
            SEEDPERFILE = random.randint(0, sys.maxint)
            csvFilename = 'syn_' + str(SEEDPERFILE) + "_" + str(rowCount) + 'x' + str(colCount) + '.csv'
            csvPathname = SYNDATASETS_DIR + '/' + csvFilename

            print "\nCreating random", csvPathname
            write_syn_dataset(csvPathname, rowCount, colCount, SEEDPERFILE)
            parseResult = h2i.import_parse(path=csvPathname, schema='put', header=0,
                hex_key=hex_key, timeoutSecs=timeoutSecs, doSummary=False)
            print "Parse result['destination_key']:", parseResult['destination_key']
            inspect = h2o_cmd.runInspect(None, parseResult['destination_key'], timeoutSecs=60)

            print "inspect:", h2o.dump_json(inspect)
            numRows = inspect['numRows']

            # Don't check for now..going to get empty rows
            # self.assertEqual(numRows, rowCount, msg='Wrong numRows likely due to unmatched " row going to NA: %s %s' % (numRows, rowCount))
            numCols = inspect['numCols']

            # because of our double quote termination hack above
            if DOUBLE_QUOTE:
                self.assertTrue((numCols==colCount or numCols==colCount+1), msg='Wrong numCols: %s %s' % (numCols, colCount))
            else:
                self.assertTrue(numCols==colCount, msg='Wrong numCols: %s %s' % (numCols, colCount))

            for k in range(colCount):
                naCnt = inspect['cols'][k]['naCnt']
                self.assertEqual(0, naCnt, msg='col %s naCnt %d should be 0' % (k, naCnt))

                stype = inspect['cols'][k]['type']
                self.assertEqual("Enum", stype, msg='col %s type %s should be Enum' % (k, stype))

if __name__ == '__main__':
    h2o.unit_main()


text:
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://jboss.org/schema/arquillian"
            xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

  <extension qualifier="openshift">
    <property name="namespace.use.current">true</property>
    <property name="env.init.enabled">true</property>
    <property name="enableImageStreamDetection">false</property>
    <property name="env.dependencies">file://${basedir}/target/test-classes/test-configmap.yml</property>
  </extension>

</arquillian>


text:
module Pulitzer
  class Post < Pulitzer::ApplicationRecord
    include ForeignOffice::Broadcaster if defined? ForeignOffice
    extend ::FriendlyId
    has_many :versions, -> { includes(free_form_sections: {partials: [{post_type_version: [:background_styles, :justification_styles, :sequence_flow_styles, :arrangement_styles]}, :content_elements, :background_style, :justification_style, :sequence_flow_style, :arrangement_style]}) }, dependent: :destroy, index_errors: true, inverse_of: :post
    has_one :active_version, -> { where(status: 'active').includes(free_form_sections: {partials: [{post_type_version: [:background_styles, :justification_styles, :sequence_flow_styles, :arrangement_styles]}, :content_elements, :background_style, :justification_style, :sequence_flow_style, :arrangement_style]}) }, class_name: "Pulitzer::Version"

    accepts_nested_attributes_for :versions

    belongs_to :post_type_version
    delegate :post_type_content_element_types, :free_form_section_types, :has_free_form_sections?, :has_templated_content_elements?, :post_type, :post_type_id, :plural?, to: :post_type_version
    delegate :post_tags, :content_elements, :content_element, :section, :has_label_type, :has_label, :post_tags_for, to: :active_version, allow_nil: true

    friendly_id :title, use: [:slugged, :finders]

    attr_accessor :new_preview_version

    validates :title, presence: true
    validates :slug, uniqueness: true

    TAG_MODELS = ["Pulitzer::Tag"] + Pulitzer.tagging_models

    def self.export_config
      {
        except: [:id, :post_type_version_id, :created_at, :updated_at, :slug],
        include: {
          versions: Version.export_config
        }
      }
    end

    def self.convert_nested_assoc(json_hash)
      this_array = json_hash.has_key?(attrs_name) ? json_hash[attrs_name] : [json_hash]
      this_array.map!{|p_attrs|
        new_attrs = Pulitzer::Version.convert_hash_to_nested p_attrs
      }
      json_hash
    end

    def active_version!
      versions.find_by!(status: Pulitzer::Version.statuses[:active])
    end

    def clonable_versions
      versions.where(status: ['active','preview'])
    end

    def tags
      post_tags.map(&:label)
    end

    def should_generate_new_friendly_id?
      new_record? || title_changed?
    end

    def get_preview_version!
      this_version = versions.preview.last
      if this_version.present?
        return this_version
      elsif versions.processing.any?
        raise Pulitzer::VersionProcessingError.new("That version is still processing, it will be done soon." )
      else
        raise Pulitzer::VersionMissingError.new("We couldn't find a preview for that post, check with your system administrator to see how this happened.")
      end
    end

    def get_active_version!
      if active_version.present?
        return active_version
      else
        raise Pulitzer::VersionMissingError.new("We couldn't find that page. It looks like we no longer offer that.")
      end
    end

    def preview_version
    	versions.preview.last
    end

    def processing_version
      versions.processing.last
    end

    def processing_failed_version
      versions.processing_failed.last
    end

    def next_version
      preview_version || processing_version || processing_failed_version
    end

    def create_preview_version
      versions.create(status: :preview)
    end

    def create_processing_version
      versions.create(status: :processing)
    end

    def editor_title
      if post_type_version.published?
        title
      else
        title + " version #{post_type_version.version_number}"
      end
    end

    def serialize
      self.attributes.merge \
        new_preview_version: self.new_preview_version
    end
  end
end


text:
<!doctype html>

  <title>element script</title>

  <link rel="import" href="../../polymer.html">

  <x-foo></x-foo>

  <x-bar></x-bar>

  <x-zot></x-zot>

  <x-baz></x-baz>

  <x-qux></x-qux>

  <x-quux></x-quux>

  <polymer-element name="x-foo">
    <template>
      Hello Light World
    </template>
  </polymer-element>

  <polymer-element name="x-bar" extends="x-foo">
    <template>
      Hello Lighter World [<shadow></shadow>]
    </template>
  </polymer-element>

  <polymer-element name="x-zot" extends="x-foo" noscript>
    <template>
      Hello Lighter World [<shadow></shadow>]
    </template>
  </polymer-element>

  <polymer-element name="x-baz" extends="x-zot">

  </polymer-element>

  <polymer-element name="x-qux" extends="x-zot">
  </polymer-element>

  <polymer-element name="x-quux" extends="x-zot">

  </polymer-element>


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tencent.mm.directory;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;

public interface Directory {
  public final char separator = '/';

  public Set<String> getFiles();

  public Set<String> getFiles(boolean recursive);

  public Map<String, Directory> getDirs();

  public Map<String, Directory> getDirs(boolean recursive);

  public boolean containsFile(String path);

  public boolean containsDir(String path);

  public InputStream getFileInput(String path) throws DirectoryException;

  public OutputStream getFileOutput(String path) throws DirectoryException;

  public Directory getDir(String path) throws PathNotExist;

  public Directory createDir(String path) throws DirectoryException;

  public boolean removeFile(String path);
}


text:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController, ToastController } from 'ionic-angular';
import { AppService, ApiUrl } from '../../app/app.service';
import { HttpService, UiProvider } from '../../providers/providers';

export interface IRegister {
  Telphone: string,
  Password: string,
  Password2: string,
  Code: string,
  StoreId: number
}
export interface ICallback {
  success: boolean,
  data: string
}
@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {
  reg: IRegister;
  _w: any = window;
  timer: any;

  constructor(public navCtrl: NavController, public navParams: NavParams,
    private http: HttpService,
    private viewCtrl: ViewController,
    private appService: AppService,
    private toastCtrl: ToastController,
    private UI: UiProvider
  ) {
    this.reg = { Telphone: "", Password: "", Code: "", Password2: "", StoreId: this._w.StoreId };
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisterPage');
    console.log(this.appService._time);
    this.interval();
  }

  interval() {
    console.log("_time:" + this.appService._time);
    this.timer = setInterval(() => {
      if (this.appService._time > 1) {
        this.appService._sendCodeBtnText = this.appService._time + '秒后重试';
        this.appService._time -= 1;
      }
      else {
        this.appService._sendCodeBtnText = "发送验证码";
        this.appService._time = 0;
        clearInterval(this.timer)
      }
      console.log(this.appService._time);
    }, 1000);
  }

  postRegister() {
    if (!/^1(3|4|5|7|8)[0-9]\d{8}$/i.test(this.reg.Telphone)) {
      this.UI.showToast("手机号码错误", 2000, "middle");
      return;
    }
    if (!/^\d{6}$/i.test(this.reg.Code)) {
      this.UI.showToast("验证码为六位数字", 2000, "middle");
      return;
    }
    if (!/^[^\s]{6,}$/i.test(this.reg.Password)) {
      this.UI.showToast("密码长度大于5位并不含空格", 2000, "middle");
      return;
    }
    this.http.httpPost(ApiUrl + "Register", this.reg)
      .then(res => {
        console.log(res);
        if (res.success) {
          this.UI.showToast("注册成功", 2000, "top");
          this.dismiss();
        }
        else {
          this.UI.showToast(res.msg, 2000, "middle");
        }
      });
  }

  sendCode() {
    if (!/^1(3|4|5|7|8)[0-9]\d{8}$/i.test(this.reg.Telphone)) {
      this.UI.showToast("手机号码错误", 2000, "top");
      return;
    }

    this.http.httpGet(ApiUrl + 'getCode?tel=' + this.reg.Telphone + "&storeid=" + this._w.StoreId)
      .then(res => {
        if (res.success) {
          this.UI.showToast("发送成功", 2000, "top");
          this.appService._time = 60;
          this.interval();
        }
        else {
          this.presentToast(res.data);
        }
      }, error => {
        this.presentToast(error);
      })
  }

  presentToast(_text) {
    let toast = this.toastCtrl.create({
      message: _text,
      duration: 2000,
      position: 'middle'
    });

    // toast.onDidDismiss(() => {
    //   console.log('Dismissed toast');
    // });

    toast.present();
  }

  verify() {

    let _result = /^\d{11}$/.test(this.reg.Telphone) &&
      /^\S{8,}$/.test(this.reg.Password) &&
      /^\d{4}$/.test(this.reg.Code);
    // console.log(_result);
    return _result;
  }

  dismiss() {
    this.viewCtrl.dismiss();
  }

  verifyTel() {
    console.log(!/^\d{11}$/.test(this.reg.Telphone) || this.appService._time > 0);
    return !/^\d{11}$/.test(this.reg.Telphone) || this.appService._time > 0;
  }

  ngOnDestroy() {
    clearInterval(this.timer)
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>retificar-boletim-de-acidente-de-transito</id>
    <dbId>2950</dbId>
    <nome>Retificar boletim de acidente de trânsito</nome>
    <sigla></sigla>
    <descricao>A retificação de boletim de acidente de trânsito é um serviço  fornecido ao usuário envolvido em acidente de transito inconformado com alguma informação constante no BAT ou algum dado que julga ser diferente do real.</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="3533">
            <tipo>Qualquer pessoa que tenha registrado um acidente junto à Polícia Rodoviária Federal.</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="6790">
            <titulo>Requerer retificação</titulo>
            <descricao>Requerimento da Retificação de Boletim de Acidente de Trânsito - interessado deverá protocolar o seu requerimento em qualquer unidade da PRF, em formulário padronizado ou não.</descricao>
            <documentos>
                <default>
                    <item id="9157">Carteira de identidade</item>
                    <item id="9158">Carteira de trabalho</item>
                    <item id="9159">documento do veículo</item>
                    <item id="9160">Requerimento</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="7038" tipo="presencial">
                        <descricao>Em qualquer [Unidade Operacional da PRF](https://www.prf.gov.br/portal/unidades-prf)</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/316" dbId="37532">
        <nomeOrgao>Ministério da Justiça e Segurança Pública (MJSP)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="1" idServicoSegmento="6713">Cidadãos</item>
        <item idSegmento="3" idServicoSegmento="6714">Empresas</item>
        <item idSegmento="2" idServicoSegmento="6715">Órgãos e entidades públicas</item>
        <item idSegmento="4" idServicoSegmento="6716">Demais segmentos (ONGs, organizações sociais, etc)</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Segurança e Ordem Pública</item>
        <item>Transportes</item>
        <item>Transporte Rodoviário</item>
        <item>Policiamento</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="12617">retificar</item>
        <item id="12618">corrigir</item>
        <item id="12619">acidente</item>
    </palavras-chave>
</servico>


text:
<?php

declare(strict_types=1);

namespace Browscap\Data\Factory;

use Assert\Assertion;
use Assert\AssertionFailedException;
use Browscap\Data\Browser;
use Browscap\Data\DataCollection;
use Browscap\Data\Device;
use Browscap\Data\Division;
use Browscap\Data\DuplicateDataException;
use Browscap\Data\Engine;
use Browscap\Data\Platform;
use Browscap\Data\Validator\DivisionDataValidator;
use JsonException;
use LogicException;
use Psr\Log\LoggerInterface;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use SplFileInfo;
use UnexpectedValueException;

use function array_keys;
use function assert;
use function file_exists;
use function file_get_contents;
use function is_array;
use function is_string;
use function json_decode;

use const JSON_THROW_ON_ERROR;

/**
 * @phpstan-import-type DivisionData from Division
 * @phpstan-import-type DeviceData from Device
 * @phpstan-import-type BrowserData from Browser
 * @phpstan-import-type EngineData from Engine
 * @phpstan-import-type PlatformData from Platform
 */
class DataCollectionFactory
{
    private DataCollection $collection;

    private LoggerInterface $logger;

    private DivisionFactory $divisionFactory;

    private DeviceFactory $deviceFactory;

    private DivisionDataValidator $divisionDataValidator;

    /** @var array<string> */
    private array $allDivisions = [];

    /**
     * @throws void
     */
    public function __construct(LoggerInterface $logger)
    {
        $this->logger                = $logger;
        $useragentFactory            = new UserAgentFactory();
        $this->divisionFactory       = new DivisionFactory($useragentFactory);
        $this->deviceFactory         = new DeviceFactory();
        $this->divisionDataValidator = new DivisionDataValidator();
        $this->collection            = new DataCollection();
    }

    /**
     * Create and populate a data collection object from a resource folder
     *
     * @throws AssertionFailedException
     * @throws RuntimeException
     * @throws UnexpectedValueException
     * @throws LogicException
     */
    public function createDataCollection(string $resourceFolder): DataCollection
    {
        $iterator = static function (string $directory, LoggerInterface $logger, callable $function): void {
            if (! file_exists($directory)) {
                throw new RuntimeException('Directory "' . $directory . '" does not exist.');
            }

            $addedFiles = 0;

            foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
                assert($file instanceof SplFileInfo);
                if (! $file->isFile() || $file->getExtension() !== 'json') {
                    continue;
                }

                $logger->debug('add file ' . $file->getPathname());
                $function($file->getPathname());
                ++$addedFiles;
            }

            if (! $addedFiles) {
                throw new RuntimeException('Directory "' . $directory . '" was empty.');
            }
        };

        $this->logger->debug('add platform file');

        $iterator(
            $resourceFolder . '/platforms',
            $this->logger,
            function (string $file): void {
                $this->addPlatformsFile($file);
            }
        );

        $this->logger->debug('add engine file');

        $iterator(
            $resourceFolder . '/engines',
            $this->logger,
            function (string $file): void {
                $this->addEnginesFile($file);
            }
        );

        $this->logger->debug('add file for default properties');
        $this->setDefaultProperties($resourceFolder . '/core/default-properties.json');

        $this->logger->debug('add file for default browser');
        $this->setDefaultBrowser($resourceFolder . '/core/default-browser.json');

        $iterator(
            $resourceFolder . '/devices',
            $this->logger,
            function (string $file): void {
                $this->addDevicesFile($file);
            }
        );

        $iterator(
            $resourceFolder . '/browsers',
            $this->logger,
            function (string $file): void {
                $this->addBrowserFile($file);
            }
        );

        $iterator(
            $resourceFolder . '/user-agents',
            $this->logger,
            function (string $file): void {
                $this->addSourceFile($file);
            }
        );

        return $this->collection;
    }

    /**
     * Load a platforms.json file and parse it into the platforms data array, validates these data and creates a
     * collection of Platform objects
     *
     * @param string $filename Name of the file
     *
     * @throws RuntimeException if the file does not exist or has invalid JSON.
     * @throws UnexpectedValueException
     * @throws AssertionFailedException
     */
    public function addPlatformsFile(string $filename): void
    {
        /** @var mixed[][] $decodedFileContent */
        /** @phpstan-var array<PlatformData> $decodedFileContent */
        $decodedFileContent = $this->loadFile($filename);

        $platformFactory = new PlatformFactory();

        foreach (array_keys($decodedFileContent) as $platformName) {
            $platformName = (string) $platformName;

            /** @phpstan-var PlatformData $platformData */
            $platformData = $decodedFileContent[$platformName];

            $this->collection->addPlatform(
                $platformName,
                $platformFactory->build($platformData, $decodedFileContent, $platformName)
            );
        }
    }

    /**
     * Load a engines.json file and parse it into the platforms data array, validates these data and creates a
     * collection of Engine objects
     *
     * @param string $filename Name of the file
     *
     * @throws RuntimeException if the file does not exist or has invalid JSON.
     * @throws AssertionFailedException
     */
    public function addEnginesFile(string $filename): void
    {
        /** @var mixed[][] $decodedFileContent */
        /** @phpstan-var array<EngineData> $decodedFileContent */
        $decodedFileContent = $this->loadFile($filename);

        $engineFactory = new EngineFactory();

        foreach (array_keys($decodedFileContent) as $engineName) {
            $engineName = (string) $engineName;
            /** @phpstan-var EngineData $engineData */
            $engineData = $decodedFileContent[$engineName];

            $this->collection->addEngine(
                $engineName,
                $engineFactory->build($engineData, $decodedFileContent, $engineName)
            );
        }
    }

    /**
     * Load a browsers.json file and parse it into the browsers data array, validates these data and creates a
     * collection of Browser objects
     *
     * @param string $filename Name of the file
     *
     * @throws RuntimeException if the file does not exist or has invalid JSON.
     * @throws AssertionFailedException
     * @throws DuplicateDataException
     */
    public function addBrowserFile(string $filename): void
    {
        /** @var mixed[][] $decodedFileContent */
        /** @phpstan-var array<BrowserData> $decodedFileContent */
        $decodedFileContent = $this->loadFile($filename);

        Assertion::isArray($decodedFileContent, 'required "browsers" structure has to be an array');

        $browserFactory = new BrowserFactory();

        foreach (array_keys($decodedFileContent) as $browserName) {
            /** @phpstan-var BrowserData $browserData */
            $browserData = $decodedFileContent[$browserName];
            $browserName = (string) $browserName;

            $this->collection->addBrowser($browserName, $browserFactory->build($browserData, $browserName));
        }
    }

    /**
     * Load a devices.json file and parse it into the platforms data array, validates these data and creates a
     * collection of Device objects
     *
     * @param string $filename Name of the file
     *
     * @throws AssertionFailedException
     * @throws RuntimeException if the file does not exist or has invalid JSON.
     * @throws DuplicateDataException
     */
    public function addDevicesFile(string $filename): void
    {
        /** @var mixed[][] $decodedFileContent */
        /** @phpstan-var array<DeviceData> $decodedFileContent */
        $decodedFileContent = $this->loadFile($filename);

        foreach ($decodedFileContent as $deviceName => $deviceData) {
            /** @phpstan-var DeviceData $deviceData */
            assert(is_array($deviceData));

            $this->collection->addDevice($deviceName, $this->deviceFactory->build($deviceData, $deviceName));
        }
    }

    /**
     * Load a JSON file, parse it's JSON to arrays, validates these data and creates a
     * collection of Division objects
     *
     * @param string $filename Name of the file
     *
     * @throws AssertionFailedException
     * @throws RuntimeException If the file does not exist or has invalid JSON.
     * @throws LogicException
     */
    public function addSourceFile(string $filename): void
    {
        /** @phpstan-var DivisionData $divisionData */
        $divisionData = $this->loadFile($filename);

        $this->allDivisions = $this->divisionDataValidator->validate($divisionData, $filename, $this->allDivisions, false);

        $this->collection->addDivision(
            $this->divisionFactory->build(
                $divisionData,
                $filename,
                false
            )
        );
    }

    /**
     * Load the file for the default properties
     *
     * @param string $filename Name of the file
     *
     * @throws AssertionFailedException
     * @throws RuntimeException if the file does not exist or has invalid JSON.
     * @throws LogicException
     */
    public function setDefaultProperties(string $filename): void
    {
        /** @phpstan-var DivisionData $divisionData */
        $divisionData = $this->loadFile($filename);

        $this->divisionDataValidator->validate($divisionData, $filename, $this->allDivisions, true);

        $this->collection->setDefaultProperties(
            $this->divisionFactory->build(
                $divisionData,
                $filename,
                true
            )
        );
    }

    /**
     * Load the file for the default browser
     *
     * @param string $filename Name of the file
     *
     * @throws AssertionFailedException
     * @throws RuntimeException if the file does not exist or has invalid JSON.
     * @throws LogicException
     */
    public function setDefaultBrowser(string $filename): void
    {
        /** @phpstan-var DivisionData $divisionData */
        $divisionData = $this->loadFile($filename);

        $this->divisionDataValidator->validate($divisionData, $filename, $this->allDivisions, true);

        $this->collection->setDefaultBrowser(
            $this->divisionFactory->build(
                $divisionData,
                $filename,
                true
            )
        );
    }

    /**
     * @return mixed[][]
     *
     * @throws RuntimeException
     * @throws AssertionFailedException
     */
    private function loadFile(string $filename): array
    {
        Assertion::file($filename, 'File "' . $filename . '" does not exist.');
        Assertion::readable($filename, 'File "' . $filename . '" is not readable.');

        $fileContent = file_get_contents($filename);
        assert(is_string($fileContent));

        Assertion::string($fileContent);
        Assertion::notRegex($fileContent, '/[^ -~\s]/', 'File "' . $filename . '" contains Non-ASCII-Characters.');

        try {
            $parsedContent = json_decode($fileContent, true, 512, JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            throw new RuntimeException(
                'File "' . $filename . '" had invalid JSON.',
                0,
                $e
            );
        }

        assert(is_array($parsedContent));

        return $parsedContent;
    }
}


text:
import React from 'react';
import {beginRound, endTurn} from '../../../actions/gameActions.js';

const RightButton = ({dispatch, socket, isStarted, currentRound: {onTurn}, player: {role}}) => {
  const _beginRound = () => dispatch(beginRound(socket));
  if(onTurn === role) return <button onClick={() => dispatch(endTurn(socket))}>end turn</button>;
  if(onTurn === '' && role === 'Sender' && !isStarted) return <button onClick={_beginRound}>start first round</button>;
  if(onTurn === '' && role === 'Sender' && isStarted) return <button onClick={_beginRound}>next round</button>;

  return ;
}

export default RightButton;


text:
export const physicalTypes = Object.freeze({
  pushable: "PUSHABLE",
  obstacle: "OBSTACLE"
});

export const groupTypes = Object.freeze({
  player: "PLAYER",
  target: "TARGET",
  box: "BOX",
  wall: "WALL"
});

export const entitySchemas = Object.freeze({
  player: {
    isPlayer: true,
    group: groupTypes.player,
    physicalType: physicalTypes.obstacle
  },
  target: { group: groupTypes.target },
  box: {
    group: groupTypes.box,
    physicalType: physicalTypes.pushable
  },
  wall: {
    group: groupTypes.wall,
    physicalType: physicalTypes.obstacle
  }
});


text:
[![Build Status](https://dev.azure.com/dsccommunity/ComputerManagementDsc/_apis/build/status/dsccommunity.ComputerManagementDsc?branchName=master)](https://dev.azure.com/dsccommunity/ComputerManagementDsc/_build/latest?definitionId=18&branchName=master)
![Code Coverage](https://img.shields.io/azure-devops/coverage/dsccommunity/ComputerManagementDsc/18/master)
[![Azure DevOps tests](https://img.shields.io/azure-devops/tests/dsccommunity/ComputerManagementDsc/18/master)](https://dsccommunity.visualstudio.com/ComputerManagementDsc/_test/analytics?definitionId=18&contextType=build)
[![PowerShell Gallery (with prereleases)](https://img.shields.io/powershellgallery/vpre/ComputerManagementDsc?label=ComputerManagementDsc%20Preview)](https://www.powershellgallery.com/packages/ComputerManagementDsc/)
[![PowerShell Gallery](https://img.shields.io/powershellgallery/v/ComputerManagementDsc?label=ComputerManagementDsc)](https://www.powershellgallery.com/packages/ComputerManagementDsc/)

## Code of Conduct

This project has adopted [this code of conduct](CODE_OF_CONDUCT.md).

## Releases

For each merge to the branch `master` a preview release will be
deployed to [PowerShell Gallery](https://www.powershellgallery.com/).
Periodically a release version tag will be pushed which will deploy a
full release to [PowerShell Gallery](https://www.powershellgallery.com/).

## Contributing

Please check out common DSC Community [contributing guidelines](https://dsccommunity.org/guidelines/contributing).

## Change log

A full list of changes in each version can be found in the [change log](CHANGELOG.md).

## Resources

The **ComputerManagementDsc** module contains the following resources:

- **Computer**: This resource allows you to configure a computer by changing its
  name and description and modifying its Active Directory domain or workgroup
  membership.
- **IEEnhancedSecurityConfiguration**: This resource allows you to configure
  the IE Enhanced Security Configuration for administrator or user roles.
- **OfflineDomainJoin**: This resource allows you to join computers to an Active
  Directory domain using an [Offline Domain Join](https://technet.microsoft.com/en-us/library/offline-domain-join-djoin-step-by-step(v=ws.10).aspx)
  request file.
- **PendingReboot**: This resource examines specific registry locations where
  a Windows Server might indicate that a reboot is pending and allows DSC to
  predictably handle the condition.
- **PowerPlan**: This resource allows specifying a power plan to activate.
- **PowerShellExecutionPolicy**: Specifies the desired PowerShell execution policy.
- **RemoteDesktopAdmin**: This resource will manage the remote desktop administration
  settings on a computer.
- **ScheduledTask**: This resource is used to define basic run once or recurring
  scheduled tasks on the local computer. It can also be used to delete or disable
  built-in scheduled tasks.

  _The **ScheduledTask** resource requires the `ScheduledTasks` PowerShell module
  which is only available on Windows Server 2012/Windows 8 and above. DSC configurations
  containing this resource may be compiled on Windows Server 2008 R2/Windows 7 but
  can not be applied._
- **SmbServerConfiguration**: This resource is used to configure the SMB Server
  settings on the local machine.
- **SmbShare**: This resource is used to manage SMB shares on a machine.
- **SystemLocale**: This resource is used to set the system locale on a
  Windows machine
- **TimeZone**: This resource is used for setting the time zone on a machine.
- **UserAccountControl**: This resource allows you to configure the notification
  level or granularly configure the User Account Control for the computer.
- **VirtualMemory**: This resource allows configuration of properties of the
  paging file on the local computer.
- **WindowsEventLog**: This resource allows configuration of a specified
  Windows Event Log.
- **WindowsCapability**: This resource provides a mechanism to enable or disable
  Windows Capabilities on a target node.

This project has adopted [this code of conduct](CODE_OF_CONDUCT.md).

## Documentation and Examples

For a full list of resources in ComputerManagementDsc and examples on their use,
check out the [ComputerManagementDsc wiki](https://github.com/dsccommunity/ComputerManagementDsc/wiki).


text:
package net.lacolaco.smileessence.twitter.task;

import android.app.Activity;

import net.lacolaco.smileessence.R;
import net.lacolaco.smileessence.data.FavoriteCache;
import net.lacolaco.smileessence.data.StatusCache;
import net.lacolaco.smileessence.logging.Logger;
import net.lacolaco.smileessence.notification.NotificationType;
import net.lacolaco.smileessence.notification.Notificator;

import twitter4j.*;

public class MentionsTimelineTask extends TwitterTask<Status[]> {

    // ------------------------------ FIELDS ------------------------------

    private final Activity activity;
    private final Paging paging;

    // --------------------------- CONSTRUCTORS ---------------------------

    protected MentionsTimelineTask(Twitter twitter, Activity activity) {
        this(twitter, activity, null);
    }

    public MentionsTimelineTask(Twitter twitter, Activity activity, Paging paging) {
        super(twitter);
        this.activity = activity;
        this.paging = paging;
    }

    // ------------------------ OVERRIDE METHODS ------------------------

    @Override
    protected void onPostExecute(twitter4j.Status[] statuses) {
        if (statuses.length != 0) {
            for (twitter4j.Status status : statuses) {
                StatusCache.getInstance().put(status);
                FavoriteCache.getInstance().put(status);
            }
        }
    }

    @Override
    protected twitter4j.Status[] doInBackground(Void... params) {
        ResponseList<twitter4j.Status> responseList;
        try {
            if (paging == null) {
                responseList = twitter.timelines().getMentionsTimeline();
            } else {
                responseList = twitter.timelines().getMentionsTimeline(paging);
            }
        } catch (TwitterException e) {
            e.printStackTrace();
            Logger.error(e.toString());
            if (e.exceededRateLimitation()) {
                Notificator.publish(activity, R.string.notice_error_rate_limit, NotificationType.ALERT);
            } else {
                Notificator.publish(activity, R.string.notice_error_get_mentions, NotificationType.ALERT);
            }
            return new twitter4j.Status[0];
        }
        return responseList.toArray(new twitter4j.Status[responseList.size()]);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textSize="16sp"
        tools:text="sc item 0" />

</RelativeLayout>


text:
<?php

class Fizzy_Resource_Sabredav extends Zend_Application_Resource_ResourceAbstract
{

    public function init()
    {
        $options = $this->getOptions();

        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->pushAutoloader(array($this, 'autoload'));
    }

    public static function autoload($className)
    {
        if(strpos($className,'Sabre_')===0) {
            include str_replace('_','/',$className) . '.php';
        }
    }

}


text:
"""
Simple version string management for git
"""

__license__ = """
Copyright (c) 2013-2014 Manuel Bua.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""

__author__ = "Manuel Bua"

try:
    from version import gitver_version
    __version__ = gitver_version
except ImportError:
    __version__ = 'UNKNOWN'


text:
// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
//     http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.

package operations

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"
	"time"

	"golang.org/x/net/context"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"

	strfmt "github.com/go-openapi/strfmt"
)

// NewListTasksParams creates a new ListTasksParams object
// with the default values initialized.
func NewListTasksParams() *ListTasksParams {
	var ()
	return &ListTasksParams{

		timeout: cr.DefaultTimeout,
	}
}

// NewListTasksParamsWithTimeout creates a new ListTasksParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewListTasksParamsWithTimeout(timeout time.Duration) *ListTasksParams {
	var ()
	return &ListTasksParams{

		timeout: timeout,
	}
}

// NewListTasksParamsWithContext creates a new ListTasksParams object
// with the default values initialized, and the ability to set a context for a request
func NewListTasksParamsWithContext(ctx context.Context) *ListTasksParams {
	var ()
	return &ListTasksParams{

		Context: ctx,
	}
}

/*ListTasksParams contains all the parameters to send to the API endpoint
for the list tasks operation typically these are written to a http.Request
*/
type ListTasksParams struct {

	/*Cluster
	  Cluster name or ARN to filter tasks by

	*/
	Cluster *string
	/*Status
	  Status to filter tasks by

	*/
	Status *string

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithTimeout adds the timeout to the list tasks params
func (o *ListTasksParams) WithTimeout(timeout time.Duration) *ListTasksParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the list tasks params
func (o *ListTasksParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the list tasks params
func (o *ListTasksParams) WithContext(ctx context.Context) *ListTasksParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the list tasks params
func (o *ListTasksParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithCluster adds the cluster to the list tasks params
func (o *ListTasksParams) WithCluster(cluster *string) *ListTasksParams {
	o.SetCluster(cluster)
	return o
}

// SetCluster adds the cluster to the list tasks params
func (o *ListTasksParams) SetCluster(cluster *string) {
	o.Cluster = cluster
}

// WithStatus adds the status to the list tasks params
func (o *ListTasksParams) WithStatus(status *string) *ListTasksParams {
	o.SetStatus(status)
	return o
}

// SetStatus adds the status to the list tasks params
func (o *ListTasksParams) SetStatus(status *string) {
	o.Status = status
}

// WriteToRequest writes these params to a swagger request
func (o *ListTasksParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	r.SetTimeout(o.timeout)
	var res []error

	if o.Cluster != nil {

		// query param cluster
		var qrCluster string
		if o.Cluster != nil {
			qrCluster = *o.Cluster
		}
		qCluster := qrCluster
		if qCluster != "" {
			if err := r.SetQueryParam("cluster", qCluster); err != nil {
				return err
			}
		}

	}

	if o.Status != nil {

		// query param status
		var qrStatus string
		if o.Status != nil {
			qrStatus = *o.Status
		}
		qStatus := qrStatus
		if qStatus != "" {
			if err := r.SetQueryParam("status", qStatus); err != nil {
				return err
			}
		}

	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
<!DOCTYPE html>

		<meta charset="utf-8"> <meta http-equiv="Refresh" content="3600" />
		<title>I2P Reseed in Yggdrasil.</title>

Number of Yggdrasil routers in the I2P network.

Data from the current reseed. Updated hourly.

99


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Spark.CSharp.Network;
using NUnit.Framework;

namespace AdapterTest
{
    [TestFixture]
    public class ByteBufPoolTest
    {
        private ByteBufPool bufPool;
        private ByteBufPool unsafeBufPool;

        [OneTimeSetUp]
        public void CreatePooledBuffer()
        {
            bufPool = new ByteBufPool(1024, ByteBufPool.DefaultChunkOrder, false);
            if (SocketFactory.IsRioSockSupported())
            {
                unsafeBufPool = new ByteBufPool(1024, ByteBufPool.DefaultChunkOrder, true);
            }
        }

        [Test]
        public void TestManagedBufferAllocate()
        {
            var byteBuf = bufPool.Allocate();
            var bufChunk = byteBuf.ByteBufChunk;
            Assert.AreEqual(bufChunk.FreeBytes, bufChunk.Size - byteBuf.Capacity);
            byteBuf.Release();
            Assert.AreEqual(bufChunk.FreeBytes, bufChunk.Size);
        }

        [Test]
        public void TestManagedBufferPoolGrow()
        {
            // Verify no chunks in 100% usage queue at beginning.
            var chunkNumbers = bufPool.GetUsages();
            Assert.AreEqual(0, chunkNumbers[5]); // The number of chunks in 100% usage queue should be 0 at beginning.

            var bufs = new List<ByteBuf>();
            for (var i = 0; i < 257; i++)
            {
                var byteBuf = bufPool.Allocate();
                bufs.Add(byteBuf);
            }

            var firstChunk = bufs[255].ByteBufChunk;
            var secondChunk = bufs[256].ByteBufChunk;

            // Verify the buffer pool got grown.
            Assert.AreNotSame(firstChunk, secondChunk);
            // Verify the usage of the first buffer chunk
            Assert.AreEqual(firstChunk.Usage, 100);
            // Verify the usage of the second buffer chunk
            Assert.AreEqual(secondChunk.Usage, 1);
            // Verify the chunk exhaust and should be in 100% usage queue now.
            chunkNumbers = bufPool.GetUsages();
            Assert.AreNotEqual(0, chunkNumbers[5]); // The number of chunks in 100% usage queue should not be 0 now.
            // Verify the ToString() shows as usage string.
            var usageStr = bufPool.ToString();
            Assert.IsTrue(usageStr.StartsWith("Chunk(s) at 0~25%"));

            // Release buffers back to pool.
            foreach (var byteBuf in bufs)
            {
                byteBuf.Release();
            }

            // Verify the first buffer chunk is disposed.
            Assert.IsTrue(firstChunk.IsDisposed);
            // Verify the usage of the second buffer chunk is 0.
            Assert.AreEqual(secondChunk.Usage, 0);
        }

        [Test]
        public void TestUnsafeBufferAllocate()
        {
            if (!SocketFactory.IsRioSockSupported())
            {
                Assert.Ignore("Omitting due to missing Riosock.dll. It might caused by no VC++ build tool or running on an OS that not supports Windows RIO socket.");
            }

            var byteBuf = unsafeBufPool.Allocate();
            var bufChunk = byteBuf.ByteBufChunk;
            Assert.AreNotEqual(IntPtr.Zero, bufChunk.UnsafeArray);
            Assert.AreNotEqual(bufChunk.BufId, IntPtr.Zero);
            Assert.AreEqual(bufChunk.FreeBytes, bufChunk.Size - byteBuf.Capacity);

            // Verify GetInputRioBuf()
            var inputRioBuf = byteBuf.GetInputRioBuf();
            Assert.AreNotEqual(null, inputRioBuf);
            Assert.AreEqual(byteBuf.WritableBytes, inputRioBuf.Length);

            // Verify GetOutputRioBuf()
            const string writeStr = "Write bytes to ByteBuf.";
            var writeBytes = Encoding.UTF8.GetBytes(writeStr);
            byteBuf.WriteBytes(writeBytes, 0, writeBytes.Length);
            var outputRioBuf = byteBuf.GetOutputRioBuf();
            Assert.AreNotEqual(null, outputRioBuf);
            Assert.AreEqual(byteBuf.ReadableBytes, outputRioBuf.Length);

            byteBuf.Release();
            Assert.AreEqual(bufChunk.FreeBytes, bufChunk.Size);
        }

        [Test]
        public void TestUnsafeBufferPoolGrow()
        {
            if (!SocketFactory.IsRioSockSupported())
            {
                Assert.Ignore("Omitting due to missing Riosock.dll. It might caused by no VC++ build tool or running on an OS that not supports Windows RIO socket.");
            }

            var bufs = new List<ByteBuf>();
            for (var i = 0; i < 257; i++)
            {
                var byteBuf = unsafeBufPool.Allocate();
                bufs.Add(byteBuf);
            }

            var firstChunk = bufs[255].ByteBufChunk;
            var secondChunk = bufs[256].ByteBufChunk;

            // Verify the buffer pool got grown.
            Assert.AreNotSame(firstChunk, secondChunk);
            Assert.AreNotEqual(firstChunk.BufId, secondChunk.BufId);
            // Verify the usage of the first buffer chunk
            Assert.AreEqual(firstChunk.Usage, 100);
            // Verify the usage of the second buffer chunk
            Assert.AreEqual(secondChunk.Usage, 1);

            // Release buffers back to pool.
            foreach (var byteBuf in bufs)
            {
                byteBuf.Release();
            }

            // Verify the first buffer chunk is disposed.
            Assert.IsTrue(firstChunk.IsDisposed);
            // Verify the usage of the second buffer chunk is 0.
            Assert.AreEqual(secondChunk.Usage, 0);
        }

        [Test]
        public void TestInvalidBufPool()
        {
            // Verify to new a ByteBufPool with a bigger chunkOrder which valid value is 0-14.
            Assert.Throws<ArgumentException>(() => new ByteBufPool(1024, 15, false));
            // Verify to new a ByteBugPool with a larger segment size to hit overflow of ByteBufChunk size.
            Assert.Throws<ArgumentException>(() => new ByteBufPool(int.MaxValue, 8, false));
        }
    }
}


text:
<?php

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class OrdersControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');
    }

    public function testAdd()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/add');
    }

    public function testEdit()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/edit/{id}');
    }

    public function testRemove()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/remove/{id}');
    }

    public function testSend()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/send/{id}');
    }

}


text:
package de.aw3s.btDiary.validation;

public interface Violation<T> {

    String getPropertyName();
    T getOffender();
    ViolationType getType();

}


text:
#ifndef __NGEN_DELEGATE_HPP
#define __NGEN_DELEGATE_HPP

#include "Ngen.Typedefs.hpp"
#include "Ngen.Cast.hpp"

namespace Ngen {
	/** @brief A data structure that represents the reference to a function.
	*/
   class Delegate {
   public:
		/** @brief De-constructor. */
      virtual ~Delegate() {}

		/** @brief Determines if the Delegate is equal-to another delegate. */
      virtual bool EqualTo(Delegate* rhs) const pure;

		/** @brief operator()(unknown, unknown*). */
      virtual unknown operator()(unknown _this, unknown* params) pure;

		/** @brief Determines if the delegate references a constant-member function. */
      virtual bool IsConst() const pure;

		/** @brief Determines if the delegate references a member function. */
      virtual bool IsMember() const pure;

		/** @brief Determines if the delegate references a non-void function. */
      virtual bool IsNonVoid() const pure;

		/** @brief Invokes the function being referenced by the delegate. */
      template<typename TOwner, typename TReturn, typename... TParams>
      TReturn Call(TOwner* _this, TParams... params) {
      	unknown ret = 0;
			unknown args[sizeof...(TParams)] {
				(Cast<TParams>::To(params))...
			};

      	if(this->IsNonVoid()) {
				ret = this->operator()(Cast<TOwner*>::To(_this), args);
      	} else {
				this->operator()(Cast<TOwner*>::To(_this), args);
      	}

			return Cast<TReturn>::From(ret);
		}
   };

   template<typename TReturn, typename... TParams>
   class NonVoidDelegate : public Delegate {
   public:
      virtual ~NonVoidDelegate() {}
      virtual TReturn Call(TParams... params) pure;
      bool IsNonVoid() const { return true; };
   };

   template<typename... TParams>
   class VoidDelegate : public Delegate {
   public:
      virtual ~VoidDelegate() {}
      virtual void Call(TParams... params) pure;
      bool IsNonVoid() const { return false; };
   };
}

#endif // __NGEN_DELEGATE_HPP


text:
import unittest
import tests.envs as envs
import pykintone

class TestApp(unittest.TestCase):

    def test_select(self):
        app = pykintone.load(envs.FILE_PATH).app()
        result = app.select()
        self.assertTrue(result.ok)
        self.assertTrue(len(result.records) > 0)

        record_id = result.records[0]["$id"]["value"]
        result = app.get(record_id)
        self.assertTrue(result.ok)
        print(result.record)

    def test_single(self):
        app = pykintone.load(envs.FILE_PATH).app()

        record = {
            "my_key": {
                "value": "test0"
            },
            "radio": {
                "value": "radio1"
            }
        }

        # create
        result = app.create(record)
        self.assertTrue(result.ok)

        record_id = result.record_id
        first_revision = result.revision
        created = app.get(record_id)
        self.assertTrue(created.ok)

        # update
        update = {
            "$id": {
                "value": record_id
            },
            "$revision": {
                "value": result.revision
            },
            "radio": {
                "value": "radio2"
            }
        }
        result = app.update(update)
        self.assertTrue(result.ok)
        self.assertTrue(first_revision < result.revision)
        updated = app.get(record_id).record
        self.assertTrue("redio2", updated["radio"]["value"])

        # delete
        result = app.delete(record_id)
        self.assertTrue(result.ok)

    def test_batch(self):
        app = pykintone.load(envs.FILE_PATH).app()

        records = [
            {
                "my_key": {
                    "value": "test_m0"
                },
                "radio": {
                    "value": "radio1"
                }
            },
            {
                "my_key": {
                    "value": "test_m1"
                },
                "radio": {
                    "value": "radio2"
                }
            }
        ]

        # create
        result = app.batch_create(records)
        self.assertTrue(result.ok)

        record_keys = result.keys
        ids = [str(k.record_id) for k in record_keys]
        query = "レコード番号 in ({0})".format(",".join(ids))
        created = app.select(query)
        self.assertTrue(created.ok)

        # update
        updates = [
            {
                "$id": {
                    "value": record_keys[0].record_id
                },
                "$revision": {
                    "value": record_keys[0].revision
                },
                "radio": {
                    "value": "radio2"
                }
            },
            {
                "$id": {
                    "value": record_keys[1].record_id
                },
                "$revision": {
                    "value": record_keys[1].revision
                },
                "radio": {
                    "value": "radio1"
                }
            }
        ]
        result = app.batch_update(updates)
        self.assertTrue(result.ok)
        for r in result.keys:
            prev = [k for k in record_keys if k.record_id == r.record_id]
            self.assertTrue(len(prev) == 1)
            self.assertTrue(prev[0].revision < r.revision)

        # delete
        result = app.delete(ids)
        self.assertTrue(result.ok)

    def test_error(self):
        app = pykintone.load(envs.FILE_PATH).app()

        record = {
            "radio": {
                "value": "xxxxx"
            }
        }

        # create (will be error)
        result = app.create(record)
        self.assertFalse(result.ok)

    def test_process(self):
        app = pykintone.load(envs.FILE_PATH).app()
        record = {
            "my_key": {
                "value": "test_process"
            }
        }

        for c in ("single", "multiple"):
            created_id = app.create(record).record_id
            created = app.get(created_id).record
            if c == "single":
                proceeded = app.proceed(created, "処理開始")
            else:
                proceeded = app.batch_proceed([created], "処理開始")
        app.delete(created_id)  # delete record
        self.assertTrue(proceeded.ok)

    def test_options(self):
        app = pykintone.load(envs.FILE_PATH).app()
        app.requests_options = {
            "verify": True
        }
        result = app.select()
        self.assertTrue(result.ok)
        self.assertTrue(len(result.records) > 0)


text:
var debug = require('debug')('bauhaus:content'),
    async = require('async'),
    View = require('express/lib/view'),
    Content = require('./model/content'),
    populateConfig = require('../document/helper').populateConfig,
    ejsFilters = require('./ejsFilters');

var middleware = module.exports = {};
/**
 * Generates middleware which adds content types to request
 * @param  {Array}   contentTypes List of content types from service content.types
 * @return {Function}             Middleware function
 */
middleware.loadContentTypes = function (contentTypes) {
    var loadContentTypes = function loadContentTypes (req, res, next) {
        if (!req.bauhaus || !req.bauhaus.content) return next();

        req.bauhaus.content.types = contentTypes;
        debug('Loaded Content Types', Object.keys(contentTypes));
        next();
    };
    return loadContentTypes;
};

/**
 * Middleware which loads contents for loaded page to req.bauhaus.content.data
 */
middleware.loadContent = function (contentTypes) {
    return function loadContent (req, res, next) {
        if (!req.bauhaus || !req.bauhaus.page) return next();

        Content.find({'_page': req.bauhaus.page._id }, 'content meta _type', function (err, contents) {
            if (err || contents.length === 0) return next();

            debug("Loaded " + contents.length + " content blocks");

            var populateParallel = [];
            for (var c in contents) {
                var contentType = contentTypes[ contents[c]._type ];
                var populationConfig = populateConfig(contentType, 'content.');
                // Add callback in Closure
                (function (content, config) {
                    populateParallel.push(function (callback) {
                        content.populate(config, callback);
                    });
                })(contents[c], populationConfig);
            }
            // Perform parallel population on all documents (documents are checked for references,
            // if there are any, there are populated)
            async.parallel(populateParallel, function (err, result) {
                if (err) return next();

                req.bauhaus.content = {
                    data: result
                };
                next();
            });
        });
    }
};

/**
 * Returns middleware function, which renders content from Array.<Object>
 * req.bauhaus.content.data according to the passed content types to
 * Array.<String> req.bauhaus.content.rendered.
 *
 * @param  {Array} contentTypes Pass service content.types
 * @return {Function}           Middleware
 */
middleware.renderContent = function (contentTypes) {
    return function renderContent (req, res, next) {
        if (!req.bauhaus || !req.bauhaus.content) return next();

        req.bauhaus.content.rendered = [];
        var renderParallel = [];
        for (var c in req.bauhaus.content.data) {
            var data = req.bauhaus.content.data[c];

            // add additional information to template
            if(data.content == null)
                data.content = {};
            data.content.user = null;
            if(req.user != null){
                data.content.user = {};
                data.content.user.username = req.user.username;
                data.content.user._id = req.user._id;
                data.content.user.fields = req.user.fields;
            }

            var typeName = data._type;
            if (typeName in contentTypes) {
                var contentType = contentTypes[typeName];
                if (typeof contentType.render === 'function') {
                    (function (data, contentType) {
                        renderParallel.push(function (callback) {
                            contentType.render(req, res, data, contentType.template, function (err, html) {
                                if (err) debug("Error when calling custom render method of content " + data._id + " of type " + typeName, err);
                                callback(err, html);
                            });
                        });
                    })(data, contentType);
                } else {
                    // Add callback in closure
                    (function (data, template, res) {
                        renderParallel.push(function (callback) {
                            res.render(template, data, function (err, html) {
                                if (err) debug("Error rendering content", data, err);
                                callback(err, html);
                            });
                        });
                    })(data.content, contentType.template, res);
                }
            }
        }

        async.parallel(renderParallel, function (err, result) {
            if (err) return next();

            req.bauhaus.content.rendered = result;

            debug("Rendered " + result.length + " content elements");
            next();
        });
    };
};


text:
package com.siyeh.ipp.trivialif;

import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiIfStatement;
import com.intellij.psi.PsiJavaToken;
import com.intellij.psi.PsiStatement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import com.siyeh.ipp.base.Intention;
import com.siyeh.ipp.base.PsiElementPredicate;

public class MergeIfOrIntention extends Intention {

  @Nonnull
  public PsiElementPredicate getElementPredicate() {
    return new MergeIfOrPredicate();
  }

  public void processIntention(PsiElement element)
    throws IncorrectOperationException {
    final PsiJavaToken token = (PsiJavaToken)element;
    if (MergeIfOrPredicate.isMergableExplicitIf(token)) {
      replaceMergeableExplicitIf(token);
    }
    else {
      replaceMergeableImplicitIf(token);
    }
  }

  private static void replaceMergeableExplicitIf(PsiJavaToken token)
    throws IncorrectOperationException {
    final PsiIfStatement parentStatement =
      (PsiIfStatement)token.getParent();
    assert parentStatement != null;
    final PsiIfStatement childStatement =
      (PsiIfStatement)parentStatement.getElseBranch();
    if (childStatement == null) {
      return;
    }
    final PsiExpression childCondition = childStatement.getCondition();
    if (childCondition == null) {
      return;
    }
    final String childConditionText;
    if (ParenthesesUtils.getPrecedence(childCondition)
        > ParenthesesUtils.OR_PRECEDENCE) {
      childConditionText = '(' + childCondition.getText() + ')';
    }
    else {
      childConditionText = childCondition.getText();
    }
    final PsiExpression condition = parentStatement.getCondition();
    if (condition == null) {
      return;
    }
    final String parentConditionText;
    if (ParenthesesUtils.getPrecedence(condition)
        > ParenthesesUtils.OR_PRECEDENCE) {
      parentConditionText = '(' + condition.getText() + ')';
    }
    else {
      parentConditionText = condition.getText();
    }
    final PsiStatement parentThenBranch = parentStatement.getThenBranch();
    if (parentThenBranch == null) {
      return;
    }
    final String parentThenBranchText = parentThenBranch.getText();
    @NonNls final StringBuilder statement = new StringBuilder();
    statement.append("if(");
    statement.append(parentConditionText);
    statement.append("||");
    statement.append(childConditionText);
    statement.append(')');
    statement.append(parentThenBranchText);
    final PsiStatement childElseBranch = childStatement.getElseBranch();
    if (childElseBranch != null) {
      final String childElseBranchText = childElseBranch.getText();
      statement.append("else ");
      statement.append(childElseBranchText);
    }
    final String newStatement = statement.toString();
    replaceStatement(newStatement, parentStatement);
  }

  private static void replaceMergeableImplicitIf(PsiJavaToken token)
    throws IncorrectOperationException {
    final PsiIfStatement parentStatement =
      (PsiIfStatement)token.getParent();
    final PsiIfStatement childStatement =
      (PsiIfStatement)PsiTreeUtil.skipSiblingsForward(parentStatement,
                                                      PsiWhiteSpace.class);
    assert childStatement != null;
    final PsiExpression childCondition = childStatement.getCondition();
    if (childCondition == null) {
      return;
    }
    final String childConditionText;
    if (ParenthesesUtils.getPrecedence(childCondition)
        > ParenthesesUtils.OR_PRECEDENCE) {
      childConditionText = '(' + childCondition.getText() + ')';
    }
    else {
      childConditionText = childCondition.getText();
    }
    assert parentStatement != null;
    final PsiExpression condition = parentStatement.getCondition();
    if (condition == null) {
      return;
    }
    final String parentConditionText;
    if (ParenthesesUtils.getPrecedence(condition)
        > ParenthesesUtils.OR_PRECEDENCE) {
      parentConditionText = '(' + condition.getText() + ')';
    }
    else {
      parentConditionText = condition.getText();
    }
    final PsiStatement parentThenBranch = parentStatement.getThenBranch();
    if (parentThenBranch == null) {
      return;
    }
    final StringBuilder newStatement = new StringBuilder();
    newStatement.append("if(");
    newStatement.append(parentConditionText);
    newStatement.append("||");
    newStatement.append(childConditionText);
    newStatement.append(')');
    newStatement.append(parentThenBranch.getText());
    final PsiStatement childElseBranch = childStatement.getElseBranch();
    if (childElseBranch != null) {
      newStatement.append("else ");
      newStatement.append(childElseBranch.getText());
    }
    replaceStatement(newStatement.toString(), parentStatement);
    childStatement.delete();
  }
}


text:
namespace blink {

// This class should only be used from inside the accessibility directory.
class AXRelationCache {
  USING_FAST_MALLOC(AXRelationCache);

 public:
  explicit AXRelationCache(AXObjectCacheImpl*);

  AXRelationCache(const AXRelationCache&) = delete;
  AXRelationCache& operator=(const AXRelationCache&) = delete;

  virtual ~AXRelationCache();

  //
  // Safe to call at any time. Doesn't make any changes to the tree.
  //

  // Returns true if the given object's position in the tree was due to
  // aria-owns.
  bool IsAriaOwned(AXID) const;
  bool IsAriaOwned(const AXObject*) const;

  // Returns the parent of the given object due to aria-owns, if valid,
  // otherwise, removes the child from maps indicating that it is owned.
  AXObject* ValidatedAriaOwner(const AXObject*);

  // Returns the validated owned children of this element with aria-owns.
  // Any children that are no longer valid are removed from maps indicating they
  // are owned.
  void ValidatedAriaOwnedChildren(const AXObject* owner,
                                  HeapVector<Member<AXObject>>& owned_children);

  // Return true if any label ever pointed to the element via the for attribute.
  bool MayHaveHTMLLabelViaForAttribute(const HTMLElement&);

  // Given an element in the DOM tree that was either just added or whose id
  // just changed, check to see if another object wants to be its parent due to
  // aria-owns. If so, add it to a queue of ids to process later during
  // ProcessUpdatesWithCleanLayout.
  // |node| is not optional.
  // |obj| is optional. If provided, it must match the AXObject for |node|.
  void UpdateRelatedTree(Node* node, AXObject* obj);

  // Remove given AXID from cache.
  void RemoveAXID(AXID);

  // The child cannot be owned, either because the child was removed or the
  // relation was invalid, so remove from all relevant mappings.
  void RemoveOwnedRelation(AXID);

  // Update map of ids to related objects.
  // If one or more ids aren't found, they're added to a lookup table so that if
  // an element with that id appears later, it can be added when you call
  // UpdateRelatedTree.
  void UpdateReverseRelations(HashMap<String, HashSet<AXID>>& id_to_axid_map,
                              const AXObject* relation_source,
                              const Vector<String>& target_ids);
  // Update map of ids to related objects for aria-labelledby/aria-describedby.
  void UpdateReverseTextRelations(const AXObject* relation_source,
                                  const Vector<String>& target_ids);

  // Called when the "for" attribute of a label element changes and the
  // reverse mapping needs to be updated.
  void LabelChanged(Node*);

  //
  // Only called when layout is clean, in the kInAccessibility lifecycle
  // stage.
  //

  // Called once towards the end of the kInAccessibility lifecycle stage.
  // Iterates over a list of ququed nodes that may require changes to their
  // set of owned children and calls UpdateAriaOwnsWithCleanLayout on each
  // of them.
  void ProcessUpdatesWithCleanLayout();

  // Determines the set of child nodes that this object owns due to aria-owns
  // (fully validating that the ownership is legal and free of cycles).
  // If that differs from the previously cached set of owned children,
  // calls ChildrenChanged on all affected nodes (old and new parents).
  // This affects the tree, which is why it should only be called at a
  // specific time in the lifecycle.
  // Pass |force=true| when the mappings must be updated even though the
  // owned ids have not changed, e.g. when an object has been refreshed.
  void UpdateAriaOwnsWithCleanLayout(AXObject* owner, bool force = false);

  // Is there work to be done when layout becomes clean?
  bool IsDirty() const;

  static bool IsValidOwner(AXObject* owner);
  static bool IsValidOwnedChild(AXObject* child);

 private:
  // Returns the parent of the given object due to aria-owns.
  AXObject* GetAriaOwnedParent(const AXObject*) const;

  // Given an object that has explicitly set elements for aria-owns, update the
  // internal state to reflect the new set of children owned by this object.
  // Note that |owned_children| will be the AXObjects corresponding to the
  // elements in |attr_associated_elements|. These elements are validated -
  // exist in the DOM, and are a descendant of a shadow including ancestor.
  void UpdateAriaOwnsFromAttrAssociatedElementsWithCleanLayout(
      AXObject* owner,
      const HeapVector<Member<Element>>& attr_associated_elements,
      HeapVector<Member<AXObject>>& owned_children,
      bool force);

  // If any object is related to this object via <label for>, aria-owns,
  // aria-describedby or aria-labeledby, update the text for the related object.
  void UpdateRelatedText(Node*);

  bool IsValidOwnsRelation(AXObject* owner, AXObject* child) const;
  void UnmapOwnedChildrenWithCleanLayout(const AXObject* owner,
                                         const Vector<AXID>& removed_child_ids,
                                         const Vector<AXID>& newly_owned_ids);

  void MapOwnedChildrenWithCleanLayout(const AXObject* owner,
                                       const Vector<AXID>&);
  void GetReverseRelated(Node*,
                         HashMap<String, HashSet<AXID>>& id_attr_to_axid_map,
                         HeapVector<Member<AXObject>>& sources);
  void MaybeRestoreParentOfOwnedChild(AXObject* removed_child);

  // Updates |aria_owner_to_children_mapping_| after calling UpdateAriaOwns for
  // either the content attribute or the attr associated elements.
  void UpdateAriaOwnerToChildrenMappingWithCleanLayout(
      AXObject* owner,
      HeapVector<Member<AXObject>>& validated_owned_children_result,
      bool force);

  // Whether the document has been scanned for initial relationships
  // first or not.
  bool initialized_ = false;

  WeakPersistent<AXObjectCacheImpl> object_cache_;

  // Map from the AXID of the owner to the AXIDs of the children.
  // This is a validated map, it doesn't contain illegal, duplicate,
  // or cyclical matches, or references to IDs that don't exist.
  HashMap<AXID, Vector<AXID>> aria_owner_to_children_mapping_;

  // Map from the AXID of a child to the AXID of the parent that owns it.
  HashMap<AXID, AXID> aria_owned_child_to_owner_mapping_;

  // Reverse relation maps from an ID (the ID attribute of a DOM element) to the
  // set of elements that at some time pointed to that ID via aria-owns,
  // aria-labelledby or aria-desribedby. This is *unvalidated*, it includes
  // possible extras and duplicates.
  // This is used so that:
  // - When an element with an ID is added to the tree or changes its ID, we can
  //   quickly determine if it affects an aria-owns relationship.
  // - When text changes, we can recompute any label or description based on it
  //   and fire the appropriate change events.
  HashMap<String, HashSet<AXID>> id_attr_to_owns_relation_mapping_;
  HashMap<String, HashSet<AXID>> id_attr_to_text_relation_mapping_;

  // HTML id attributes that at one time havehad a <label for> pointing to it.
  // IDs are not necessarily removed from this set. It is not necessary to
  // remove IDs as false positives are ok. Being able to determine that a
  // labelable element has never had an associated label allows the accessible
  // name calculation to be optimized.
  HashSet<AtomicString> all_previously_seen_label_target_ids_;

  // A set of IDs that need to be updated during the kInAccessibility
  // lifecycle phase. For each of these, the new set of owned children
  // will be computed, and if it's different than before, ChildrenChanged
  // will be fired on all affected nodes.
  HashSet<AXID> owner_ids_to_update_;

  // Helpers that call back into object cache
  AXObject* ObjectFromAXID(AXID) const;
  AXObject* GetOrCreate(Node*, const AXObject* owner);
  AXObject* Get(Node*);
  void ChildrenChanged(AXObject*);

  // Do an initial scan of the document to find any relationships.
  // We'll catch any subsequent ones when attributes change.
  void DoInitialDocumentScan();
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_RELATION_CACHE_H_


text:
import yaml

class Config:
	def __init__(self, cdict):
		attrs = set(self.attrs) # copy and "unfreeze"
		for k, v in cdict.items():
			attrs.remove(k) # check if the key is allowed, mark it as present
			setattr(self, k, v)
		if len(attrs) != 0:
			raise KeyError('missing required bot config keys: %s' % attrs)

class WebConfig(Config):
	attrs = frozenset([
		'port',
		'host',
		'cookie_secret',
		'github_client_id',
		'github_client_secret',
		'mailgun_api_key',
		'debug',
	])

class DBConfig(Config):
	attrs = frozenset([
		'user',
		'database',
	])

__doc = yaml.load(open('config.yaml', 'r'))
web = WebConfig(__doc['web'])
db = DBConfig(__doc['db'])


text: <!DOCTYPE html>