text:
if(!dojo._hasResource["dijit._editor.range"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit._editor.range"] = true;
dojo.provide("dijit._editor.range");

dijit.range={};

dijit.range.getIndex=function(/*DomNode*/node, /*DomNode*/parent){
//	dojo.profile.start("dijit.range.getIndex");
	var ret=[], retR=[];
	var stop = parent;
	var onode = node;

	var pnode, n;
	while(node != stop){
		var i = 0;
		pnode = node.parentNode;
		while((n=pnode.childNodes[i++])){
			if(n===node){
				--i;
				break;
			}
		}
		if(i>=pnode.childNodes.length){
			dojo.debug("Error finding index of a node in dijit.range.getIndex");
		}
		ret.unshift(i);
		retR.unshift(i-pnode.childNodes.length);
		node = pnode;
	}

	//normalized() can not be called so often to prevent
	//invalidating selection/range, so we have to detect
	//here that any text nodes in a row
	if(ret.length>0 && onode.nodeType==3){
		n = onode.previousSibling;
		while(n && n.nodeType==3){
			ret[ret.length-1]--;
			n = n.previousSibling;
		}
		n = onode.nextSibling;
		while(n && n.nodeType==3){
			retR[retR.length-1]++;
			n = n.nextSibling;
		}
	}
//	dojo.profile.end("dijit.range.getIndex");
	return {o: ret, r:retR};
}

dijit.range.getNode = function(/*Array*/index, /*DomNode*/parent){
	if(!dojo.isArray(index) || index.length==0){
		return parent;
	}
	var node = parent;
//	if(!node)debugger
	dojo.every(index, function(i){
		if(i>=0&&i< node.childNodes.length){
			node = node.childNodes[i];
		}else{
			node = null;
			console.debug('Error: can not find node with index',index,'under parent node',parent );
			return false; //terminate dojo.every
		}
		return true; //carry on the every loop
	});

	return node;
}

dijit.range.getCommonAncestor = function(n1,n2,root){
	var getAncestors = function(n,root){
		var as=[];
		while(n){
			as.unshift(n);
			if(n!=root && n.tagName!='BODY'){
				n = n.parentNode;
			}else{
				break;
			}
		}
		return as;
	};
	var n1as = getAncestors(n1,root);
	var n2as = getAncestors(n2,root);

	var m = Math.min(n1as.length,n2as.length);
	var com = n1as[0]; //at least, one element should be in the array: the root (BODY by default)
	for(var i=1;i<m;i++){
		if(n1as[i]===n2as[i]){
			com = n1as[i]
		}else{
			break;
		}
	}
	return com;
}

dijit.range.getAncestor = function(/*DomNode*/node, /*RegEx?*/regex, /*DomNode?*/root){
	root = root || node.ownerDocument.body;
	while(node && node !== root){
		var name = node.nodeName.toUpperCase() ;
		if(regex.test(name)){
			return node;
		}

		node = node.parentNode;
	}
	return null;
}

dijit.range.BlockTagNames = /^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/;
dijit.range.getBlockAncestor = function(/*DomNode*/node, /*RegEx?*/regex, /*DomNode?*/root){
	root = root || node.ownerDocument.body;
	regex = regex || dijit.range.BlockTagNames;
	var block=null, blockContainer;
	while(node && node !== root){
		var name = node.nodeName.toUpperCase() ;
		if(!block && regex.test(name)){
			block = node;
		}
		if(!blockContainer && (/^(?:BODY|TD|TH|CAPTION)$/).test(name)){
			blockContainer = node;
		}

		node = node.parentNode;
	}
	return {blockNode:block, blockContainer:blockContainer || node.ownerDocument.body};
}

dijit.range.atBeginningOfContainer = function(/*DomNode*/container, /*DomNode*/node, /*Int*/offset){
	var atBeginning = false;
	var offsetAtBeginning = (offset == 0);
	if(!offsetAtBeginning && node.nodeType==3){ //if this is a text node, check whether the left part is all space
		if(dojo.trim(node.nodeValue.substr(0,offset))==0){
			offsetAtBeginning = true;
		}
	}
	if(offsetAtBeginning){
		var cnode = node;
		atBeginning = true;
		while(cnode && cnode !== container){
			if(cnode.previousSibling){
				atBeginning = false;
				break;
			}
			cnode = cnode.parentNode;
		}
	}
	return atBeginning;
}

dijit.range.atEndOfContainer = function(/*DomNode*/container, /*DomNode*/node, /*Int*/offset){
	var atEnd = false;
	var offsetAtEnd = (offset == (node.length || node.childNodes.length));
	if(!offsetAtEnd && node.nodeType==3){ //if this is a text node, check whether the right part is all space
		if(dojo.trim(node.nodeValue.substr(offset))==0){
			offsetAtEnd = true;
		}
	}
	if(offsetAtEnd){
		var cnode = node;
		atEnd = true;
		while(cnode && cnode !== container){
			if(cnode.nextSibling){
				atEnd = false;
				break;
			}
			cnode = cnode.parentNode;
		}
	}
	return atEnd;
}

dijit.range.adjacentNoneTextNode=function(startnode, next){
	var node = startnode;
	var len = (0-startnode.length) || 0;
	var prop = next?'nextSibling':'previousSibling';
	while(node){
		if(node.nodeType!=3){
			break;
		}
		len += node.length
		node = node[prop];
	}
	return [node,len];
}

dijit.range._w3c = Boolean(window['getSelection']);
dijit.range.create = function(){
	if(dijit.range._w3c){
		return dojo.doc.createRange();
	}else{//IE
		return new dijit.range.W3CRange;
	}
}

dijit.range.getSelection = function(win, /*Boolean?*/ignoreUpdate){
	if(dijit.range._w3c){
		return win.getSelection();
	}else{//IE
		var id=win.__W3CRange,s;
		if(!id || !dijit.range.ie.cachedSelection[id]){
			s = new dijit.range.ie.selection(win);
			//use win as the key in an object is not reliable, which
			//can leads to quite odd behaviors. thus we generate a
			//string and use it as a key in the cache
			id=(new Date).getTime();
			while(id in dijit.range.ie.cachedSelection){
				id=id+1;
			}
			id=String(id);
			dijit.range.ie.cachedSelection[id] = s;
		}else{
			s = dijit.range.ie.cachedSelection[id];
		}
		if(!ignoreUpdate){
			s._getCurrentSelection();
		}
		return s;
	}
}

if(!dijit.range._w3c){
	dijit.range.ie={
		cachedSelection: {},
		selection: function(win){
			this._ranges = [];
			this.addRange = function(r, /*boolean*/internal){
				this._ranges.push(r);
				if(!internal){
					r._select();
				}
				this.rangeCount = this._ranges.length;
			};
			this.removeAllRanges = function(){
				//don't detach, the range may be used later
//				for(var i=0;i<this._ranges.length;i++){
//					this._ranges[i].detach();
//				}
				this._ranges = [];
				this.rangeCount = 0;
			};
			var _initCurrentRange = function(){
				var r = win.document.selection.createRange();
				var type=win.document.selection.type.toUpperCase();
				if(type == "CONTROL"){
					//TODO: multiple range selection(?)
					return new dijit.range.W3CRange(dijit.range.ie.decomposeControlRange(r));
				}else{
					return new dijit.range.W3CRange(dijit.range.ie.decomposeTextRange(r));
				}
			};
			this.getRangeAt = function(i){
				return this._ranges[i];
			};
			this._getCurrentSelection = function(){
				this.removeAllRanges();
				var r=_initCurrentRange();
				if(r){
					this.addRange(r, true);
				}
			};
		},
		decomposeControlRange: function(range){
			var firstnode = range.item(0), lastnode = range.item(range.length-1)
			var startContainer = firstnode.parentNode, endContainer = lastnode.parentNode;
			var startOffset = dijit.range.getIndex(firstnode, startContainer).o;
			var endOffset = dijit.range.getIndex(lastnode, endContainer).o+1;
			return [[startContainer, startOffset],[endContainer, endOffset]];
		},
		getEndPoint: function(range, end){
			var atmrange = range.duplicate();
			atmrange.collapse(!end);
			var cmpstr = 'EndTo' + (end?'End':'Start');
			var parentNode = atmrange.parentElement();

			var startnode, startOffset, lastNode;
			if(parentNode.childNodes.length>0){
				dojo.every(parentNode.childNodes, function(node,i){
					var calOffset;
					if(node.nodeType != 3){
						atmrange.moveToElementText(node);

						if(atmrange.compareEndPoints(cmpstr,range) > 0){
							startnode = node.previousSibling;
							if(lastNode && lastNode.nodeType == 3){
								//where share we put the start? in the text node or after?
								startnode = lastNode;
								calOffset = true;
							}else{
								startnode = parentNode;
								startOffset = i;
								return false;
							}
						}else{
							if(i==parentNode.childNodes.length-1){
								startnode = parentNode;
								startOffset = parentNode.childNodes.length;
								return false;
							}
						}
					}else{
						if(i==parentNode.childNodes.length-1){//at the end of this node
							startnode = node;
							calOffset = true;
						}
					}
		//			try{
						if(calOffset && startnode){
							var prevnode = dijit.range.adjacentNoneTextNode(startnode)[0];
							if(prevnode){
								startnode = prevnode.nextSibling;
							}else{
								startnode = parentNode.firstChild; //firstChild must be a text node
							}
							var prevnodeobj = dijit.range.adjacentNoneTextNode(startnode);
							prevnode = prevnodeobj[0];
							var lenoffset = prevnodeobj[1];
							if(prevnode){
								atmrange.moveToElementText(prevnode);
								atmrange.collapse(false);
							}else{
								atmrange.moveToElementText(parentNode);
							}
							atmrange.setEndPoint(cmpstr, range);
							startOffset = atmrange.text.length-lenoffset;

							return false;
						}
		//			}catch(e){ debugger }
					lastNode = node;
					return true;
				});
			}else{
				startnode = parentNode;
				startOffset = 0;
			}

			//if at the end of startnode and we are dealing with start container, then
			//move the startnode to nextSibling if it is a text node
			//TODO: do this for end container?
			if(!end && startnode.nodeType!=3 && startOffset == startnode.childNodes.length){
				if(startnode.nextSibling && startnode.nextSibling.nodeType==3){
					startnode = startnode.nextSibling;
					startOffset = 0;
				}
			}
			return [startnode, startOffset];
		},
		setEndPoint: function(range, container, offset){
			//text node
			var atmrange = range.duplicate(), node, len;
			if(container.nodeType!=3){ //normal node
				atmrange.moveToElementText(container);
				atmrange.collapse(true);
				if(offset == container.childNodes.length){
					if(offset > 0){
						//a simple atmrange.collapse(false); won't work here:
						//although moveToElementText(node) is supposed to encompass the content of the node,
						//but when collapse to end, it is in fact after the ending tag of node (collapse to start
						//is after the begining tag of node as expected)
						node = container.lastChild;
						len = 0;
						while(node && node.nodeType == 3){
							len += node.length;
							container = node; //pass through
							node = node.previousSibling;
						}
						if(node){
							atmrange.moveToElementText(node);
						}
						atmrange.collapse(false);
						offset = len; //pass through
					}else{ //no childNodes
						atmrange.moveToElementText(container);
						atmrange.collapse(true);
					}
				}else{
					if(offset > 0){
						node = container.childNodes[offset-1];
						if(node.nodeType==3){
							container = node;
							offset = node.length;
							//pass through
						}else{
							atmrange.moveToElementText(node);
							atmrange.collapse(false);
						}
					}
				}
			}
			if(container.nodeType==3){
				var prevnodeobj = dijit.range.adjacentNoneTextNode(container);
				var prevnode = prevnodeobj[0];
				len = prevnodeobj[1];
				if(prevnode){
					atmrange.moveToElementText(prevnode);
					atmrange.collapse(false);
					//if contentEditable is not inherit, the above collapse won't make the end point
					//in the correctly position: it always has a -1 offset, so compensate it
					if(prevnode.contentEditable!='inherit'){
						len++;
					}
				}else{
					atmrange.moveToElementText(container.parentNode);
					atmrange.collapse(true);
				}

				offset += len;
				if(offset>0){
					if(atmrange.moveEnd('character',offset) != offset){
						alert('Error when moving!');
					}
					atmrange.collapse(false);
				}
			}

			return atmrange;
		},
		decomposeTextRange: function(range){
			var tmpary = dijit.range.ie.getEndPoint(range);
			var startContainter = tmpary[0], startOffset = tmpary[1];
			var endContainter = tmpary[0], endOffset = tmpary[1];

			if(range.htmlText.length){
				if(range.htmlText == range.text){ //in the same text node
					endOffset = startOffset+range.text.length;
				}else{
					tmpary = dijit.range.ie.getEndPoint(range,true);
					endContainter = tmpary[0], endOffset = tmpary[1];
				}
			}
			return [[startContainter, startOffset],[endContainter, endOffset], range.parentElement()];
		},
		setRange: function(range, startContainter,
			startOffset, endContainter, endOffset, check){
			var startrange = dijit.range.ie.setEndPoint(range, startContainter, startOffset);
			range.setEndPoint('StartToStart', startrange);
			if(!this.collapsed){
				var endrange = dijit.range.ie.setEndPoint(range, endContainter, endOffset);
				range.setEndPoint('EndToEnd', endrange);
			}

			return range;
		}
	}

dojo.declare("dijit.range.W3CRange",null, {
	constructor: function(){
		if(arguments.length>0){
			this.setStart(arguments[0][0][0],arguments[0][0][1]);
			this.setEnd(arguments[0][1][0],arguments[0][1][1],arguments[0][2]);
		}else{
			this.commonAncestorContainer = null;
			this.startContainer = null;
			this.startOffset = 0;
			this.endContainer = null;
			this.endOffset = 0;
			this.collapsed = true;
		}
	},
	_simpleSetEndPoint: function(node, range, end){
		var r = (this._body||node.ownerDocument.body).createTextRange();
		if(node.nodeType!=1){
			r.moveToElementText(node.parentNode);
		}else{
			r.moveToElementText(node);
		}
		r.collapse(true);
		range.setEndPoint(end?'EndToEnd':'StartToStart',r);
	},
	_updateInternal: function(__internal_common){
		if(this.startContainer !== this.endContainer){
			if(!__internal_common){
				var r = (this._body||this.startContainer.ownerDocument.body).createTextRange();
				this._simpleSetEndPoint(this.startContainer,r);
				this._simpleSetEndPoint(this.endContainer,r,true);
				__internal_common = r.parentElement();
			}
			this.commonAncestorContainer = dijit.range.getCommonAncestor(this.startContainer, this.endContainer, __internal_common);
		}else{
			this.commonAncestorContainer = this.startContainer;
		}
		this.collapsed = (this.startContainer === this.endContainer) && (this.startOffset == this.endOffset);
	},
	setStart: function(node, offset, __internal_common){
		offset=parseInt(offset);
		if(this.startContainer === node && this.startOffset == offset){
			return;
		}
		delete this._cachedBookmark;

		this.startContainer = node;
		this.startOffset = offset;
		if(!this.endContainer){
			this.setEnd(node, offset, __internal_common);
		}else{
			this._updateInternal(__internal_common);
		}
	},
	setEnd: function(node, offset, __internal_common){
		offset=parseInt(offset);
		if(this.endContainer === node && this.endOffset == offset){
			return;
		}
		delete this._cachedBookmark;

		this.endContainer = node;
		this.endOffset = offset;
		if(!this.startContainer){
			this.setStart(node, offset, __internal_common);
		}else{
			this._updateInternal(__internal_common);
		}
	},
	setStartAfter: function(node, offset){
		this._setPoint('setStart', node, offset, 1);
	},
	setStartBefore: function(node, offset){
		this._setPoint('setStart', node, offset, 0);
	},
	setEndAfter: function(node, offset){
		this._setPoint('setEnd', node, offset, 1);
	},
	setEndBefore: function(node, offset){
		this._setPoint('setEnd', node, offset, 0);
	},
	_setPoint: function(what, node, offset, ext){
		var index = dijit.range.getIndex(node, node.parentNode).o;
		this[what](node.parentNode, index.pop()+ext);
	},
	_getIERange: function(){
		var r=(this._body||this.endContainer.ownerDocument.body).createTextRange();
		dijit.range.ie.setRange(r, this.startContainer, this.startOffset, this.endContainer, this.endOffset);
		return r;
	},
	getBookmark: function(body){
		this._getIERange();
		return this._cachedBookmark;
	},
	_select: function(){
		var r = this._getIERange();
		r.select();
	},
	deleteContents: function(){
		var r = this._getIERange();
		r.pasteHTML('');
		this.endContainer = this.startContainer;
		this.endOffset = this.startOffset;
		this.collapsed = true;
	},
	cloneRange: function(){
		var r = new dijit.range.W3CRange([[this.startContainer,this.startOffset],
			[this.endContainer,this.endOffset]]);
		r._body = this._body;
		return r;
	},
	detach: function(){
		this._body = null;
		this.commonAncestorContainer = null;
		this.startContainer = null;
		this.startOffset = 0;
		this.endContainer = null;
		this.endOffset = 0;
		this.collapsed = true;
}
});
} //if(!dijit.range._w3c)

}


text:
using ::testing::AnyNumber;
using ::testing::AtLeast;
using ::testing::InSequence;
using ::testing::StrictMock;
using ::testing::_;

using google_apis::DriveServiceInterface;
using google_apis::DriveUploaderInterface;
using google_apis::test_util::LoadJSONFile;

namespace sync_file_system {

namespace {

const char kSyncRootDirectoryName[] = "Chrome Syncable FileSystem";

FilePath::StringType ASCIIToFilePathString(const std::string& path) {
  return FilePath().AppendASCII(path).value();
}

void DidInitialize(bool* done, fileapi::SyncStatusCode status, bool created) {
  EXPECT_FALSE(*done);
  *done = true;
  EXPECT_EQ(fileapi::SYNC_STATUS_OK, status);
  EXPECT_TRUE(created);
}

void ExpectEqStatus(bool* done,
                    fileapi::SyncStatusCode expected,
                    fileapi::SyncStatusCode actual) {
  EXPECT_FALSE(*done);
  *done = true;
  EXPECT_EQ(expected, actual);
}

}  // namespace

class MockRemoteServiceObserver : public RemoteFileSyncService::Observer {
 public:
  MockRemoteServiceObserver() {}
  virtual ~MockRemoteServiceObserver() {}

  // LocalChangeProcessor override.
  MOCK_METHOD1(OnRemoteChangeAvailable,
               void(int64 pending_changes));
  MOCK_METHOD2(OnRemoteServiceStateUpdated,
               void(RemoteServiceState state,
                    const std::string& description));
};

class DriveFileSyncServiceTest : public testing::Test {
 public:
  DriveFileSyncServiceTest()
      : mock_drive_service_(NULL) {
  }

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(fileapi::RegisterSyncableFileSystem(
        DriveFileSyncService::kServiceName));

    mock_drive_service_ = new StrictMock<google_apis::MockDriveService>;

    EXPECT_CALL(*mock_drive_service(),
                Initialize(&profile_)).Times(1);

    sync_client_ = DriveFileSyncClient::CreateForTesting(
        &profile_,
        scoped_ptr<DriveServiceInterface>(mock_drive_service_),
        scoped_ptr<DriveUploaderInterface>()).Pass();
    ASSERT_TRUE(base_dir_.CreateUniqueTempDir());
    metadata_store_.reset(new DriveMetadataStore(
        base_dir_.path(), base::MessageLoopProxy::current()));

    bool done = false;
    metadata_store_->Initialize(base::Bind(&DidInitialize, &done));
    message_loop_.RunUntilIdle();
    EXPECT_TRUE(done);
  }

  void SetUpDriveSyncService() {
    sync_service_ = DriveFileSyncService::CreateForTesting(
        sync_client_.Pass(), metadata_store_.Pass()).Pass();
    sync_service_->AddObserver(&mock_remote_observer_);
  }

  virtual void TearDown() OVERRIDE {
    EXPECT_CALL(*mock_drive_service(), CancelAll());

    if (sync_service_) {
      sync_service_.reset();
    }

    metadata_store_.reset();
    sync_client_.reset();
    mock_drive_service_ = NULL;

    EXPECT_TRUE(fileapi::RevokeSyncableFileSystem(
        DriveFileSyncService::kServiceName));
    message_loop_.RunUntilIdle();
  }

 protected:
  DriveFileSyncClient* sync_client() {
    if (sync_client_)
      return sync_client_.get();
    return sync_service_->sync_client_.get();
  }

  DriveMetadataStore* metadata_store() {
    if (metadata_store_)
      return metadata_store_.get();
    return sync_service_->metadata_store_.get();
  }

  StrictMock<google_apis::MockDriveService>* mock_drive_service() {
    return mock_drive_service_;
  }

  StrictMock<MockRemoteServiceObserver>* mock_remote_observer() {
    return &mock_remote_observer_;
  }

  MessageLoop* message_loop() { return &message_loop_; }
  DriveFileSyncService* sync_service() { return sync_service_.get(); }

  std::string FormatTitleQuery(const std::string& title) {
    return DriveFileSyncClient::FormatTitleQuery(title);
  }

  const DriveFileSyncService::PendingChangeQueue& pending_changes() const {
    return sync_service_->pending_changes_;
  }

 private:
  MessageLoop message_loop_;

  base::ScopedTempDir base_dir_;
  TestingProfile profile_;

  scoped_ptr<DriveFileSyncService> sync_service_;

  // Owned by |sync_client_|.
  StrictMock<google_apis::MockDriveService>* mock_drive_service_;
  StrictMock<MockRemoteServiceObserver> mock_remote_observer_;

  scoped_ptr<DriveFileSyncClient> sync_client_;
  scoped_ptr<DriveMetadataStore> metadata_store_;

  DISALLOW_COPY_AND_ASSIGN(DriveFileSyncServiceTest);
};

// Invokes |arg0| as a GetDataCallback.
ACTION_P2(InvokeGetDataCallback0, error, result) {
  scoped_ptr<base::Value> value(result.Pass());
  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE,
      base::Bind(arg0, error, base::Passed(&value)));
}

