text:
// портирован
var Schema = storage.Schema
  , utils = storage.utils
  , random = utils.random;

var EmbeddedDocument = storage.Types.Embedded
  , DocumentArray = storage.Types.DocumentArray
  , SchemaType = storage.SchemaType
  , ValidationError = storage.Error.ValidationError;

/**
 * Setup.
 */

function Dummy () {
  storage.Document.call(this, {});
}
Dummy.prototype = Object.create( storage.Document.prototype );
Dummy.prototype.constructor = Dummy;

Dummy.prototype.$__setSchema(new Schema());

function Subdocument () {
  var arr = new DocumentArray();
  arr._path = 'jsconf.ar';
  arr._parent = new Dummy();
  arr[0] = this;
  EmbeddedDocument.call(this, {}, arr);
}

/**
 * Inherits from EmbeddedDocument.
 */
Subdocument.prototype = Object.create( EmbeddedDocument.prototype );
Subdocument.prototype.constructor = Subdocument;

/**
 * Set schema.
 */

Subdocument.prototype.$__setSchema(new Schema({
    test: { type: String, required: true }
  , work: { type: String, validate: /^good/ }
}));

/**
 * Schema.
 */

var RatingSchema = new Schema({
    stars: Number
  , description: { source: { url: String, time: Date }}
});

var MovieSchema = new Schema({
    title: String
  , ratings: [RatingSchema]
});

storage.createCollection('Movie', MovieSchema);

/**
 * Test.
 */

describe('types.document', function(){

  it('test that save fires errors', function(done){
    var a = new Subdocument();
    a.set('test', '');
    a.set('work', 'nope');

    a.validate(function(){
      assert.ok(a.__parent.$__.validationError instanceof ValidationError);
      assert.equal(a.__parent.errors['jsconf.ar.0.work'].name, 'ValidatorError');

      assert.equal(a.__parent.errors['jsconf.ar.0.work'].message, 'Validator failed for path `work` with value `nope`');
      assert.equal(a.__parent.errors['jsconf.ar.0.test'].message, 'Path `test` is required.');
      done();
    });
  });

  it('objects can be passed to #set', function (done) {
    var a = new Subdocument();
    a.set({ test: 'paradiddle', work: 'good flam'});
    assert.equal(a.test, 'paradiddle');
    assert.equal(a.work, 'good flam');
    done();
  });

  it('Subdocuments can be passed to #set', function (done) {
    var a = new Subdocument();
    a.set({ test: 'paradiddle', work: 'good flam'});
    assert.equal(a.test, 'paradiddle');
    assert.equal(a.work, 'good flam');
    var b = new Subdocument();
    b.set(a);
    assert.equal(b.test, 'paradiddle');
    assert.equal(b.work, 'good flam');
    done();
  });

  it('cached _ids', function (done) {
    var Movie = storage.createCollection('Movie');
    var m = Movie.add();

    assert.equal(m.id, m.$__._id);
    var old = m.id;
    m._id = new storage.Types.ObjectId();
    assert.equal(m.id, m.$__._id);
    assert.strictEqual(true, old !== m.$__._id);

    var m2= Movie.add();
    delete m2._doc._id;
    m2.init({ _id: new storage.Types.ObjectId() });
    assert.equal(m2.id, m2.$__._id);
    assert.strictEqual(true, m.$__._id !== m2.$__._id);
    assert.strictEqual(true, m.id !== m2.id);
    assert.strictEqual(true, m.$__._id !== m2.$__._id);
    done();
  });

  it('Subdocument#remove (gh-531)', function (done) {
    var Movie = storage.createCollection('Movie');

    var super8 = Movie.add({ title: 'Super 8' });

    var id1 = '4e3d5fc7da5d7eb635063c96';
    var id2 = '4e3d5fc7da5d7eb635063c97';
    var id3 = '4e3d5fc7da5d7eb635063c98';
    var id4 = '4e3d5fc7da5d7eb635063c99';

    super8.ratings.push({ stars: 9, _id: id1 });
    super8.ratings.push({ stars: 8, _id: id2 });
    super8.ratings.push({ stars: 7, _id: id3 });
    super8.ratings.push({ stars: 6, _id: id4 });

    super8.save(function ( movieObj ) {
      assert.equal(movieObj.title, 'Super 8');
      assert.equal(movieObj.ratings[0].stars.valueOf(), 9);
      assert.equal(movieObj.ratings[1].stars.valueOf(), 8);
      assert.equal(movieObj.ratings[2].stars.valueOf(), 7);
      assert.equal(movieObj.ratings[3].stars.valueOf(), 6);

      super8.ratings.id(id1).stars = 5;
      super8.ratings.id(id2).remove();
      super8.ratings.id(id3).stars = 4;
      super8.ratings.id(id4).stars = 3;

      super8.save(function ( movieObj1 ) {
        assert.equal(movieObj1.title, undefined);
        assert.equal(movieObj1.ratings.length,3);
        assert.equal(movieObj1.ratings[0].stars.valueOf(), 5);
        assert.equal(movieObj1.ratings[1].stars.valueOf(), 4);
        assert.equal(movieObj1.ratings[2].stars.valueOf(), 3);

        super8.ratings.id(id1).stars = 2;
        super8.ratings.id(id3).remove();
        super8.ratings.id(id4).stars = 1;

        super8.save(function ( movieObj2 ) {
          assert.equal(movieObj2.ratings.length,2);
          assert.equal(movieObj2.ratings[0].stars.valueOf(), 2);
          assert.equal(movieObj2.ratings[1].stars.valueOf(), 1);

          // gh-531
          super8.ratings[0].remove();
          super8.ratings[0].remove();

          super8.save(function ( movieObj3 ) {
            assert.equal(0, movieObj3.ratings.length);
            done();
          });
        });
      });
    });
  });

  describe('setting nested objects', function(){
    it('works (gh-1394)', function(done){
      var Movie = storage.createCollection('Movie');

      var LifeOfPi = Movie.add({
        title: 'Life of Pi',
        ratings: [{
          description: {
            source: {
              url: 'http://www.imdb.com/title/tt0454876/',
              time: new Date()
            }
          }
        }]
      });

      LifeOfPi.save(function ( movieObj ) {
        assert.ok( movieObj.ratings[0].description.source.time instanceof Date );
        LifeOfPi.ratings[0].description.source = { url: 'http://www.lifeofpimovie.com/' };

        LifeOfPi.save(function ( movieObj1 ) {
          assert.equal('http://www.lifeofpimovie.com/', movieObj1['ratings.0.description.source'].url);

          // overwritten date
          assert.equal( undefined, movieObj1['ratings.0.description.source'].time );

          var newDate = new Date();
          LifeOfPi.ratings[0].set('description.source.time', newDate, { merge: true });
          LifeOfPi.save(function ( movieObj2 ) {
            assert.equal(String(newDate), movieObj2['ratings.0.description.source'].time);
            // url not overwritten using merge
            assert.equal('http://www.lifeofpimovie.com/', movieObj2['ratings.0.description.source'].url);
            done();
          });
        });
      });
    });
  });

});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Beih. Nova Hedwigia 43: 58 (1973)

#### Original name
Entoloma peralbidum E. Horak, 1973

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
Ensembl.Panel.Register = Ensembl.Panel.ModalContent.extend({

  init: function () {
    var panel = this;
    this.base();

    this.elLk.form      = this.el.find('form#registration');
    this.elLk.button    = this.el.find('#pre_consent');
    this.elLk.checkbox  = this.el.find('#consent_checkbox');

    this.elLk.checkbox.on('click', function(e) {
      if (panel.elLk.button.hasClass('disabled')) {
        panel.elLk.button.removeClass('disabled');
      }
      else {
        panel.elLk.button.addClass('disabled');
      }
    });

    this.elLk.button.on('click', function(e) {
      if (!panel.elLk.button.hasClass('disabled')) {
        panel.formSubmit(panel.elLk.form);
      }
    });
  }

});


text:
package edu.uw.apl.commons.tsk4j.digests;

import java.io.File;

import edu.uw.apl.commons.tsk4j.filesys.FileSystem;

public class BodyFileBuilderTest extends junit.framework.TestCase {

	public void testNuga2() throws Exception {
		File f = new File( "data/nuga2.dd" );
		if( !f.exists() ) {
			return;
		}
		FileSystem fs = new FileSystem( f.getPath(), 63 );

		BodyFile bf = BodyFileBuilder.create( fs, 0 );
		fs.close();
		for( BodyFile.Record r : bf.records() ) {
			System.out.println( r );
		}
		System.out.println( bf.getName() );
	}
}

// eof


text:
package com.lqtemple.android.lqbookreader.model;

import android.util.Log;

import com.lqtemple.android.lqbookreader.Configuration;

import java.util.List;

/**
 * Created by sundxing on 16/12/25.
 * 段落,包含文本索引
 */

public class Content {
    private static final String TAG = "Content";
    JContent mJContent;
    private int mOffset;
    private int mParagraphIndex;
    private int totalOffset;

    // 添加缩进和换行
    private CharSequence mFormatText;

    private int[] imageStartOffsets;
    private int[] imageEndOffsets;

    public Content(JContent JContent) {
        mJContent = JContent;
        mParagraphIndex = extractParagraphIndex(mJContent.getIndex());
    }

    private int extractParagraphIndex(String index) {
        return Integer.valueOf(index.substring(0, index.indexOf("-")));
    }

    public int getOffset() {
        return mOffset;
    }

    public void setOffset(int offset) {
        mOffset = offset;
    }

    public List<String> getImageUrl() {
        return mJContent.getImageUrl();
    }

    public int getAudioFrame() {
        return mJContent.getAudioTimeFrame();
    }

    public int getParagraphIndex() {
        return mParagraphIndex;
    }

    @Override
    public String toString() {
        return "Index" + mJContent.getIndex() + ", offset:" + mOffset;
    }

    public Type getTypeEnum() {
        return mJContent.getTypeEnum();
    }

    public String getIndex() {
        return mJContent.getIndex();
    }

    public CharSequence getText() {
        format();
        return mFormatText;
    }

    public Content format() {

        if (mFormatText == null) {
            Log.d(TAG, "Format string : ");
            StringBuilder sb = new StringBuilder();

            final String text = mJContent.getText();
            if (getTypeEnum() == Type.Title) {
                sb.append("\n")
                        .append(text)
                        .append("\n");
            } else {
                // Paragraph leading
                sb.append(Configuration.getInstance().getLeadingMarginText())
                        .append(text)
                        .append("\n");
            }

            // Insert image tag.
            imageStartOffsets = new int[getImageUrl().size()];
            imageEndOffsets = new int[imageStartOffsets.length];
            int index = 0;
            for (String imageUrl : getImageUrl()) {
                // TODO 添加图片说明
                String imageDesc = "图片";
                imageStartOffsets[index] = sb.length();
                Log.d(TAG, "image add :" + imageStartOffsets[index]);

                sb.append(Configuration.IMAGE_TAG);
                sb.append(imageUrl);
                sb.append(Configuration.IMAGE_TAG);
                imageEndOffsets[index] = sb.length();

                sb.append("\n").append(imageDesc).append("\n");
                index++;
            }
            mFormatText = sb.toString();
        }

        return this;
    }

    public boolean isChapterStart() {
        if (mJContent.getType() != Type.Title.ordinal()) return false;
        String[] indexStr = getIndex().split("-");
        return indexStr.length == 2 && indexStr[1].equals("0");
    }

    public int getTotalOffset() {
        return totalOffset;
    }

    public void setTotalOffset(int totalOffset) {
        this.totalOffset = totalOffset;
    }

    public boolean isBodyType() {
        return getTypeEnum()== Type.Content;
    }

    public int getImageTagLength(String uri) {
        return (uri != null ? uri.length() : 0 ) + Configuration.IMAGE_TAG.length() * 2;
    }

    public int[] getImageStartOffsets() {
        return imageStartOffsets;
    }

    public int[] getImageEndOffsets() {
        return imageEndOffsets;
    }
}