// Invokes |arg0| as a GetDataCallback.
ACTION_P2(InvokeGetDataCallback1, error, result) {
  scoped_ptr<base::Value> value(result.Pass());
  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE,
      base::Bind(arg1, error, base::Passed(&value)));
}

// Invokes |arg2| as a GetDataCallback.
ACTION_P2(InvokeGetDataCallback2, error, result) {
  scoped_ptr<base::Value> value(result.Pass());
  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE,
      base::Bind(arg2, error, base::Passed(&value)));
}

// Invokes |arg5| as a GetDataCallback.
ACTION_P2(InvokeGetDataCallback5, error, result) {
  scoped_ptr<base::Value> value(result.Pass());
  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE,
      base::Bind(arg5, error, base::Passed(&value)));
}

#if !defined(OS_ANDROID)

TEST_F(DriveFileSyncServiceTest, GetSyncRoot) {
  scoped_ptr<Value> sync_root_found(LoadJSONFile(
      "sync_file_system/sync_root_found.json"));
  std::string query = FormatTitleQuery(kSyncRootDirectoryName);
  EXPECT_CALL(*mock_drive_service(),
              GetDocuments(GURL(), 0, query, false, std::string(), _))
      .WillOnce(InvokeGetDataCallback5(
          google_apis::HTTP_SUCCESS,
          base::Passed(&sync_root_found)));

  EXPECT_CALL(*mock_remote_observer(),
              OnRemoteServiceStateUpdated(REMOTE_SERVICE_OK, _))
      .Times(1);
  EXPECT_CALL(*mock_remote_observer(), OnRemoteChangeAvailable(0))
      .Times(AnyNumber());

  SetUpDriveSyncService();
  message_loop()->RunUntilIdle();

  EXPECT_EQ("folder:sync_root_resource_id",
            metadata_store()->sync_root_directory());

  EXPECT_EQ(0u, metadata_store()->batch_sync_origins().size());
  EXPECT_EQ(0u, metadata_store()->incremental_sync_origins().size());
  EXPECT_EQ(0u, pending_changes().size());
}

TEST_F(DriveFileSyncServiceTest, BatchSyncOnInitialization) {
  const GURL kOrigin1("http://example.com");
  const GURL kOrigin2("http://hoge.example.com");
  const std::string kDirectoryResourceId1(
      "folder:origin_directory_resource_id");
  const std::string kDirectoryResourceId2(
      "folder:origin_directory_resource_id2");
  const std::string kSyncRootResourceId("folder:sync_root_resource_id");

  metadata_store()->SetSyncRootDirectory(kSyncRootResourceId);
  metadata_store()->AddBatchSyncOrigin(kOrigin1, kDirectoryResourceId1);
  metadata_store()->AddBatchSyncOrigin(kOrigin2, kDirectoryResourceId2);
  metadata_store()->MoveBatchSyncOriginToIncremental(kOrigin2);

  EXPECT_CALL(*mock_remote_observer(),
              OnRemoteChangeAvailable(4))
      .Times(AnyNumber());

  InSequence sequence;

  scoped_ptr<Value> account_metadata(LoadJSONFile(
      "gdata/account_metadata.json"));
  EXPECT_CALL(*mock_drive_service(),
              GetAccountMetadata(_))
      .WillOnce(InvokeGetDataCallback0(
          google_apis::HTTP_SUCCESS,
          base::Passed(&account_metadata)));

  scoped_ptr<Value> listing_files_in_directory(LoadJSONFile(
      "sync_file_system/listing_files_in_directory.json"));
  EXPECT_CALL(*mock_drive_service(),
              GetDocuments(GURL(), 0, std::string(), false,
                           kDirectoryResourceId1, _))
      .WillOnce(InvokeGetDataCallback5(
          google_apis::HTTP_SUCCESS,
          base::Passed(&listing_files_in_directory)));

  EXPECT_CALL(*mock_remote_observer(),
              OnRemoteServiceStateUpdated(REMOTE_SERVICE_OK, _))
      .Times(1);

  SetUpDriveSyncService();
  message_loop()->RunUntilIdle();

  // kOrigin1 should be a batch sync origin and kOrigin2 should be an
  // incremental sync origin.
  // 4 pending remote changes are from listing_files_in_directory as batch sync
  // changes.
  EXPECT_EQ(1u, metadata_store()->batch_sync_origins().size());
  EXPECT_EQ(1u, metadata_store()->incremental_sync_origins().size());
  EXPECT_EQ(4u, pending_changes().size());
}