text:
import os from 'os';

import { HTTP } from 'meteor/http';
import { check, Match } from 'meteor/check';

import { Settings } from '../../../models';
import { Info } from '../../../utils';
import { getWorkspaceAccessToken } from '../../../cloud/server';

export default () => {
	try {
		const uniqueID = Settings.findOne('uniqueID');

		const params = {
			uniqueId: uniqueID.value,
			installedAt: uniqueID.createdAt.toJSON(),
			version: Info.version,
			osType: os.type(),
			osPlatform: os.platform(),
			osArch: os.arch(),
			osRelease: os.release(),
			nodeVersion: process.version,
			deployMethod: process.env.DEPLOY_METHOD || 'tar',
			deployPlatform: process.env.DEPLOY_PLATFORM || 'selfinstall',
		};

		const headers = {};
		const token = getWorkspaceAccessToken();
		if (token) {
			headers.Authorization = `Bearer ${ token }`;
		}

		const { data } = HTTP.get('https://releases.rocket.chat/updates/check', {
			params,
			headers,
		});

		check(data, Match.ObjectIncluding({
			versions: [Match.ObjectIncluding({
				version: Match.Optional(String),
				security: Match.Optional(Boolean),
				infoUrl: Match.Optional(String),
			})],
			alerts: Match.Optional([Match.ObjectIncluding({
				id: Match.Optional(String),
				title: Match.Optional(String),
				text: Match.Optional(String),
				textArguments: Match.Optional([Match.Any]),
				modifiers: Match.Optional([String]),
				infoUrl: Match.Optional(String),
			})]),
		}));

		return data;
	} catch (error) {
		// There's no need to log this error
		// as it's pointless and the user
		// can't do anything about it anyways

		return {
			versions: [],
			alerts: [],
		};
	}
};


text:
// Copyright (c) 2014, Sailing Lab
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the <ORGANIZATION> nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// server_thread.cpp
// author: jinliang

#include <petuum_ps/server/server_threads.hpp>
#include <petuum_ps/thread/context.hpp>
#include <petuum_ps/thread/ps_msgs.hpp>
#include <petuum_ps_common/thread/mem_transfer.hpp>
#include <petuum_ps_common/util/stats.hpp>

namespace petuum {

pthread_barrier_t ServerThreads::init_barrier;
std::vector<pthread_t> ServerThreads::threads_;
std::vector<int32_t> ServerThreads::thread_ids_;
boost::thread_specific_ptr<ServerThreads::ServerContext>
  ServerThreads::server_context_;
CommBus::RecvFunc ServerThreads::CommBusRecvAny;
CommBus::RecvTimeOutFunc ServerThreads::CommBusRecvTimeOutAny;
CommBus::SendFunc ServerThreads::CommBusSendAny;
CommBus::RecvAsyncFunc ServerThreads::CommBusRecvAsyncAny;
CommBus *ServerThreads::comm_bus_;
ServerThreads::ServerPushRowFunc ServerThreads::ServerPushRow;
CommBus::RecvWrapperFunc ServerThreads::CommBusRecvAnyWrapper;
ServerThreads::RowSubscribeFunc ServerThreads::RowSubscribe;

void ServerThreads::Init(int32_t id_st){

  pthread_barrier_init(&init_barrier, NULL,
    GlobalContext::get_num_local_server_threads() + 1);
  threads_.resize(GlobalContext::get_num_local_server_threads());
  thread_ids_.resize(GlobalContext::get_num_local_server_threads());
  comm_bus_ = GlobalContext::comm_bus;

  if (GlobalContext::get_num_clients() == 1) {
    CommBusRecvAny = &CommBus::RecvInProc;
    CommBusRecvAsyncAny = &CommBus::RecvInProcAsync;
  } else{
    CommBusRecvAny = &CommBus::Recv;
    CommBusRecvAsyncAny = &CommBus::RecvAsync;
  }

  if (GlobalContext::get_num_clients() == 1) {
    CommBusRecvTimeOutAny = &CommBus::RecvInProcTimeOut;
  } else{
    CommBusRecvTimeOutAny = &CommBus::RecvTimeOut;
  }

  if (GlobalContext::get_num_clients() == 1) {
    CommBusSendAny = &CommBus::SendInProc;
  } else {
    CommBusSendAny = &CommBus::Send;
  }

  //ServerThreadMainFunc ServerThreadMain;
  ConsistencyModel consistency_model = GlobalContext::get_consistency_model();
  switch(consistency_model) {
    case SSP:
      ServerPushRow = SSPServerPushRow;
      RowSubscribe = SSPRowSubscribe;
      break;
    case SSPPush:
      ServerPushRow = SSPPushServerPushRow;
      RowSubscribe = SSPPushRowSubscribe;
      VLOG(0) << "RowSubscribe = SSPPushRowSubscribe";
      break;
    default:
      LOG(FATAL) << "Unrecognized consistency model " << consistency_model;
  }

  if (GlobalContext::get_aggressive_cpu()) {
    CommBusRecvAnyWrapper = CommBusRecvAnyBusy;
  } else {
    CommBusRecvAnyWrapper = CommBusRecvAnySleep;
  }

  int i;
  for (i = 0; i < GlobalContext::get_num_local_server_threads(); ++i) {
    VLOG(0) << "Create server thread " << i;
    thread_ids_[i] = id_st + i;
    int ret = pthread_create(&threads_[i], NULL, ServerThreadMain,
      &thread_ids_[i]);
    CHECK_EQ(ret, 0);
  }
  pthread_barrier_wait(&init_barrier);
}

void ServerThreads::ShutDown(){
  for(int i = 0; i < GlobalContext::get_num_local_server_threads(); ++i){
    int ret = pthread_join(threads_[i], NULL);
    CHECK_EQ(ret, 0);
  }
}

/* Private Functions */

void ServerThreads::SendToAllBgThreads(void *msg, size_t msg_size){
  int32_t i;
  for(i = 0; i < GlobalContext::get_num_total_bg_threads(); ++i){
    int32_t bg_id = server_context_->bg_thread_ids_[i];
    size_t sent_size = (comm_bus_->*CommBusSendAny)(bg_id, msg, msg_size);
    CHECK_EQ(sent_size, msg_size);
  }
}

void ServerThreads::ConnectToNameNode(){
  int32_t name_node_id = GlobalContext::get_name_node_id();

  ServerConnectMsg server_connect_msg;
  void *msg = server_connect_msg.get_mem();
  int32_t msg_size = server_connect_msg.get_size();

  if (comm_bus_->IsLocalEntity(name_node_id)) {
    VLOG(0) << "Connect to local name node";
    comm_bus_->ConnectTo(name_node_id, msg, msg_size);
  } else {
    VLOG(0) << "Connect to remote name node";
    HostInfo name_node_info = GlobalContext::get_host_info(name_node_id);
    std::string name_node_addr = name_node_info.ip + ":" + name_node_info.port;
    VLOG(0) << "name_node_addr = " << name_node_addr;
    comm_bus_->ConnectTo(name_node_id, name_node_addr, msg, msg_size);
  }
}

int32_t ServerThreads::GetConnection(bool *is_client, int32_t *client_id){
  int32_t sender_id;
  zmq::message_t zmq_msg;
  (comm_bus_->*CommBusRecvAny)(&sender_id, &zmq_msg);
  MsgType msg_type = MsgBase::get_msg_type(zmq_msg.data());
  if (msg_type == kClientConnect) {
    ClientConnectMsg msg(zmq_msg.data());
    *is_client = true;
    *client_id = msg.get_client_id();
  } else {
    CHECK_EQ(msg_type, kServerConnect);
    *is_client = false;
  }
  return sender_id;
}

void ServerThreads::InitServer(int32_t server_id) {
  ConnectToNameNode();

  int32_t num_bgs;
  for(num_bgs = 0; num_bgs < GlobalContext::get_num_total_bg_threads();
    ++num_bgs){
    int32_t client_id;
    bool is_client;
    int32_t bg_id = GetConnection(&is_client, &client_id);
    CHECK(is_client);
    server_context_->bg_thread_ids_[num_bgs] = bg_id;
    server_context_->server_obj_.AddClientBgPair(client_id, bg_id);
  }

  server_context_->server_obj_.Init(server_id);
  ClientStartMsg client_start_msg;
  int32_t msg_size = client_start_msg.get_size();
  SendToAllBgThreads(client_start_msg.get_mem(), msg_size);

  VLOG(0) << "InitNonNameNode done";
}

bool ServerThreads::HandleShutDownMsg(){
  // When num_shutdown_bgs reaches the total number of bg threads, the server
  // reply to each bg with a ShutDownReply message
  int32_t &num_shutdown_bgs = server_context_->num_shutdown_bgs_;
  ++num_shutdown_bgs;
  if(num_shutdown_bgs == GlobalContext::get_num_total_bg_threads()){
    ServerShutDownAckMsg shut_down_ack_msg;
    size_t msg_size = shut_down_ack_msg.get_size();
    int i;
    for(i = 0; i < GlobalContext::get_num_total_bg_threads(); ++i){
      int32_t bg_id = server_context_->bg_thread_ids_[i];
      size_t sent_size = (comm_bus_->*CommBusSendAny)(bg_id,
        shut_down_ack_msg.get_mem(), msg_size);
      CHECK_EQ(msg_size, sent_size);
    }
    return true;
  }
  return false;
}

void ServerThreads::HandleCreateTable(int32_t sender_id,
  CreateTableMsg &create_table_msg) {
  int32_t table_id = create_table_msg.get_table_id();

  // I'm not name node
  CreateTableReplyMsg create_table_reply_msg;
  create_table_reply_msg.get_table_id() = create_table_msg.get_table_id();
  size_t sent_size = (comm_bus_->*CommBusSendAny)(sender_id,
    create_table_reply_msg.get_mem(), create_table_reply_msg.get_size());
  CHECK_EQ(sent_size, create_table_reply_msg.get_size());

  TableInfo table_info;
  table_info.table_staleness = create_table_msg.get_staleness();
  table_info.row_type = create_table_msg.get_row_type();
  table_info.row_capacity = create_table_msg.get_row_capacity();
  server_context_->server_obj_.CreateTable(table_id, table_info);
}

void ServerThreads::SetUpServerContext(){
  server_context_.reset(new ServerContext);
  server_context_->bg_thread_ids_.resize(
    GlobalContext::get_num_total_bg_threads());
  server_context_->num_shutdown_bgs_ = 0;
}

void ServerThreads::SetUpCommBus() {
  int32_t my_id = ThreadContext::get_id();
  CommBus::Config comm_config;
  comm_config.entity_id_ = my_id;
  VLOG(0) << "ServerThreads num_clients = " << GlobalContext::get_num_clients();
  VLOG(0) << "my id = " << my_id;

  if (GlobalContext::get_num_clients() > 1) {
    comm_config.ltype_ = CommBus::kInProc | CommBus::kInterProc;
    HostInfo host_info = GlobalContext::get_host_info(my_id);
    comm_config.network_addr_ = host_info.ip + ":" + host_info.port;
    VLOG(0) << "network addr = " << comm_config.network_addr_;
  } else {
    comm_config.ltype_ = CommBus::kInProc;
  }

  comm_bus_->ThreadRegister(comm_config);
  VLOG(0) << "Server thread registered CommBus";
}

void ServerThreads::HandleRowRequest(int32_t sender_id,
  RowRequestMsg &row_request_msg) {
  int32_t table_id = row_request_msg.get_table_id();
  int32_t row_id = row_request_msg.get_row_id();
  int32_t clock = row_request_msg.get_clock();
  int32_t server_clock = server_context_->server_obj_.GetMinClock();
  if (server_clock < clock) {
    // not fresh enough, wait
    server_context_->server_obj_.AddRowRequest(sender_id, table_id, row_id,
      clock);
    return;
  }

  uint32_t version = server_context_->server_obj_.GetBgVersion(sender_id);
  ServerRow *server_row = server_context_->server_obj_.FindCreateRow(table_id,
    row_id);
  //VLOG(0) << "calling RowSubscribe";
  RowSubscribe(server_row, GlobalContext::thread_id_to_client_id(sender_id));

  //VLOG(0) << "fresh enough, reply now";
  ReplyRowRequest(sender_id, server_row, table_id, row_id, server_clock,
   version);
}

void ServerThreads::ReplyRowRequest(int32_t bg_id, ServerRow *server_row,
  int32_t table_id, int32_t row_id, int32_t server_clock, uint32_t version){

  size_t row_size = server_row->SerializedSize();

  ServerRowRequestReplyMsg server_row_request_reply_msg(row_size);
  server_row_request_reply_msg.get_table_id() = table_id;
  server_row_request_reply_msg.get_row_id() = row_id;
  server_row_request_reply_msg.get_clock() = server_clock;
  server_row_request_reply_msg.get_version() = version;
  //VLOG(0) << "Replying client row request, version = " << version
  //       << " table_id = " << table_id;

  row_size = server_row->Serialize(server_row_request_reply_msg.get_row_data());

  server_row_request_reply_msg.get_row_size() = row_size;

  MemTransfer::TransferMem(comm_bus_, bg_id, &server_row_request_reply_msg);
}

void ServerThreads::HandleOpLogMsg(int32_t sender_id,
  ClientSendOpLogMsg &client_send_oplog_msg) {
  int32_t client_id = client_send_oplog_msg.get_client_id();
  bool is_clock = client_send_oplog_msg.get_is_clock();
  uint32_t version = client_send_oplog_msg.get_version();

  STATS_SERVER_ADD_PER_CLOCK_OPLOG_SIZE(client_send_oplog_msg.get_size());

  STATS_SERVER_ACCUM_APPLY_OPLOG_BEGIN();
  server_context_->server_obj_.ApplyOpLog(client_send_oplog_msg.get_data(),
    sender_id, version);
  STATS_SERVER_ACCUM_APPLY_OPLOG_END();

  if (is_clock) {
    bool clock_changed
      = server_context_->server_obj_.Clock(client_id, sender_id);
    if (clock_changed) {
      std::vector<ServerRowRequest> requests;
      server_context_->server_obj_.GetFulfilledRowRequests(&requests);
      for (auto request_iter = requests.begin();
	   request_iter != requests.end(); request_iter++) {
	int32_t table_id = request_iter->table_id;
	int32_t row_id = request_iter->row_id;
	int32_t bg_id = request_iter->bg_id;
	int32_t version = server_context_->server_obj_.GetBgVersion(bg_id);
	ServerRow *server_row
	  = server_context_->server_obj_.FindCreateRow(table_id, row_id);
        RowSubscribe(server_row,
                     GlobalContext::thread_id_to_client_id(bg_id));
	int32_t server_clock = server_context_->server_obj_.GetMinClock();
	ReplyRowRequest(bg_id, server_row, table_id, row_id, server_clock,
	  version);
      }
      STATS_SERVER_CLOCK();
      ServerPushRow();
    }
  }
}

void ServerThreads::CommBusRecvAnyBusy(int32_t *sender_id,
                                       zmq::message_t *zmq_msg) {
  bool received = (comm_bus_->*CommBusRecvAsyncAny)(sender_id, zmq_msg);
  while (!received) {
    received = (comm_bus_->*CommBusRecvAsyncAny)(sender_id, zmq_msg);
  }
}

void ServerThreads::CommBusRecvAnySleep(int32_t *sender_id,
                                        zmq::message_t *zmq_msg) {
  (comm_bus_->*CommBusRecvAny)(sender_id, zmq_msg);
}

void ServerThreads::SSPPushServerPushRow() {
  STATS_SERVER_ACCUM_PUSH_ROW_BEGIN();
  server_context_->server_obj_.CreateSendServerPushRowMsgs(
      SendServerPushRowMsg);
  STATS_SERVER_ACCUM_PUSH_ROW_END();
}

void ServerThreads::SendServerPushRowMsg(int32_t bg_id,
  ServerPushRowMsg *msg, bool last_msg) {

  msg->get_version() = server_context_->server_obj_.GetBgVersion(bg_id);
  STATS_SERVER_ADD_PER_CLOCK_PUSH_ROW_SIZE(msg->get_size());

  if (last_msg) {
    msg->get_is_clock() = true;
    msg->get_clock() = server_context_->server_obj_.GetMinClock();
    MemTransfer::TransferMem(comm_bus_, bg_id, msg);
  } else {
    msg->get_is_clock() = false;
    size_t sent_size = (comm_bus_->*CommBusSendAny)(bg_id, msg->get_mem(),
                                                    msg->get_size());
    CHECK_EQ(sent_size, msg->get_size());
  }
}

void ServerThreads::SSPPushRowSubscribe(ServerRow *server_row,
                                        int32_t client_id) {
  server_row->Subscribe(client_id);
}

void *ServerThreads::ServerThreadMain(void *thread_id){
  int32_t my_id = *(reinterpret_cast<int32_t*>(thread_id));

  ThreadContext::RegisterThread(my_id);
  STATS_REGISTER_THREAD(kServerThread);

  // set up thread-specific server context
  SetUpServerContext();
  SetUpCommBus();

  pthread_barrier_wait(&init_barrier);

  InitServer(my_id);

  zmq::message_t zmq_msg;
  int32_t sender_id;
  MsgType msg_type;
  void *msg_mem;
  bool destroy_mem = false;
  while(1) {
    CommBusRecvAnyWrapper(&sender_id, &zmq_msg);

    msg_type = MsgBase::get_msg_type(zmq_msg.data());
    //VLOG(0) << "msg_type = " << msg_type;
    destroy_mem = false;

    if (msg_type == kMemTransfer) {
      MemTransferMsg mem_transfer_msg(zmq_msg.data());
      msg_mem = mem_transfer_msg.get_mem_ptr();
      msg_type = MsgBase::get_msg_type(msg_mem);
      destroy_mem = true;
    } else {
      msg_mem = zmq_msg.data();
    }

    switch (msg_type) {
    case kClientShutDown:
      {
	VLOG(0) << "get ClientShutDown from bg " << sender_id;
	bool shutdown = HandleShutDownMsg();
	if (shutdown) {
          VLOG(0) << "Server shutdown";
	  comm_bus_->ThreadDeregister();
	  STATS_DEREGISTER_THREAD();
	  return 0;
	}
	break;
      }
    case kCreateTable:
      {
	CreateTableMsg create_table_msg(msg_mem);
	HandleCreateTable(sender_id, create_table_msg);
	break;
      }
    case kRowRequest:
      {
	RowRequestMsg row_request_msg(msg_mem);
	HandleRowRequest(sender_id, row_request_msg);
      }
      break;
    case kClientSendOpLog:
      {
	ClientSendOpLogMsg client_send_oplog_msg(msg_mem);
	HandleOpLogMsg(sender_id, client_send_oplog_msg);
      }
      break;
    default:
      LOG(FATAL) << "Unrecognized message type " << msg_type;
    }

    if (destroy_mem)
      MemTransfer::DestroyTransferredMem(msg_mem);
  }
}

}