TEST_F(DriveFileSyncServiceTest, RegisterNewOrigin) {
  const GURL kOrigin("http://example.com");
  const std::string kDirectoryResourceId("folder:origin_directory_resource_id");
  const std::string kSyncRootResourceId("folder:sync_root_resource_id");
  const GURL kSyncRootContentURL("https://sync_root_content_url/");

  metadata_store()->SetSyncRootDirectory(kSyncRootResourceId);

  EXPECT_CALL(*mock_remote_observer(),
              OnRemoteServiceStateUpdated(REMOTE_SERVICE_OK, _))
      .Times(AtLeast(1));
  EXPECT_CALL(*mock_remote_observer(), OnRemoteChangeAvailable(0))
      .Times(AnyNumber());

  InSequence sequence;

  scoped_ptr<Value> origin_directory_not_found(LoadJSONFile(
      "sync_file_system/origin_directory_not_found.json"));
  std::string query = FormatTitleQuery(kOrigin.spec());

  EXPECT_CALL(*mock_drive_service(),
              GetDocuments(GURL(), 0, query, false, kSyncRootResourceId, _))
      .WillOnce(InvokeGetDataCallback5(
          google_apis::HTTP_SUCCESS,
          base::Passed(&origin_directory_not_found)))
      .RetiresOnSaturation();

  // If the directory for the origin is missing, DriveFileSyncService should
  // attempt to create it. And as a preparation, it should fetch the content url
  // of the parent directory.
  //
  // |sync_root_entry| contains kSyncRootContentURL which is to be added as
  // a new origin directory under the root directory.
  scoped_ptr<Value> sync_root_entry(LoadJSONFile(
      "sync_file_system/sync_root_entry.json"));
  EXPECT_CALL(*mock_drive_service(),
              GetDocumentEntry(kSyncRootResourceId, _))
      .WillOnce(InvokeGetDataCallback1(
          google_apis::HTTP_SUCCESS,
          base::Passed(&sync_root_entry)));

  scoped_ptr<Value> origin_directory_created(LoadJSONFile(
      "sync_file_system/origin_directory_created.json"));
  FilePath::StringType dirname =
      FilePath().AppendASCII(kOrigin.spec()).value();
  EXPECT_CALL(*mock_drive_service(),
              AddNewDirectory(kSyncRootContentURL, dirname, _))
      .WillOnce(InvokeGetDataCallback2(
          google_apis::HTTP_SUCCESS,
          base::Passed(&origin_directory_created)));

  // Once the directory is created GetAccountMetadata should be called to get
  // the largest changestamp for the origin as a prepariation of the batch sync.
  scoped_ptr<Value> account_metadata(LoadJSONFile(
      "gdata/account_metadata.json"));
  EXPECT_CALL(*mock_drive_service(), GetAccountMetadata(_))
      .WillOnce(InvokeGetDataCallback0(
          google_apis::HTTP_SUCCESS,
          base::Passed(&account_metadata)));

  scoped_ptr<Value> listing_files_in_empty_directory(LoadJSONFile(
      "sync_file_system/listing_files_in_empty_directory.json"));
  EXPECT_CALL(*mock_drive_service(),
              GetDocuments(GURL(), 0, std::string(), false,
                           kDirectoryResourceId, _))
      .WillOnce(InvokeGetDataCallback5(
          google_apis::HTTP_SUCCESS,
          base::Passed(&listing_files_in_empty_directory)));

  SetUpDriveSyncService();
  bool done = false;
  sync_service()->RegisterOriginForTrackingChanges(
      kOrigin, base::Bind(&ExpectEqStatus, &done, fileapi::SYNC_STATUS_OK));
  message_loop()->RunUntilIdle();
  EXPECT_TRUE(done);

  EXPECT_EQ(1u, metadata_store()->batch_sync_origins().size());
  EXPECT_TRUE(metadata_store()->incremental_sync_origins().empty());
  EXPECT_TRUE(pending_changes().empty());
}