text:
package net.nunoachenriques.vader.text;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * A simple tokenizer of plain text.
 *
 * @author Nuno A. C. Henriques [nunoachenriques.net]
 * @see net.nunoachenriques.vader.text.Tokenizer
 * @see java.util.regex.Pattern
 */
public class TokenizerEnglish
        implements Tokenizer {

    /**
     * All types of white space (e.g., line feed).
     *
     * Python
     * string.whitespace equivalent to Java \p{Space}
     */
    private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{Space}");
    /**
     * The defined characters as punctuation except for contractions
     * (e.g., "can't" in english is kept as "can't" instead of "cant"), URL
     * (e.g., nunoachenriques.net), and name abbreviations
     * (e.g., J.R.R. => J.R.R).
     *
     * Python
     * string.punctuation equivalent to Java \p{Punct}
     */
    private static final Pattern PUNCTUATION_EXCLUDE_CONTRACTION_PATTERN = Pattern.compile("[\\p{Punct}&&[^.']]|(?<=(^|\\s|\\p{Punct}))[.']|[.'](?=($|\\s|\\p{Punct}))");

    public TokenizerEnglish() {
    }

    @Override
    public List<String> split(String s, Pattern p) {
        return new LinkedList<>(Arrays.asList(p.split(s)));
    }

    @Override
    public List<String> cleanAndSplit(String s, Pattern p, Pattern c, String r) {
        return new LinkedList<>(Arrays.asList(p.split(c.matcher(s).replaceAll(r))));
    }

    @Override
    public List<String> splitWhitespace(String s) {
        return split(s, WHITESPACE_PATTERN);
    }

    @Override
    public List<String> cleanPunctuationAndSplitWhitespace(String s, String r) {
        return cleanAndSplit(s, WHITESPACE_PATTERN, PUNCTUATION_EXCLUDE_CONTRACTION_PATTERN, r);
    }

    @Override
    public void removeTokensBySize(List<String> l, int min, int max) {
        Iterator<String> i = l.iterator();
        while (i.hasNext()) {
            String t = i.next();
            if (t.length() < min || t.length() > max) {
                i.remove();
            }
        }
    }
}


text:
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}

module Opaleye.Join where

import qualified Opaleye.Internal.Unpackspec as U
import qualified Opaleye.Internal.Tag as T
import qualified Opaleye.Internal.PrimQuery as PQ
import qualified Opaleye.Internal.PackMap as PM
import           Opaleye.QueryArr (Query)
import qualified Opaleye.QueryArr as Q
import           Opaleye.Column (Column(Column), Nullable)
import qualified Opaleye.Column as C
import qualified Opaleye.Internal.Values as V

import           Data.Profunctor (Profunctor, dimap)
import           Data.Profunctor.Product (ProductProfunctor, empty, (***!))
import qualified Data.Profunctor.Product.Default as D

import qualified Database.HaskellDB.PrimQuery as HPQ

data NullMaker a b = NullMaker (a -> b)

toNullable :: NullMaker a b -> a -> b
toNullable (NullMaker f) = f

leftJoin  :: (D.Default U.Unpackspec columnsA columnsA,
              D.Default U.Unpackspec columnsB columnsB,
              D.Default NullMaker columnsB nullableColumnsB) =>
             Query columnsA -> Query columnsB
          -> ((columnsA, columnsB) -> Column Bool)
          -> Query (columnsA, nullableColumnsB)
leftJoin = leftJoinExplicit D.def D.def D.def

leftJoinExplicit :: U.Unpackspec columnsA columnsA
                 -> U.Unpackspec columnsB columnsB
                 -> NullMaker columnsB nullableColumnsB
                 -> Query columnsA -> Query columnsB
                 -> ((columnsA, columnsB) -> Column Bool)
                 -> Query (columnsA, nullableColumnsB)
leftJoinExplicit unpackA unpackB nullmaker qA qB cond = Q.simpleQueryArr q where
  q ((), startTag) = ((newColumnsA, nullableColumnsB), primQueryR, T.next endTag)
    where (columnsA, primQueryA, midTag) = Q.runSimpleQueryArr qA ((), startTag)
          (columnsB, primQueryB, endTag) = Q.runSimpleQueryArr qB ((), midTag)

          (newColumnsA, ljPEsA) =
            PM.run (U.runUnpackspec unpackA (extractLeftJoinFields 1 endTag) columnsA)
          (newColumnsB, ljPEsB) =
            PM.run (U.runUnpackspec unpackB (extractLeftJoinFields 2 endTag) columnsB)

          nullableColumnsB = toNullable nullmaker newColumnsB

          Column cond' = cond (columnsA, columnsB)
          primQueryR = PQ.Join PQ.LeftJoin (ljPEsA ++ ljPEsB) cond' primQueryA primQueryB

-- TODO: Move this to Internal
extractLeftJoinFields :: Int -> T.Tag -> HPQ.PrimExpr
            -> PM.PM [(String, HPQ.PrimExpr)] HPQ.PrimExpr
extractLeftJoinFields n = V.extractAttr (\i -> "result" ++ show n ++ "_" ++ i)

instance D.Default NullMaker (Column a) (Column (Nullable a)) where
  def = NullMaker C.unsafeCoerce

instance D.Default NullMaker (Column (Nullable a)) (Column (Nullable a)) where
  def = NullMaker C.unsafeCoerce

-- { Boilerplate instances

instance Profunctor NullMaker where
  dimap f g (NullMaker h) = NullMaker (dimap f g h)

instance ProductProfunctor NullMaker where
  empty = NullMaker empty
  NullMaker f ***! NullMaker f' = NullMaker (f ***! f')

--


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SIM.Models
{
    public class UnallocateClassroom
    {
        public bool Flag { get; set; }
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import {withDefaultNowContext} from '../testing/NowContainer';
import InsightAboutTeamMembership from './InsightAboutTeamMembership';

function testProps(props = {}) {
  return {
    firstName: 'Mari',
    insightPayload: {
      activity_text: 'Indoor Track - Girls Varsity',
      season_key: 'winter',
      school_year_text: '2018-19',
      coach_text: 'Eric Taylor',
      active: true,
    },
    ...props
  };
}

function testEl(props = {}) {
  return withDefaultNowContext(<InsightAboutTeamMembership {...props} />);
}

// since element sizing methods aren't present in the Jest JS environment
jest.mock('../components/FitText', () => 'mocked-fit-text');

it('renders without crashing', () => {
  const el = document.createElement('div');
  const props = testProps();
  ReactDOM.render(testEl(props), el);
});

it('snapshots view', () => {
  const props = testProps();
  const tree = renderer
    .create(testEl(props))
    .toJSON();
  expect(tree).toMatchSnapshot();
});

it('snapshots for last year', () => {
  const defaultProps = testProps();
  const props = {
    ...defaultProps,
    insightPayload: {
      ...defaultProps.insightPayload,
      school_year_text: '2017-18',
      active: false
    }
  };
  const tree = renderer
    .create(testEl(props))
    .toJSON();
  expect(tree).toMatchSnapshot();
});


text:
package net.milanqiu.mimas.db;

import net.milanqiu.mimas.string.StrUtils;

/**
 * Database management system explicitly supported by mimas.
 * <p>
 * Creation Date: 2017-05-03
 * @author Milan Qiu
 */
public enum Dbms {

    /**
     * MySQL.
     */
    MYSQL {
        @Override
        public String getJdbcDriverClassName() {
            return "com.mysql.cj.jdbc.Driver";
        }

        @Override
        public String getJdbcProtocol() {
            return "jdbc:mysql://";
        }
    };

    /**
     * Returns the jdbc driver class name to access database.
     * @return the jdbc driver class name to access database
     */
    public abstract String getJdbcDriverClassName();

    /**
     * Returns the jdbc protocol to access database.
     * @return the jdbc protocol to access database
     */
    public abstract String getJdbcProtocol();

    /**
     * Returns the database url used by jdbc.
     * @param dbProfile the profile of database to be accessed
     * @return the database url used by jdbc
     */
    public String getJdbcUrl(DatabaseProfile dbProfile) {
        return getJdbcProtocol() + dbProfile.getAddress() + "/" + dbProfile.getName() + StrUtils.addPrefixIfNotEmpty("?", dbProfile.getParams());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using StackExchange.Redis;

namespace NETCore.RedisKit.Services
{
    public interface ICustomRedisEventService
    {
        /// <summary>
        /// Raised when nodes are explicitly requested to reconfigure via broadcast; this usually means master/slave changes
        /// </summary>
        /// <param name="point"></param>
        void RedisConfigurationChangedBroadcast(EndPoint point);

        /// <summary>
        /// Raised when a hash-slot has been relocated
        /// </summary>
        /// <param name="oldPoint"></param>
        /// <param name="newPoint"></param>
        void RedisHashSlotMoved(EndPoint oldPoint, EndPoint newPoint);

        /// <summary>
        ///   Redis internal error
        /// </summary>
        /// <param name="point"></param>
        /// <param name="innerEx"></param>
        /// <param name="origin"></param>
        void RedisInternalError(EndPoint point, Exception innerEx, string origin);

        /// <summary>
        ///  Redis connection failded
        /// </summary>
        /// <param name="connectionType"></param>
        /// <param name="point"></param>
        /// <param name="innerEx"></param>
        /// <param name="failureType"></param>
        void RedisConnectionFailed(string connectionType, EndPoint point, Exception innerEx, string failureType);

        /// <summary>
        /// Raised whenever a physical connection is established
        /// </summary>
        /// <param name="connectionType"></param>
        /// <param name="point"></param>
        /// <param name="innerEx"></param>
        /// <param name="failureType"></param>
        void RedisConnectionRestored(string connectionType, EndPoint point, Exception innerEx, string failureType);

        /// <summary>
        /// Redis configuration changed
        /// </summary>
        /// <param name="point"></param>
        void RedisConfigurationChanged(EndPoint point);
    }
}


text:
//  Unit test for boost::lexical_cast.
//
//  See http://www.boost.org for most recent version, including documentation.
//
//  Copyright Antony Polukhin, 2012-2019.
//
//  Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).

#include <boost/config.hpp>

#if defined(__INTEL_COMPILER)
#pragma warning(disable: 193 383 488 981 1418 1419)
#elif defined(BOOST_MSVC)
#pragma warning(disable: 4097 4100 4121 4127 4146 4244 4245 4511 4512 4701 4800)
#endif

#include <boost/lexical_cast.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/range/iterator_range.hpp>

using namespace boost;

// Testing compilation and some basic usage with BOOST_NO_STD_LOCALE
// Tests are mainly copyied from lexical_cast_empty_input_test.cpp (something
// new added to test_empty_3)

#ifndef BOOST_NO_STD_LOCALE
#error "This test must be compiled with -DBOOST_NO_STD_LOCALE"
#endif

template <class T>
void do_test_on_empty_input(T& v)
{
    BOOST_CHECK_THROW(lexical_cast<int>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<float>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<double>(v), bad_lexical_cast);
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
    BOOST_CHECK_THROW(lexical_cast<long double>(v), bad_lexical_cast);
#endif
    BOOST_CHECK_THROW(lexical_cast<unsigned int>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned short>(v), bad_lexical_cast);
#if defined(BOOST_HAS_LONG_LONG)
    BOOST_CHECK_THROW(lexical_cast<boost::ulong_long_type>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<boost::long_long_type>(v), bad_lexical_cast);
#elif defined(BOOST_HAS_MS_INT64)
    BOOST_CHECK_THROW(lexical_cast<unsigned __int64>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<__int64>(v), bad_lexical_cast);
#endif
}

void test_empty_1()
{
    boost::iterator_range<char*> v;
    do_test_on_empty_input(v);
    BOOST_CHECK_EQUAL(lexical_cast<std::string>(v), std::string());
    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);

    boost::iterator_range<const char*> cv;
    do_test_on_empty_input(cv);
    BOOST_CHECK_EQUAL(lexical_cast<std::string>(cv), std::string());
    BOOST_CHECK_THROW(lexical_cast<char>(cv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(cv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(cv), bad_lexical_cast);

    const boost::iterator_range<const char*> ccv;
    do_test_on_empty_input(ccv);
    BOOST_CHECK_EQUAL(lexical_cast<std::string>(ccv), std::string());
    BOOST_CHECK_THROW(lexical_cast<char>(ccv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(ccv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(ccv), bad_lexical_cast);
}

void test_empty_2()
{
    std::string v;
    do_test_on_empty_input(v);
    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);
}

struct Escape
{
    Escape(){}
    Escape(const std::string& s)
        : str_(s)
    {}

    std::string str_;
};

inline std::ostream& operator<< (std::ostream& o, const Escape& rhs)
{
    return o << rhs.str_;
}

inline std::istream& operator>> (std::istream& i, Escape& rhs)
{
    return i >> rhs.str_;
}

void test_empty_3()
{
    Escape v("");
    do_test_on_empty_input(v);

    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);

    v = lexical_cast<Escape>(100);
    BOOST_CHECK_EQUAL(lexical_cast<int>(v), 100);
    BOOST_CHECK_EQUAL(lexical_cast<unsigned int>(v), 100u);

    v = lexical_cast<Escape>(0.0);
    BOOST_CHECK_EQUAL(lexical_cast<double>(v), 0.0);
}

namespace std {
inline std::ostream & operator<<(std::ostream & out, const std::vector<long> & v)
{
    std::ostream_iterator<long> it(out);
    std::copy(v.begin(), v.end(), it);
    assert(out);
    return out;
}
}

void test_empty_4()
{
    std::vector<long> v;
    do_test_on_empty_input(v);
    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);
}

struct my_string {
    friend std::ostream &operator<<(std::ostream& sout, my_string const&/* st*/) {
            return sout << "";
    }
};

void test_empty_5()
{
    my_string st;
    BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(st), std::string());;
}

unit_test::test_suite *init_unit_test_suite(int, char *[])
{
    unit_test::test_suite *suite =
        BOOST_TEST_SUITE("lexical_cast. Testing with BOOST_NO_STD_LOCALE");
    suite->add(BOOST_TEST_CASE(&test_empty_1));
    suite->add(BOOST_TEST_CASE(&test_empty_2));
    suite->add(BOOST_TEST_CASE(&test_empty_3));
    suite->add(BOOST_TEST_CASE(&test_empty_4));
    suite->add(BOOST_TEST_CASE(&test_empty_5));

    return suite;
}


text:
<root><keywords><chatbot></chatbot>
<infobot>search,  find</infobot>
<cmdbot>open,   start,   youtube,   google,   facebook</cmdbot>
<learningbot>user.train,      train,      bot,      cmdbot,      infobot,      chatbot</learningbot>
</keywords></root>


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 io.prestosql.sql.planner.iterative.rule;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.iterative.rule.test.BaseRuleTest;
import io.prestosql.sql.planner.plan.ExplainAnalyzeNode;
import org.testng.annotations.Test;

import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.expression;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.node;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.strictProject;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.values;

public class TestPruneExplainAnalyzeSourceColumns
        extends BaseRuleTest
{
    @Test
    public void testNotAllOutputsReferenced()
    {
        tester().assertThat(new PruneExplainAnalyzeSourceColumns())
                .on(p -> {
                    Symbol a = p.symbol("a");
                    Symbol b = p.symbol("b");
                    return p.explainAnalyzeNode(
                            p.symbol("query plan", VARCHAR),
                            ImmutableList.of(b),
                            p.values(a, b));
                })
                .matches(
                        node(ExplainAnalyzeNode.class,
                                strictProject(
                                        ImmutableMap.of("b", expression("b")),
                                        values("a", "b"))));
    }

    @Test
    public void testAllOutputsReferenced()
    {
        tester().assertThat(new PruneExplainAnalyzeSourceColumns())
                .on(p -> {
                    Symbol a = p.symbol("a");
                    Symbol b = p.symbol("b");
                    return p.explainAnalyzeNode(
                            p.symbol("query plan", VARCHAR),
                            ImmutableList.of(a, b),
                            p.values(a, b));
                })
                .doesNotFire();
    }
}


text:
local drive = require("drive")
local intake = require("intake")
local math = require("math")
local pid = require("pid")
local turret = require("turret")
local wpilib = require("wpilib")

module(...)

local dashboard = wpilib.SmartDashboard_GetInstance()

autoMode = nil
local fireCount = 0
local startedFiring = false
local driveStopped = false
local bridgeTimer = nil

local driveGains = {p=0.5, i=0, d=0.00}
local stableGains = {p=0.1, i=0, d=0}
local autodrivePIDX = pid.new()
autodrivePIDX.min, autodrivePIDX.max = -1, 1
local autodrivePIDY = pid.new()
autodrivePIDY.min, autodrivePIDY.max = -1, 1

Delay_1 = 3
Delay_2 = 4
Delay_3 = 4

local function setDriveAxis(axis)
    if axis == "x" then
        autodrivePIDX.p = driveGains.p
        autodrivePIDX.i = driveGains.i
        autodrivePIDX.d = driveGains.d
        autodrivePIDY.p = stableGains.p
        autodrivePIDY.i = stableGains.i
        autodrivePIDY.d = stableGains.d
    else
        autodrivePIDX.p = stableGains.p
        autodrivePIDX.i = stableGains.i
        autodrivePIDX.d = stableGains.d
        autodrivePIDY.p = driveGains.p
        autodrivePIDY.i = driveGains.i
        autodrivePIDY.d = driveGains.d
    end
end
setDriveAxis("y")

local fireTimer = nil
local FIRE_COOLDOWN = 0.5
local REPACK_COOLDOWN = 0.25

function run(extraUpdate)
    fireCount = 0
    startedFiring = false
    drive.resetFollowerPosition()
    drive.resetGyro()
    driveStopped = false
    bridgeTimer = nil

    local t = wpilib.Timer()
    t:Start()

    while wpilib.IsAutonomous() and wpilib.IsEnabled() do
        autoMode(t:Get())

        intake.update(true)
        turret.update()
        if extraUpdate then
            extraUpdate()
        end

        wpilib.Wait(0.005)
    end

    turret.fullStop()
    intake.fullStop()
    drive.undeployFollower()
    drive.setFrontSkid(true)
end

function calculateTurretTarget(x,y,gyro)
    return math.deg(-math.atan2(x,y)) - gyro
end

function fire()
    local fireCount = 0
    if fireTimer and fireTimer:Get() > FIRE_COOLDOWN then
        fireTimer = nil
        startedFiring = false
    end

    if fireTimer == nil then
        -- Ready to fire
        if intake.getLastBallSoftness() and startedFiring then
            fireTimer = wpilib.Timer()
            fireTimer:Start()
            fireCount = 1
        else
            intake.loadBall()
            startedFiring = true
        end
    else
        -- Cooldown
        intake.setVerticalSpeed(0.0)
    end
    turret.clearFlywheelFired()
    return fireCount
end

function stopFire()
    if fireTimer and fireTimer:Get() > FIRE_COOLDOWN then
        fireTimer = nil
        startedFiring = false
    end

    intake.setVerticalSpeed(0)
    turret.clearFlywheelFired()
end

-- For each autonomous mode, make sure you set:
--[[
1. Drive
2. Flywheel Speed
3. Intake speed
4. Fire/stopFire
5. Skid
--]]

function sittingKeyshot(t)
    turret.setTurretEnabled(false)
    turret.setPreset("key")
    if t < Delay_1 - 2 then
        turret.runFlywheel(false)
        stopFire()
    elseif t < Delay_1 then
        turret.runFlywheel(true)
        stopFire()
    else
        fireCount = fireCount + fire()
        turret.runFlywheel(true)
    end

end

function sittingKeyshotWithPass(t)
    turret.setTurretEnabled(false)
    turret.setPreset("key")
    if t < Delay_1 - 2 then
        turret.runFlywheel(false)
        stopFire()
        intake.setIntake(0.0)
    elseif t < Delay_1 then
        turret.runFlywheel(true)
        stopFire()
        intake.setIntake(0.0)
    elseif t < Delay_2 then
        turret.runFlywheel(true)
        fireCount = fireCount + fire()
        intake.setIntake(0.0)
    elseif t < Delay_3 then
        intake.setIntake(1.0)
        turret.runFlywheel(true)
        stopFire()
    else
        turret.runFlywheel(true)
        fireCount = fireCount + fire()
        intake.setIntake(1.0)
    end
end

function sittingKeyshotWithDropPass(t)
    turret.setTurretEnabled(false)
    turret.setPreset("key")
    if t < Delay_1 - 2 then
        turret.runFlywheel(false)
        stopFire()
        intake.setIntake(0.0)
    elseif t < Delay_1 then
        turret.runFlywheel(true)
        stopFire()
        intake.setIntake(0.0)
    elseif t < Delay_2 then
        turret.runFlywheel(true)
        fireCount = fireCount + fire()
        intake.setIntake(0.0)
    elseif t < Delay_3 then
        intake.setIntake(1.0)
        turret.runFlywheel(true)
        stopFire()
        intake.setLowered(true)
    else
        turret.runFlywheel(true)
        fireCount = fireCount + fire()
        intake.setIntake(1.0)
        intake.setLowered(true)
    end
end

function sittingKeyshotWithSlapPass(t)
    local SLAP_INTERVAL = 20
    turret.setTurretEnabled(false)
    turret.setPreset("key")
    if t < Delay_1 - 2 then
        turret.runFlywheel(false)
        stopFire()
        intake.setIntake(0.0)
    elseif t < Delay_1 then
        turret.runFlywheel(true)
        stopFire()
        intake.setIntake(0.0)
    elseif t < Delay_2 then
        turret.runFlywheel(true)
        fireCount = fireCount + fire()
        intake.setIntake(0.0)
    else
        intake.setIntake(1.0)
        turret.runFlywheel(true)
        if t < Delay_3 then
            stopFire()
        else
            fireCount = fireCount + fire()
        end
        intake.setLowered(math.floor((t-Delay_2)/SLAP_INTERVAL)%2 == 0)
    end
end

function keyShotWithCoOpBridge(t)
    local posx, posy = drive.getFollowerPosition()
    turret.setTurretEnabled(false)
    autodrivePIDX:update(posx)
    autodrivePIDY:update(posy)
    dashboard:PutDouble("Follower X", posx)
    dashboard:PutDouble("Follower Y", posy)
    drive.deployFollower()
    turret.setPreset("key")
    if t < Delay_1 - 2 then
        drive.setFrontSkid(false)
        turret.runFlywheel(true)
        stopFire()
        drive.run({x=0, y=0}, 0, 1)
        intake.setIntake(0.0)
    elseif t < Delay_1 then
        drive.setFrontSkid(false)
        turret.runFlywheel(true)
        stopFire()
        drive.run({x=0, y=0}, 0, 1)
        intake.setIntake(0.0)
    elseif t < Delay_2 then
        drive.setFrontSkid(true)
        turret.runFlywheel(true)
        if fireCount < 2 then
            fireCount = fireCount + fire()
            drive.run({x=0, y=0}, 0, 1)
        else
            stopFire()
            autodrivePIDX.target = 0.0
            autodrivePIDY.target = -4.0
            setDriveAxis("y")
            drive.run({x=autodrivePIDX.output, y=autodrivePIDY.output}, 0, 1)
        end
        intake.setIntake(1.0)
    else
        drive.setFrontSkid(true)
        turret.runFlywheel(true)
        if not drive.isFollowerStopped() then
            drive.run({x=autodrivePIDX.output, y=autodrivePIDY.output}, 0, 1)
        else
            drive.run({x=0, y=0}, 0, 1)
        end
        fireCount = fireCount + fire()
        intake.setIntake(1.0)
    end
end

local DISTANCE_TO_HOOP = 15

function keyShotWithCoOpBridgeFar(t)
    local CLOSE_BRIDGE_DISTANCE = -13
    local RPM_FUDGE = 100

    local posx, posy = drive.getFollowerPosition()

    turret.setTurretEnabled(true)
    autodrivePIDX:update(posx)
    autodrivePIDY:update(posy)
    dashboard:PutDouble("Follower X", posx)
    dashboard:PutDouble("Follower Y", posy)
    drive.deployFollower()
    turret.setPreset("key")

    if t < Delay_1 - 2 then
        drive.run({x=0, y=0}, 0, 1)
        turret.runFlywheel(false)
        intake.setIntake(0.0)
        stopFire()
        drive.setFrontSkid(false)
    elseif t < Delay_1 then
        drive.run({x=0, y=0}, 0, 1)
        turret.runFlywheel(true)
        intake.setIntake(0.0)
        stopFire()
        drive.setFrontSkid(false)
    elseif fireCount < 2 then
        -- After Delay_1, Fire two balls
        drive.run({x=0, y=0}, 0, 1)
        turret.runFlywheel(true)
        intake.setIntake(0.0)
        fireCount = fireCount + fire()
        drive.setFrontSkid(false)
    elseif not driveStopped then
        -- After firing two balls
        autodrivePIDX.target = 0.0
        autodrivePIDY.target = CLOSE_BRIDGE_DISTANCE
        autodrivePIDY.min, autodrivePIDY.max = -0.9, 0.9
        setDriveAxis("y")
        drive.run({x=autodrivePIDX.output, y=autodrivePIDY.output}, 0, 1)
        stopFire()

        intake.setIntake(1)
        drive.setFrontSkid(true)
        turret.setTargetAngle(calculateTurretTarget(posx, DISTANCE_TO_HOOP - posy, drive.normalizeAngle(-drive.getGyroAngle())))
        if posy/CLOSE_BRIDGE_DISTANCE > .9 and drive.isFollowerStopped() then
            driveStopped = true
            bridgeTimer = wpilib.Timer()
            bridgeTimer:Start()
        end
    else
        if bridgeTimer:Get() > 2 then
            intake.setLowered(true)
            autodrivePIDX.target = 0.0
            autodrivePIDY.target = 0.0
            autodrivePIDY.min, autodrivePIDY.max = -1.0, 1.0
            drive.run({x=autodrivePIDX.output, y=autodrivePIDY.output}, 0, 1)
        else
            intake.setLowered(false)
            drive.run({x=0, y=0}, 0, 1)
        end

        if t > Delay_3 then
            -- Fire continuous
            fireCount = fireCount + fire()
            turret.setTargetAngle(calculateTurretTarget(posx, DISTANCE_TO_HOOP - posy, drive.normalizeAngle(-drive.getGyroAngle())))
        else
            stopFire()
        end
    end
end

function lshape(t)
    local posx, posy = drive.getFollowerPosition()
    autodrivePIDX:update(posx)
    autodrivePIDY:update(posy)
    dashboard:PutDouble("Follower X", posx)
    dashboard:PutDouble("Follower Y", posy)

    intake.setIntake(0.0)
    turret.runFlywheel(false)
    stopFire()

    if t < Delay_1 then
        autodrivePIDX.target = 0.0
        autodrivePIDY.target = -4.0
        setDriveAxis("y")
        drive.run({x=autodrivePIDX.output, y=autodrivePIDY.output}, 0, 1)
    else
        autodrivePIDX.target = 4.0
        autodrivePIDY.target = -4.0
        setDriveAxis("x")
        drive.run({x=autodrivePIDX.output, y=autodrivePIDY.output}, 0, 1)
    end
end

function sittingKeyshotSafety(t)
    turret.setPreset("key")
    turret.setTurretEnabled(false)
    if t < Delay_1 - 2 then
        turret.runFlywheel(false)
        intake.setVerticalSpeed(0)
    elseif t < Delay_1 then
        turret.runFlywheel(true)
        intake.setVerticalSpeed(0)
    else
        intake.setVerticalSpeed(1)
        turret.runFlywheel(true)
    end
end

function sittingKeyshotWithPassSafety(t)
    turret.setPreset("key")
    turret.setTurretEnabled(false)
    if t < Delay_1 - 2 then
        turret.runFlywheel(false)
        intake.setVerticalSpeed(0)
        intake.setIntake(0.0)
    elseif t < Delay_1 then
        turret.runFlywheel(true)
        intake.setVerticalSpeed(0)
        intake.setIntake(0.0)
    elseif t < Delay_2 then
        turret.runFlywheel(true)
        intake.setVerticalSpeed(1)
        intake.setIntake(0.0)
    elseif t < Delay_3 then
        intake.setIntake(1.0)
        turret.runFlywheel(true)
        intake.setVerticalSpeed(0)
    else
        turret.runFlywheel(true)
        intake.setVerticalSpeed(1)
        intake.setIntake(1.0)
    end
end

autoMode = sittingKeyshot


text:
var codeBase = "file:///C:/arun/java/svn/trunk/cmtranslit/";
function includeFile(file) {
    document.write( '<script type="text/javascript" src="' + file + '"></script>' );
}
var Language = new Object();
var languages = new Array();

var interactiveTranslitlets = new Array();

includeFile(codeBase + "cmtranslit_base.js" );
includeFile(codeBase + "kt.js" );
includeFile(codeBase + "tamil.js" );
includeFile(codeBase + "english.js" );
includeFile(codeBase + "diacritics.js" );

function trim(s) { return s.replace(/^\s+|\s+$/, '') }

function clone(obj) {
    if(typeof(obj) != 'object') return obj;
    if(obj == null) return obj;
    var newObj = new Object();
    for(var i in obj) {
	newObj[i] = clone(obj[i]);
    }
    return newObj;
}

var _nTranslitlets = 0;

function processTranslitlets()
{
    if( !_nTranslitlets  ) {
	initTranslitletsSupport();
	var notationlets = new Array();
	renderTranslitlets(document.body, notationlets);
    }
}

function getTranslator(lang_spec)
{
    var re = /^(diacritics|english|tamil|sanskrit|kannada|telugu)(.*)$/i;
    var re_ret = re.exec(lang_spec);
    var translator = null;
    if( re_ret != null && re_ret.length > 1 ) {
	var dest_lang = re_ret[1].toLowerCase();
	var l = languages[dest_lang];
	if( l )
	    translator = clone(l);
	if( translator ) {
	    if( re_ret.length > 2 ) {
		var rest = trim(re_ret[2]);
		if( rest.indexOf(':') == 0 ) {
		    rest = rest.substr(1);
		    var attrs = rest.split(':');
		    for(var i = 0; i < attrs.length; i++ ) {
			var attr = trim(attrs[i].toLowerCase());
			if( attr != "" ) {
			    translator.setAttribute(attr);
			}
		    }
		}
	    }
	}
    }
    return translator;
}

function renderTranslitlets(p, results)
{
    if( p.className ) {
	var re = /cmtranslitlet_(.*)$/i;
	var re_ret = re.exec(p.className);
	if( re_ret != null && re_ret.length > 1 ) {
	    _nTranslitlets++;
	    var r = re_ret[1].toLowerCase();
	    if( re_ret[1].indexOf( "auto:" ) == 0 ) {
		var auto_spec = re_ret[1].substr(5);
		var lang_split = auto_spec.split('/');
		if( lang_split != null ) {
		    var rawContent = "" + p.innerHTML;
		    var content = "";
		    for(var i = 0; i < lang_split.length; i++ ) {
			var translator = getTranslator(lang_split[i].toLowerCase());
			if( i != 0 ) content += "/";
			if( translator ) {
			    content += translateHTML(rawContent, translator);
			}
		    }
		    p.innerHTML = content;
		    return;
		}
	    }
	    else {
		var translator = getTranslator(re_ret[1]);
		if( translator ) {
		    var txt = p.innerHTML;
		    var transl_txt = translateHTML(txt, translator);
		    if( transl_txt != null ) {
			p.innerHTML = transl_txt;
			return;
		    }
		}
	    }
	}
    }
    if( p.firstChild) {
	var c = p.firstChild;
	while( c ) {
	    renderTranslitlets(c, results);
	    c = c.nextSibling;
	}
    }
}

function _findInteractiveTranslitlets(p) {
    if( p.className && p.className.match(/^cmtranslitlet$/i) ) {
	var o = new Object();
	o.obj = p;
	o.content = p.innerHTML;
	interactiveTranslitlets[interactiveTranslitlets.length] = o;
    }
    if( p.firstChild) {
	var c = p.firstChild;
	while( c ) {
	    _findInteractiveTranslitlets(c);
	    c = c.nextSibling;
	}
    }
}

function renderTranslitletsInLanguage(langSpec) {
    var translator = getTranslator(langSpec);

    if( interactiveTranslitlets.length == 0 ) {
	_findInteractiveTranslitlets(document.body);
    }
    for(var i = 0; i < interactiveTranslitlets.length; i++ ) {
	var o   = interactiveTranslitlets[i];
	if( o ) {
	    var p = o.obj;
	    var transl_txt = null;

	    if( translator )
		transl_txt = translateHTML(o.content, translator);
	    if( transl_txt != null )
		p.innerHTML = transl_txt;
	    else
		p.innerHTML = o.content;
	}
    }
}

function initTranslitletsSupport()
{
    languages["sanskrit"]   =  new NonTamilBasicTranslator(NonTamilBasicTranslator.prototype.LANG_SANSKRIT);
    languages["english"]    =  new EnglishTranslator();
    languages["telugu"]      = new NonTamilBasicTranslator(NonTamilBasicTranslator.prototype.LANG_TELUGU);
    languages["tamil"]       = new TamilTranslator();
    languages["kannada"]     = new NonTamilBasicTranslator(NonTamilBasicTranslator.prototype.LANG_KANNADA);
    languages["malayalam"]   = new NonTamilBasicTranslator(NonTamilBasicTranslator.prototype.LANG_MALAYALAM);
    languages["diacritics"] = new DiacriticsTranslator();

    var id = document.getElementById("cmtranslit_choice");
    if( id != null ) {
	id.innerHTML = '<select id="__cmtranslit_choice" name="list" size="1" onchange="renderTranslitletsInLanguage(this.options[this.selectedIndex].value);">' +
			'<option value="english">English</option>' +
			'<option value="sanskrit">Sanskrit</option>' +
			'<option value="telugu">Telugu</option>' +
			'<option value="tamil:natural">Tamil</option>' +
			'<option value="kannada">Kannada</option>' +
			'<option value="english:raw">Raw Transliteration Input</option>' +
			'</select>';
	id = document.getElementById("__cmtranslit_choice");
	if( id ) {
	    id.selectedIndex = 0;
	    renderTranslitletsInLanguage("english");
	}
    }
}

var __d = document.body;
if( !__d ) __d = document;
if (__d.attachEvent)
    __d.attachEvent("onreadystatechange", processTranslitlets )
else
    __d.addEventListener('readystatechange',processTranslitlets, false);
if( window.attachEvent )
    window.attachEvent("onload", processTranslitlets );
else
    window.addEventListener("load",processTranslitlets,false);


text:
package org.ccnx.ccn.utils.explorer;

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

import org.ccnx.ccn.io.content.Link;
import org.ccnx.ccn.profiles.security.access.group.ACL;
import org.ccnx.ccn.profiles.security.access.group.ACL.ACLOperation;
import org.ccnx.ccn.protocol.Component;
import org.ccnx.ccn.protocol.ContentName;

public class ACLTable extends AbstractTableModel {

	private static final long serialVersionUID = 1L;

	private String[] columnNames = {"Principals", "Read", "Write", "Manage"};
	private int ACL_LENGTH = 3;
	private ContentName[] principals;
	private Object[][] aclTable;
	private ACL initialACL;

	public ACLTable(String type, ContentName[] principals, ACL initialACL) {
		columnNames[0] = type;
		this.principals = principals;
		if (initialACL != null) initializeACLTable(initialACL);
		else System.out.println("Fatal error: initial ACL cannot be null");
	}

	public void initializeACLTable(ACL initialACL) {
		this.initialACL = initialACL;
		aclTable = new Object[principals.length][ACL_LENGTH];
		for (int c=0; c<ACL_LENGTH; c++) {
			for (int r=0; r<principals.length; r++) {
				aclTable[r][c] = Boolean.FALSE;
			}
		}

		for (int i=0; i<initialACL.size(); i++) {
			Link lk = (Link) initialACL.get(i);
			ContentName principal = lk.targetName();
			String role = lk.targetLabel();
			this.setRole(principal, role);
		}
	}

	public int getColumnCount() {
		return columnNames.length;
	}

	public String getColumnName(int col) {
		return columnNames[col];
	}

	public int getRowCount() {
		return principals.length;
	}

	public Class<?> getColumnClass(int col) {
		return getValueAt(0, col).getClass();
	}

	public Object getValueAt(int row, int col) {
		if (col == 0) {
			String friendlyName = Component.printNative(principals[row].lastComponent());
			return friendlyName;
		}
		else if (col < 4) return aclTable[row][col-1];
		else return null;
	}

	public void setValueAt(Object value, int row, int col) {
		Boolean v = (Boolean) value;
		if (v.equals(Boolean.TRUE)) {
			for (int c=0; c<col; c++) {
				aclTable[row][c] = v;
				fireTableCellUpdated(row, c+1);
			}
		}
		else {
			for (int c=col-1; c < ACL_LENGTH; c++) {
				aclTable[row][c] = v;
				fireTableCellUpdated(row, c+1);
			}
		}
	}

	public boolean isCellEditable(int row, int col) {
		if (col == 0 ) return false;
		else return true;
	}

	public void cancelChanges() {
		initializeACLTable(initialACL);
		fireTableDataChanged();
	}

	public int getIndexOfPrincipal(ContentName principal) {
		int pos = -1;
		for (int i=0; i<principals.length; i++) {
			if (principal.compareTo(principals[i]) == 0) {
				pos = i;
				break;
			}
		}
		return pos;
	}

	public void setRole(ContentName principal, String role) {
		int pos = getIndexOfPrincipal(principal);
		if (pos > -1) {
			if (role.equals(ACL.LABEL_READER)) {
				aclTable[pos][0] = Boolean.TRUE;
				aclTable[pos][1] = Boolean.FALSE;
				aclTable[pos][2] = Boolean.FALSE;
			}
			if (role.equals(ACL.LABEL_WRITER)) {
				aclTable[pos][0] = Boolean.TRUE;
				aclTable[pos][1] = Boolean.TRUE;
				aclTable[pos][2] = Boolean.FALSE;
			}
			if (role.equals(ACL.LABEL_MANAGER)) {
				aclTable[pos][0] = Boolean.TRUE;
				aclTable[pos][1] = Boolean.TRUE;
				aclTable[pos][2] = Boolean.TRUE;
			}
		}
	}

	public String getRole(ContentName principal) {
		String role = null;
		int pos = getIndexOfPrincipal(principal);
		if (pos > -1) {
			if ((Boolean) aclTable[pos][2]) role = ACL.LABEL_MANAGER;
			else if ((Boolean) aclTable[pos][1]) role = ACL.LABEL_WRITER;
			else if ((Boolean) aclTable[pos][0]) role = ACL.LABEL_READER;
		}
		return role;
	}

	public ArrayList<ACLOperation> computeACLUpdates() {
		ArrayList<ACLOperation> ACLUpdates = new ArrayList<ACLOperation>();

		for (int i=0; i<principals.length; i++) {
			ContentName principal = principals[i];
			Link plk = new Link(principal);

			// get initial role
			String initialRole = null;
			for (int j=0; j<initialACL.size(); j++) {
				Link lk = (Link) initialACL.get(j);
				if (principal.compareTo(lk.targetName()) == 0) {
					initialRole = lk.targetLabel();
				}
			}

			// get final role
			String finalRole = getRole(principal);

			// compare initial and final role
			if (initialRole == null) {
				if (finalRole == null) continue;
				if (finalRole.equals(ACL.LABEL_READER)) ACLUpdates.add(ACLOperation.addReaderOperation(plk));
				else if (finalRole.equals(ACL.LABEL_WRITER)) ACLUpdates.add(ACLOperation.addWriterOperation(plk));
				else if (finalRole.equals(ACL.LABEL_MANAGER)) ACLUpdates.add(ACLOperation.addManagerOperation(plk));
			}
			else if (initialRole.equals(ACL.LABEL_READER)) {
				if (finalRole == null) ACLUpdates.add(ACLOperation.removeReaderOperation(plk));
				else if (finalRole.equals(ACL.LABEL_WRITER)) ACLUpdates.add(ACLOperation.addWriterOperation(plk));
				else if (finalRole.equals(ACL.LABEL_MANAGER)) ACLUpdates.add(ACLOperation.addManagerOperation(plk));
			}
			else if (initialRole.equals(ACL.LABEL_WRITER)) {
				if (finalRole == null) ACLUpdates.add(ACLOperation.removeWriterOperation(plk));
				else if (finalRole.equals(ACL.LABEL_READER)) {
					ACLUpdates.add(ACLOperation.removeWriterOperation(plk));
					ACLUpdates.add(ACLOperation.addReaderOperation(plk));
				}
				else if (finalRole.equals(ACL.LABEL_MANAGER)) ACLUpdates.add(ACLOperation.addManagerOperation(plk));
			}
			else if (initialRole.equals(ACL.LABEL_MANAGER)) {
				if (finalRole == null) ACLUpdates.add(ACLOperation.removeManagerOperation(plk));
				else if (finalRole.equals(ACL.LABEL_READER)) {
					ACLUpdates.add(ACLOperation.removeManagerOperation(plk));
					ACLUpdates.add(ACLOperation.addReaderOperation(plk));
				}
				else if (finalRole.equals(ACL.LABEL_WRITER)) {
					ACLUpdates.add(ACLOperation.removeManagerOperation(plk));
					ACLUpdates.add(ACLOperation.addWriterOperation(plk));
				}
			}
		}

		return ACLUpdates;
	}

}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150710_102458_part_over extends Migration
{
    public function up()
    {
        $this->createTable('part_over', [
            'id' => Schema::TYPE_PK,
            'code' => Schema::TYPE_STRING,
            'name' => Schema::TYPE_STRING . ' NOT NULL',
            'manufacture' => Schema::TYPE_STRING,
            'price' => Schema::TYPE_FLOAT,
            'quantity' => Schema::TYPE_INTEGER,
            'srokmin' => Schema::TYPE_INTEGER,
            'srokmax' => Schema::TYPE_INTEGER,
            'lotquantity' => Schema::TYPE_INTEGER,
            'pricedate' => Schema::TYPE_DATE,
            'skladid' => Schema::TYPE_INTEGER,
            'sklad' => Schema::TYPE_STRING,
            'flagpostav' => Schema::TYPE_STRING,
            'date_update' => Schema::TYPE_TIMESTAMP.' DEFAULT NOW()' ,
        ],'CHARACTER SET utf8 COLLATE utf8_general_ci');
        $this->createIndex('parts_unique','part_over',['code','name','flagpostav'],true);

    }
    public function down()
    {
        $this->dropTable('part_over');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
(function() {
  Navigation = function() {
    menu = document.querySelector(".menu-icon");
    trigger = document.querySelector(".menu-trigger");

    clicked = function() {
      return trigger.className.indexOf("triggered") > -1;
    },

    changeState = function() {
      if (clicked()) {
        hide();
      } else {
        show();
      }
    },

    show = function() {
      trigger.className = "menu-trigger triggered";
    },

    hide = function() {
      trigger.className = "menu-trigger trigger";
    }
  };

  Navigation.prototype.initialize = function() {
    var eventRegister = new EventRegister();
    eventRegister.add(menu, "click", changeState);
  };

}());


text:
package eu.matejkormuth.game.client.core.scene;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.matejkormuth.game.client.content.Content;
import eu.matejkormuth.game.client.content.ResourceInjectLocation;
import eu.matejkormuth.game.client.core.scene.nodetypes.Camera;
import eu.matejkormuth.game.client.gl.ICamera;
import eu.matejkormuth.game.shared.Disposable;

import java.util.List;

public class SceneInitializer {

    private static final Logger log = LoggerFactory.getLogger(SceneInitializer.class);

    private Node rootNode;
    private ICamera camera;

    public SceneInitializer(Node rootNode) {
        this.rootNode = rootNode;
    }

    public Node loadScene() {
        // Create scene graph.
        try {
            rootNode.createGraphBasedOnFields();
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        // Find camera or fail.
        for (Node node : rootNode.children) {
            if (node instanceof ICamera) {
                this.camera = (ICamera) node;
                break;
            }
        }
        if (this.camera == null) {
            log.error("Loaded scene does not contains camera!");
            log.warn("Creating default camera to allow scene render.");
            Camera cam = new Camera();
            rootNode.addChild(cam);
            this.camera = cam;
        }

        // Find resources in scene graph.
        List<ResourceInjectLocation> resources = rootNode.gatherResourceInjectLocations(null);

        // Load resources and inject them.
        for (ResourceInjectLocation resourceLoc : resources) {
            // Resource key should be in format category/folder/folder/name.ext

            Disposable resource = Content.provide(resourceLoc.annotation.value(), resourceLoc.resourceKey.split("/"));
            resourceLoc.inject(resource);
        }

        // Initialize resources (default values).

        // Finalize.

        // Go to render loop.
        return rootNode;
    }

    public ICamera getCamera() {
        return camera;
    }
}


text:
package net.ontopia.utils;

import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.TreeMap;

/**
 * INTERNAL: A sorted map which stores entries containing Collection
 * values. Any object can be used as key. The add(key,value) and
 * remove(key,value) makes sure that the Collection values are updated
 * correctly.

 *
 * The maintained index must only contain values implementing the
 * Collection interface. The data structure looks like this:
 * {key: [value, value, ...], key: [value, ...]}

 *
 * Empty entries are removed by default.

 */

public class CollectionSortedMap<K, V> extends TreeMap<K, Collection<V>> {

  protected boolean drop_empty = true;

  public CollectionSortedMap() {
  }

  public CollectionSortedMap(Comparator<K> c) {
    super(c);
  }

  // ----------------------------------------------------------------------------
  // Collection index values
  // ----------------------------------------------------------------------------

  protected Collection<V> createCollection() {
    return new HashSet<V>();
  }

  public void add(K key, V value) {

    // Get collection value
    Collection<V> coll = get(key);

    // Add to collection
    if (coll != null) {
      // Add new value
      coll.add(value);
    } else {
      // Create new collection
      coll = createCollection();
      coll.add(value);
      // Add new entry to index
      put(key, coll);
    }
  }

  //@Override disabled for java 7 backward compatibility
  public boolean remove(Object key, Object value) {

    // Get collection value
    Collection<V> coll = get(key);

    // Remove from collection
    if (coll != null) {
      // Remove value
      boolean removed = coll.remove(value);
      // Remove key
      if (drop_empty && coll.size() == 0) {
        remove(key);
      }

      return removed;
    }
    return false;
  }

  public void move(V value, K old_key, K new_key) {
    remove(old_key, value);
    add(new_key, value);
  }

  // public void replace(Object key, Object old_value, Object new_value) {
  //
  //   // Get collection value
  //   Collection coll = (Collection)get(key);
  //
  //   // Remove from collection
  //   if (coll != null) {
  //     // Remove value
  //     coll.remove(old_value);
  //     coll.add(new_value);
  //   } else {
  //     // Create new collection
  //     coll = createCollection();
  //     coll.add(new_value);
  //     // Add new entry to index
  //     put(key, coll);
  //   }
  //
  // }

  // public void replaceAll(Object key, Object old_value, Object new_value) {
  // }

}


text:
FactoryGirl.define do
  now = Time.new(2001,1,1,1,1)
  twenty_one_years_ago = Time.current - 21.years

  sequence(:dscc_number_helper) do |n|
    n
  end

  generate_dscc_number = -> do
    n = FactoryGirl.sequence_by_name(:dscc_number_helper).next
    prefix = (created_at || Time.now).strftime("%y%m")
    return "%s%05d%s" % [prefix, n, DsccNumberGenerator::DEFAULT_SUFFIX]
  end

  factory :defence_request do
    sequence(:detainee_name) { |n| "detainee_name-#{n}" }
    gender "male"
    date_of_birth twenty_one_years_ago
    custody_number "AN14574637587"
    offences "Theft"
    time_of_arrival now
    sequence(:comments) { |n| "commenty-comments-are here: #{n}" }
    adult [nil, true, false].sample
    appropriate_adult false
    fit_for_interview true
    interpreter_required false
    detainee_address_not_given "1"
    time_of_arrest now
    time_of_detention_authorised now
    circumstances_of_arrest "Caught with their hand in the cookie jar"
    custody_suite_uid { SecureRandom.uuid }
  end

  trait :draft do
    state "draft"
  end

  trait :queued do
    state "queued"
  end

  trait :acknowledged do
    state "acknowledged"
    association :cco, factory: :cco_user
  end

  trait :with_solicitor do
    association :solicitor, factory: :solicitor_user
  end

  trait :with_dscc_number do
    dscc_number &generate_dscc_number
  end

  trait :with_arrest_time do
    time_of_arrest DateTime.current
  end

  trait :with_detention_authorised_time do
    time_of_detention_authorised DateTime.current
  end

  trait :accepted do
    state "accepted"
    dscc_number &generate_dscc_number
    association :solicitor, factory: :solicitor_user
  end

  trait :aborted do
    dscc_number &generate_dscc_number
    reason_aborted "This has been closed for a reason."
    state "aborted"
  end

  trait :completed do
    state "completed"
  end

  trait :appropriate_adult do
    appropriate_adult true
    appropriate_adult_reason "detainee_juvenile"
  end

  trait :interview_start_time do
    interview_start_time now
  end

  trait :with_detainee_address do
    detainee_address_not_given "0"
    detainee_address "House on the Hill, Letsby Avenue, Right up my street, London, Greater London, XX1 1XX"
  end

  trait :with_investigating_officer do
    investigating_officer_name "Dave Mc.Copper"
    investigating_officer_contact_number "0207 111 0000"
  end

  trait :unfit_for_interview do
    fit_for_interview false
    unfit_for_interview_reason "Drunk as a skunk"
  end

  trait :with_interpreter_required do
    interpreter_required true
    interpreter_type "ENGLISH - GERMAN"
  end
end


text:
Virtual File Systems are used to abstract different file systems in a uniform
way. IntelliJ IDEA uses it for its representation of project files, and
Metaborg Core uses it for uniform access to resources, regardless of where
they physically live.

## IntelliJ VFS
IntelliJ IDEA uses its own Virtual File System, whose main class is the
`VirtualFile` class. It captures a snapshot of the physical file which is
periodically synchronized. You can find more information [here][1] and
[here][2].

The textual content of a file is represented by a `Document`.
[More information][3].

A file may be part of a PSI tree. In that case the file is a `PsiFile`
([more information][4]) and it contains PSI elements ([more information][5]).
Think of the PSI tree as a mix between an Abstract Syntax Tree and a Parse Tree,
but it also extends outside the file to represent the project that contains
the file.

```eval_rst
.. note:: While `VirtualFile` has an `exists()` method that can be used to
   check whether a file exists, it's also possible for functions such as the
   following to return `null` when the file is not found::

       this.file = LocalFileSystem.getInstance().refreshAndFindFileByPath("/home/user/test.txt");

```

## Apache VFS
Metaborg Core uses [Apache Commons VFS][6], which despite the similar name and
function is completely different from IntelliJ's VFS. An implementation of the
Apache VFS for IntelliJ resides in the [`org.metaborg.intellij.vfs`][7] package.

The default scheme for the implementation is `intellij://`, and any IntelliJ VFS
virtual files are resolved to Apache VFS file objects in the `intellij://`
file system using the [default implementation][8] of the
[`IIntelliJResourceService`][9].

[1]: http://www.jetbrains.org/intellij/sdk/docs/basics/virtual_file_system.html
[2]: http://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/virtual_file.html
[3]: http://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/documents.html
[4]: http://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi_files.html
[5]: http://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi_elements.html
[6]: https://commons.apache.org/proper/commons-vfs/
[7]: https://github.com/metaborg/spoofax-intellij/tree/develop/org.metaborg.intellij/src/main/java/org/metaborg/intellij/vfs
[8]: https://github.com/metaborg/spoofax-intellij/blob/develop/org.metaborg.intellij/src/main/java/org/metaborg/intellij/resources/DefaultIntelliJResourceService.java
[9]: https://github.com/metaborg/spoofax-intellij/blob/develop/org.metaborg.intellij/src/main/java/org/metaborg/intellij/resources/IIntelliJResourceService.java


text:
<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" >

    <include
        android:id="@+id/layout_title"
        layout="@layout/common_title" />

    <GridView
        android:id="@+id/id_gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/layout_title"
        android:cacheColorHint="@android:color/transparent"
        android:clipChildren="true"
        android:gravity="center"
        android:horizontalSpacing="3dip"
        android:listSelector="@android:color/transparent"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:verticalSpacing="3dip" >
    </GridView>

    <RelativeLayout
        android:id="@+id/id_bottom_ly"
        android:layout_width="match_parent"
        android:layout_height="50dip"
        android:layout_alignParentBottom="true"
        android:background="@color/title_background"
        android:clickable="true" >

        <TextView
            android:id="@+id/id_choose_dir"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:gravity="center_vertical"
            android:paddingLeft="10dip"
            android:text="所有图片"
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/id_total_count"
            android:layout_width="50dip"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:gravity="center"
            android:text="0张"
            android:textColor="@android:color/white" />
    </RelativeLayout>

</RelativeLayout>


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Automation;

namespace Azure.ResourceManager.Automation.Models
{
    /// <summary> The response model for the list connection type operation. </summary>
    internal partial class AutomationConnectionTypeListResult
    {
        /// <summary> Initializes a new instance of AutomationConnectionTypeListResult. </summary>
        internal AutomationConnectionTypeListResult()
        {
            Value = new ChangeTrackingList<AutomationConnectionTypeData>();
        }

        /// <summary> Initializes a new instance of AutomationConnectionTypeListResult. </summary>
        /// <param name="value"> Gets or sets a list of connection types. </param>
        /// <param name="nextLink"> Gets or sets the next link. </param>
        internal AutomationConnectionTypeListResult(IReadOnlyList<AutomationConnectionTypeData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Gets or sets a list of connection types. </summary>
        public IReadOnlyList<AutomationConnectionTypeData> Value { get; }
        /// <summary> Gets or sets the next link. </summary>
        public string NextLink { get; }
    }
}


text:
package java.util.function;

import static javaemul.internal.InternalPreconditions.checkCriticalNotNull;

import org.jspecify.nullness.NullMarked;
import org.jspecify.nullness.Nullable;

/**
 * See the
 * official Java API doc for details.
 *
 * @param <T> type of the first argument
 * @param  type of the second argument
 * @param <R> type of the return value
 */
@FunctionalInterface
@NullMarked
public interface BiFunction<
    T extends @Nullable Object, U extends @Nullable Object, R extends @Nullable Object> {

  R apply(T t, U u);

  default <V extends @Nullable Object> BiFunction<T, U, V> andThen(
      Function<? super R, ? extends V> after) {
    checkCriticalNotNull(after);
    return (t, u) -> after.apply(apply(t, u));
  }
}


text:
package mount

import (
	"time"
)

// GetMounts retrieves a list of mounts for the current running process.
func GetMounts() ([]*Info, error) {
	return parseMountTable()
}

// Mounted determines if a specified mountpoint has been mounted.
// On Linux it looks at /proc/self/mountinfo and on Solaris at mnttab.
func Mounted(mountpoint string) (bool, error) {
	entries, err := parseMountTable()
	if err != nil {
		return false, err
	}

	// Search the table for the mountpoint
	for _, e := range entries {
		if e.Mountpoint == mountpoint {
			return true, nil
		}
	}
	return false, nil
}

// Mount will mount filesystem according to the specified configuration, on the
// condition that the target path is *not* already mounted. Options must be
// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See
// flags.go for supported option flags.
func Mount(device, target, mType, options string) error {
	flag, _ := parseOptions(options)
	if flag&REMOUNT != REMOUNT {
		if mounted, err := Mounted(target); err != nil || mounted {
			return err
		}
	}
	return ForceMount(device, target, mType, options)
}

// ForceMount will mount a filesystem according to the specified configuration,
// *regardless* if the target path is not already mounted. Options must be
// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See
// flags.go for supported option flags.
func ForceMount(device, target, mType, options string) error {
	flag, data := parseOptions(options)
	if err := mount(device, target, mType, uintptr(flag), data); err != nil {
		return err
	}
	return nil
}

// Unmount will unmount the target filesystem, so long as it is mounted.
func Unmount(target string) error {
	if mounted, err := Mounted(target); err != nil || !mounted {
		return err
	}
	return ForceUnmount(target)
}

// ForceUnmount will force an unmount of the target filesystem, regardless if
// it is mounted or not.
func ForceUnmount(target string) (err error) {
	// Simple retry logic for unmount
	for i := 0; i < 10; i++ {
		if err = unmount(target, 0); err == nil {
			return nil
		}
		time.Sleep(100 * time.Millisecond)
	}
	return
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.feed.library.feedprotocoladapter.internal.transformers;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;

import org.chromium.components.feed.core.proto.libraries.api.internal.StreamDataProto.ClientBasicLoggingMetadata;
import org.chromium.components.feed.core.proto.libraries.api.internal.StreamDataProto.StreamDataOperation;
import org.chromium.components.feed.core.proto.libraries.api.internal.StreamDataProto.StreamFeature;
import org.chromium.components.feed.core.proto.libraries.api.internal.StreamDataProto.StreamPayload;
import org.chromium.components.feed.core.proto.ui.stream.StreamStructureProto.BasicLoggingMetadata;
import org.chromium.components.feed.core.proto.ui.stream.StreamStructureProto.Content;
import org.chromium.components.feed.core.proto.ui.stream.StreamStructureProto.Content.Type;
import org.chromium.components.feed.core.proto.wire.DataOperationProto.DataOperation;
import org.chromium.components.feed.core.proto.wire.FeatureProto.Feature;
import org.chromium.components.feed.core.proto.wire.FeatureProto.Feature.RenderableUnit;
import org.chromium.components.feed.core.proto.wire.FeedResponseProto.FeedResponseMetadata;
import org.chromium.testing.local.LocalRobolectricTestRunner;

/** Tests for {@link ContentDataOperationTransformer}. */
@RunWith(LocalRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ContentDataOperationTransformerTest {
    private static final String CONTENT_ID = "content-11";
    private static final long RESPONSE_TIME = 1000;
    private static final FeedResponseMetadata METADATA =
            FeedResponseMetadata.newBuilder().setResponseTimeMs(RESPONSE_TIME).build();
    private ContentDataOperationTransformer mContentDataOperationTransformer;
    private DataOperation.Builder mDataOperation;
    private StreamDataOperation.Builder mDataOperationBuilder;
    private StreamFeature mStreamFeature;

    @Before
    public void setUp() {
        mContentDataOperationTransformer = new ContentDataOperationTransformer();
        mDataOperation = DataOperation.newBuilder();
        mStreamFeature = StreamFeature.newBuilder().setContentId(CONTENT_ID).build();
        mDataOperationBuilder = StreamDataOperation.newBuilder().setStreamPayload(
                StreamPayload.newBuilder().setStreamFeature(mStreamFeature));
    }

    @Test
    public void transform_setsContent() {
        BasicLoggingMetadata basicLoggingMetadata =
                BasicLoggingMetadata.newBuilder().setScore(.2f).build();
        ClientBasicLoggingMetadata clientBasicLoggingMetadata =
                ClientBasicLoggingMetadata.newBuilder()
                        .setAvailabilityTimeSeconds(RESPONSE_TIME)
                        .build();
        Content content = Content.newBuilder()
                                  .setType(Type.UNKNOWN_CONTENT)
                                  .setBasicLoggingMetadata(basicLoggingMetadata)
                                  .build();
        mDataOperation.setFeature(Feature.newBuilder()
                                          .setExtension(Content.contentExtension, content)
                                          .setRenderableUnit(RenderableUnit.CONTENT));

        StreamDataOperation.Builder operation = mContentDataOperationTransformer.transform(
                mDataOperation.build(), mDataOperationBuilder, METADATA);

        assertThat(operation.getStreamPayload().getStreamFeature().getContent())
                .isEqualTo(
                        content.toBuilder()
                                .setBasicLoggingMetadata(
                                        basicLoggingMetadata.toBuilder()
                                                .setExtension(ClientBasicLoggingMetadata
                                                                      .clientBasicLoggingMetadata,
                                                        clientBasicLoggingMetadata)
                                                .build())
                                .build());
    }

    @Test
    public void transform_responseTimeNotSet() {
        mDataOperation.setFeature(
                Feature.newBuilder()
                        .setExtension(Content.contentExtension, Content.getDefaultInstance())
                        .setRenderableUnit(RenderableUnit.CONTENT));
        StreamDataOperation.Builder operation =
                mContentDataOperationTransformer.transform(mDataOperation.build(),
                        mDataOperationBuilder, FeedResponseMetadata.getDefaultInstance());

        assertThat(operation).isSameInstanceAs(mDataOperationBuilder);
    }

    @Test
    public void transform_featureIsNotContent() {
        StreamDataOperation.Builder operation = mContentDataOperationTransformer.transform(
                mDataOperation.build(), mDataOperationBuilder, METADATA);

        assertThat(operation).isSameInstanceAs(mDataOperationBuilder);
    }
}


text:
<!DOCTYPE html>

<?php $thisPage="listen"; ?>
<?php $section="main"; ?>

    <?php include "phpincludes/head.php"; ?>

    <?php include "phpincludes/nav.php"; ?>


text:
source "$(dirname "${BASH_SOURCE}")/../../hack/lib/init.sh"
trap os::test::junit::reconcile_output EXIT

# Cleanup cluster resources created by this test
(
  set +e
  exit 0
) &>/dev/null

os::test::junit::declare_suite_start "cmd/observe"

# basic scenarios
os::cmd::expect_failure_and_text 'oc observe' 'you must specify at least one argument containing the resource to observe'
os::cmd::expect_success_and_text 'oc observe serviceaccounts --once' 'Sync ended'
os::cmd::expect_success_and_text 'oc observe daemonsets --once' 'Nothing to sync, exiting immediately'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces' 'default kubernetes'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces --print-metrics-on-exit' 'observe_counts{type="Sync"}'
os::cmd::expect_failure_and_text 'oc observe services --once --names echo' '\-\-delete and \-\-names must both be specified'
os::cmd::expect_success_and_text 'oc observe services --exit-after=1s' 'Shutting down after 1s ...'
os::cmd::expect_success_and_text 'oc observe services --exit-after=1s --all-namespaces --print-metrics-on-exit' 'observe_counts{type="Sync"}'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces' 'default kubernetes'
# TODO: fix #31755 and make this a --once test
os::cmd::expect_success_and_text 'oc observe services --exit-after=3s --all-namespaces --names echo --names default/notfound --delete echo --delete remove' 'remove default notfound'

# error counting
os::cmd::expect_failure_and_text 'oc observe services --exit-after=1m --all-namespaces --maximum-errors=1 -- /bin/sh -c "exit 1"' 'reached maximum error limit of 1, exiting'
os::cmd::expect_failure_and_text 'oc observe services --exit-after=1m --all-namespaces --retry-on-exit-code=2 --maximum-errors=1 --loglevel=4 -- /bin/sh -c "exit 2"' 'retrying command: exit status 2'

# argument templates
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces -a "{ .spec.clusterIP }"' '10.3.0.1'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces -a "{{ .spec.clusterIP }}" --output=gotemplate' '10.3.0.1'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces -a "bad{ .missingkey }key"' 'badkey'
os::cmd::expect_failure_and_text 'oc observe services --once --all-namespaces -a "bad{ .missingkey }key" --strict-templates' 'missingkey is not found'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces -a "{{ .unknown }}" --output=gotemplate' '""'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces -a "bad{{ or (.unknown) \"\" }}key" --output=gotemplate' 'badkey'
os::cmd::expect_success_and_text 'oc observe services --once --all-namespaces -a "bad{{ .unknown }}key" --output=gotemplate --strict-templates' '\<no value\>'

# --type-env-var
os::cmd::expect_success_and_text 'MYENV=should_be_passed oc observe services --once --all-namespaces --type-env-var=EVENT -- /bin/sh -c "echo \$EVENT \$MYENV"' 'Sync should_be_passed'

echo "observe: ok"
os::test::junit::declare_suite_end