TEST_F(DriveFileSyncServiceTest, RegisterExistingOrigin) {
  const GURL kOrigin("http://example.com");
  const std::string kDirectoryResourceId("folder:origin_directory_resource_id");
  const std::string kSyncRootResourceId("folder:sync_root_resource_id");

  metadata_store()->SetSyncRootDirectory(kSyncRootResourceId);

  EXPECT_CALL(*mock_remote_observer(),
              OnRemoteServiceStateUpdated(REMOTE_SERVICE_OK, _))
      .Times(AtLeast(1));
  EXPECT_CALL(*mock_remote_observer(), OnRemoteChangeAvailable(4))
      .Times(AnyNumber());

  InSequence sequence;

  scoped_ptr<Value> origin_directory_found(LoadJSONFile(
      "sync_file_system/origin_directory_found.json"));
  std::string query = FormatTitleQuery("http://example.com/");
  EXPECT_CALL(*mock_drive_service(),
              GetDocuments(GURL(), 0, query, false, kSyncRootResourceId, _))
      .WillOnce(InvokeGetDataCallback5(
          google_apis::HTTP_SUCCESS,
          base::Passed(&origin_directory_found)))
      .RetiresOnSaturation();

  scoped_ptr<Value> account_metadata(LoadJSONFile(
      "gdata/account_metadata.json"));
  EXPECT_CALL(*mock_drive_service(), GetAccountMetadata(_))
      .WillOnce(InvokeGetDataCallback0(
          google_apis::HTTP_SUCCESS,
          base::Passed(&account_metadata)));

  // DriveFileSyncService should fetch the list of the directory content
  // to start the batch sync.
  scoped_ptr<Value> listing_files_in_directory(LoadJSONFile(
      "sync_file_system/listing_files_in_directory.json"));
  EXPECT_CALL(*mock_drive_service(),
              GetDocuments(GURL(), 0, std::string(),
                           false, kDirectoryResourceId, _))
      .WillOnce(InvokeGetDataCallback5(
          google_apis::HTTP_SUCCESS,
          base::Passed(&listing_files_in_directory)));

  SetUpDriveSyncService();
  bool done = false;
  sync_service()->RegisterOriginForTrackingChanges(
      kOrigin, base::Bind(&ExpectEqStatus, &done, fileapi::SYNC_STATUS_OK));
  message_loop()->RunUntilIdle();
  EXPECT_TRUE(done);

  // The origin should be registered as a batch sync origin.
  EXPECT_EQ(1u, metadata_store()->batch_sync_origins().size());
  EXPECT_TRUE(metadata_store()->incremental_sync_origins().empty());

  // |listing_files_in_directory| contains 4 items to sync.
  EXPECT_EQ(4u, pending_changes().size());
}

TEST_F(DriveFileSyncServiceTest, UnregisterOrigin) {
  const GURL kOrigin1("chrome-extension://example1");
  const GURL kOrigin2("chrome-extension://example2");
  const std::string kDirectoryResourceId1(
      "folder:origin_directory_resource_id");
  const std::string kDirectoryResourceId2(
      "folder:origin_directory_resource_id2");
  const std::string kSyncRootResourceId("folder:sync_root_resource_id");

  metadata_store()->SetSyncRootDirectory(kSyncRootResourceId);
  metadata_store()->AddBatchSyncOrigin(kOrigin1, kDirectoryResourceId1);
  metadata_store()->AddBatchSyncOrigin(kOrigin2, kDirectoryResourceId2);
  metadata_store()->MoveBatchSyncOriginToIncremental(kOrigin2);

  EXPECT_CALL(*mock_remote_observer(),
              OnRemoteServiceStateUpdated(REMOTE_SERVICE_OK, _))
      .Times(AtLeast(1));
  EXPECT_CALL(*mock_remote_observer(), OnRemoteChangeAvailable(_))
      .Times(AnyNumber());

  InSequence sequence;

  scoped_ptr<Value> account_metadata(LoadJSONFile(
      "gdata/account_metadata.json"));
  EXPECT_CALL(*mock_drive_service(),
              GetAccountMetadata(_))
      .WillOnce(InvokeGetDataCallback0(
          google_apis::HTTP_SUCCESS,
          base::Passed(&account_metadata)));

  scoped_ptr<Value> listing_files_in_directory(LoadJSONFile(
      "sync_file_system/listing_files_in_directory.json"));
  EXPECT_CALL(*mock_drive_service(),
              GetDocuments(GURL(), 0, std::string(), false,
                           kDirectoryResourceId1, _))
      .WillOnce(InvokeGetDataCallback5(
          google_apis::HTTP_SUCCESS,
          base::Passed(&listing_files_in_directory)));

  SetUpDriveSyncService();
  message_loop()->RunUntilIdle();

  EXPECT_EQ(1u, metadata_store()->batch_sync_origins().size());
  EXPECT_EQ(1u, metadata_store()->incremental_sync_origins().size());
  EXPECT_EQ(4u, pending_changes().size());

  bool done = false;
  sync_service()->UnregisterOriginForTrackingChanges(
      kOrigin1, base::Bind(&ExpectEqStatus, &done, fileapi::SYNC_STATUS_OK));
  message_loop()->RunUntilIdle();
  EXPECT_TRUE(done);

  EXPECT_TRUE(metadata_store()->batch_sync_origins().empty());
  EXPECT_EQ(1u, metadata_store()->incremental_sync_origins().size());
  EXPECT_TRUE(pending_changes().empty());
}

#endif  // !defined(OS_ANDROID)

}  // namespace sync_file_system

redpajama_set_name: RedPajamaGithub


text:
@interface MSRequestResponse (Film)

+ (BOOL)isFilmExistInInfo:(NSDictionary *)info;
+ (NSString *)filmIdFromInfo:(NSDictionary *)info;
+ (NSString *)errorTextFromInfo:(NSDictionary *)info;

@end


text:
"""
Tests for the decorators module in Yellowbrick utils.
"""

##########################################################################
## Imports
##########################################################################

from yellowbrick.utils.decorators import *

##########################################################################
## Decorator Tests
##########################################################################

class TestDecorators(object):
    """
    Tests for the decorator utilities.
    """

    def test_memoization(self):
        """
        Test the memoized property decorator on a class.
        """

        class Visualizer(object):
            @memoized
            def foo(self):
                return "bar"

        viz = Visualizer()
        assert not hasattr(viz, "_foo")
        assert viz.foo == "bar"
        assert viz._foo == "bar"

    def test_docutil(self):
        """
        Test the docutil docstring copying methodology.
        """

        class Visualizer(object):
            def __init__(self):
                """
                This is the correct docstring.
                """
                pass

        def undecorated(*args, **kwargs):
            """
            This is an undecorated function string.
            """
            pass

        # Test the undecorated string to protect from magic
        assert undecorated.__doc__.strip() == "This is an undecorated function string."

        # Decorate manually and test the newly decorated return function.
        decorated = docutil(Visualizer.__init__)(undecorated)
        assert decorated.__doc__.strip() == "This is the correct docstring."

        # Assert that decoration modifies the original function.
        assert undecorated.__doc__.strip() == "This is the correct docstring."

        @docutil(Visualizer.__init__)
        def sugar(*args, **kwargs):
            pass

        # Assert that syntactic sugar works as expected.
        assert sugar.__doc__.strip() == "This is the correct docstring."


text:
#ifndef PANDACORE_TOOLS_DUPLICATEREMOVER
#define PANDACORE_TOOLS_DUPLICATEREMOVER

#include "TTree.h"
#include "TFile.h"
#include "TString.h"
#include "TH1F.h"
#include "TEntryList.h"
#include "TList.h"
#include "PandaCore/Tools/interface/Common.h"
#include <unordered_set>

/**
 * \brief Removes duplicate entries given two input trees
 */
class DuplicateRemover
{
public:
	DuplicateRemover() { }
	~DuplicateRemover() { }

	/*
	 * \brief Merges two input trees and puts them into a new file
	 *
	 * First checks all events in t1, removes them from t2, and
	 * merges the trees into a single tree in fOutPath. Note that
	 * both input trees are left alone.
	 */
	void Merge(TTree *t1, TTree *t2, TString fOutPath);

	/*
	 * \brief Merges two input trees given the files that contain them
	 */
	void Merge(TString f1Path, TString f2Path, TString fOutPath);

	bool verbose=false; /**< verbosity */
	TString runName = "runNumber"; /**< name of run branch */
	TString eventName = "eventNumber"; /**< name of event branch */
	TString lumiName = "lumiNumber"; /**< name of lumi branch */
	TString treeName = "events"; /**< name of input and output trees */
};
#endif


text:
package com.github.aureliano.evtbridge.core.helper;

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

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class TimeHelperTest {

	@Test
	public void testConvertToMilliseconds() {
		assertEquals(500, TimeHelper.convertToMilliseconds(TimeUnit.MILLISECONDS, 500));
		assertEquals(5000, TimeHelper.convertToMilliseconds(TimeUnit.SECONDS, 5));
		assertEquals(420000, TimeHelper.convertToMilliseconds(TimeUnit.MINUTES, 7));
		assertEquals(7200000, TimeHelper.convertToMilliseconds(TimeUnit.HOURS, 2));
		assertEquals(259200000, TimeHelper.convertToMilliseconds(TimeUnit.DAYS, 3));
	}

	@Test
	public void testConvertToMillisecondsUnsupportedTimeUnit() {
		try {
			TimeHelper.convertToMilliseconds(TimeUnit.MICROSECONDS, 500);
		} catch (IllegalArgumentException ex) {
			assertEquals("Unsupported time unit. The smallest time unit supported is " +
					TimeUnit.MILLISECONDS + " but got " + TimeUnit.MICROSECONDS, ex.getMessage());
		}

		try {
			TimeHelper.convertToMilliseconds(TimeUnit.NANOSECONDS, 500);
		} catch (IllegalArgumentException ex) {
			assertEquals("Unsupported time unit. The smallest time unit supported is " +
					TimeUnit.MILLISECONDS + " but got " + TimeUnit.NANOSECONDS, ex.getMessage());
		}
	}

	@Test
	public void testIsValidTimeUnit() {
		assertTrue(TimeHelper.isValidTimeUnit("MILLISECONDS"));
		assertTrue(TimeHelper.isValidTimeUnit("milliseconds"));
		assertTrue(TimeHelper.isValidTimeUnit("Seconds"));
		assertTrue(TimeHelper.isValidTimeUnit("MinuteS"));
		assertTrue(TimeHelper.isValidTimeUnit("hours"));
		assertTrue(TimeHelper.isValidTimeUnit("DAYS"));
		assertTrue(TimeHelper.isValidTimeUnit("MICROSECONDS"));
		assertTrue(TimeHelper.isValidTimeUnit("nanoseconds"));

		assertFalse(TimeHelper.isValidTimeUnit("months"));
		assertFalse(TimeHelper.isValidTimeUnit("weeks"));
		assertFalse(TimeHelper.isValidTimeUnit("years"));
	}

	@Test
	public void testParseToDateTime() {
		Date date = TimeHelper.parseToDateTime("2015-06-10 09:27:35");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);

		assertEquals(2015, calendar.get(Calendar.YEAR));
		assertEquals(Calendar.JUNE, calendar.get(Calendar.MONTH));
		assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
		assertEquals(9, calendar.get(Calendar.HOUR_OF_DAY));
		assertEquals(27, calendar.get(Calendar.MINUTE));
		assertEquals(35, calendar.get(Calendar.SECOND));
	}

	@Test
	public void testFormatDateTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, 2015);
		calendar.set(Calendar.MONTH, Calendar.JUNE);
		calendar.set(Calendar.DAY_OF_MONTH, 10);
		calendar.set(Calendar.HOUR_OF_DAY, 9);
		calendar.set(Calendar.MINUTE, 27);
		calendar.set(Calendar.SECOND, 35);

		String dateTime = TimeHelper.formatDateTime(calendar.getTime());
		assertEquals("2015-06-10 09:27:35", dateTime);
	}
}


text:
// Copyright (c) 2012-2014 Turbulenz Limited
// Allows the 'debugger' event to be fired when a property of an Object, function, or Array is read or/and written.
// Use DebuggingTools.dataBreakpoint(someObjectOrArray, "somePropertyOrIndex", breakOnRead, breakOnWrite);
// or DebuggingTools.dataBreakpoint(someObjectOrArray); // For all properties or all array elements.
// Use the same arguments to DebuggingTools.clearDataBreakpoint() to clear it or no arguments for all breakpoints.
// breakOnRead and breakOnWrite are optional. These can be toggle in the debugger too.
// The same pattern could be used to log access to an object, which combined with stacktrace,
// would be useful for time dependent async debugging.
// Issues
// * property delete does not tigger an event on watched object and will leak breakpoints
// * Array push/slice etc not trapped.
// * Does not work on typed arrays or directly on Numbers/Strings etc
// * Sealed objects
/* tslint:disable:no-debugger no-string-literal */
var DebuggingTools = {
    dataBreakpoints: [],
    log: function DebuggingToolsLogFn(a0, a1, a2, a3, a4, a5) {
        var console = window.console;
        if (console) {
            console.log.apply(console, arguments);
        }
    },
    dataBreakpoint: function debuggingToolsDataBreakpointFn(object, propertyName, breakOnRead, breakOnWrite) {
        if (propertyName) {
            DebuggingTools.log("dataBreakpoint Property:" + propertyName);
        }

        if (propertyName) {
            var descriptor = Object.getOwnPropertyDescriptor(object, propertyName);
            if (descriptor.get === undefined && descriptor.set === undefined) {
                var breakpoint = {
                    object: object,
                    propertyName: propertyName,
                    currentValue: object[propertyName],
                    breakOnRead: breakOnRead !== undefined ? breakOnRead : true,
                    breakOnWrite: breakOnWrite !== undefined ? breakOnWrite : true
                };

                DebuggingTools.dataBreakpoints.push(breakpoint);

                object['__defineSetter__'].call(object, propertyName, function (value) {
                    if (breakpoint.breakOnWrite) {
                        debugger;
                    }
                    breakpoint.currentValue = value;
                });

                object['__defineGetter__'].call(object, propertyName, function () {
                    if (breakpoint.breakOnRead) {
                        debugger;
                    }
                    return breakpoint.currentValue;
                });
            } else {
                DebuggingTools.log("Skipping getter/setter. Property:" + propertyName);
            }
        } else {
            if (Array.isArray(object)) {
                var index;
                for (index = 0; index < object.length; index += 1) {
                    DebuggingTools.dataBreakpoint(object, String(index), breakOnRead, breakOnWrite);
                }
                DebuggingTools.dataBreakpoint(object, "length", breakOnRead, breakOnWrite);
            } else if (typeof object === 'object' || typeof object === 'function') {
                if (object.constructor === ArrayBuffer || object.constructor === Int8Array || object.constructor === Uint8Array || object.constructor === Int16Array || object.constructor === Uint16Array || object.constructor === Int32Array || object.constructor === Uint32Array || object.constructor === Float32Array || object.constructor === Float64Array) {
                    DebuggingTools.log("Type: Typed Arrays are not supported. Property:" + propertyName);
                } else {
                    var name;
                    for (name in object) {
                        if (object.hasOwnProperty(name)) {
                            DebuggingTools.dataBreakpoint(object, name, breakOnRead, breakOnWrite);
                        }
                    }
                }
            } else {
                DebuggingTools.log("Type: " + typeof object + " not supported. Property:" + propertyName);
            }
        }
    },
    clearDataBreakpoint: function debuggingToolsClearDataBreakpointFn(object, propertyName) {
        var matched = false;
        var i = 0;
        while (i < DebuggingTools.dataBreakpoints.length) {
            var breakpoint = DebuggingTools.dataBreakpoints[i];
            if (object === undefined || (breakpoint.object === object && (propertyName === undefined || breakpoint.propertyName === propertyName))) {
                delete breakpoint.object[breakpoint.propertyName];
                breakpoint.object[breakpoint.propertyName] = breakpoint.currentValue;
                DebuggingTools.dataBreakpoints.splice(i, 1);
                matched = true;
            } else {
                i += 1;
            }
        }
        return matched;
    }
};