auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener) throws InvalidOperatingModeException, XBeeException { <START> if (!connectionInterface.isConnected()) <END> throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); switch (getOperatingMode()) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(); case API: case API_ESCAPE: if (packet instanceof XBeeAPIPacket) { if (((XBeeAPIPacket)packet).hasAPIFrameID()) { if (((XBeeAPIPacket)packet).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)packet).setFrameID(getNextFrameID()); if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener, ((XBeeAPIPacket)packet).getFrameID()); } else if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener); } try { writePacket(packet); } catch (IOException e) { throw new XBeeException(XBeeException.GENERIC, e.getMessage()); } break; } }</code><technical_language>connectionInterface null</technical_language>

Target:
public void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); switch (getOperatingMode()) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(); case API: case API_ESCAPE: if (packet instanceof XBeeAPIPacket) { if (((XBeeAPIPacket)packet).needsAPIFrameID()) { if (((XBeeAPIPacket)packet).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)packet).setFrameID(getNextFrameID()); if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener, ((XBeeAPIPacket)packet).getFrameID()); } else if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener); } try { writePacket(packet); } catch (IOException e) { throw new XBeeException(XBeeException.GENERIC, e.getMessage()); } break; } }
Source:
<code>public Result<Storage> setDefaultStorage(final String defaultStorageId) { final Result<Storage> storageResult = getStorage(defaultStorageId); if (storageResult.isSuccessful()) { try { curator.setData().forPath(ZK_TIMELINES_DEFAULT_STORAGE, defaultStorageId.getBytes(Charsets.UTF_8)); <START> } catch (Exception e) { <END> LOG.error(e.getMessage(), e); return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, "Zookeeper connection error")); } } return storageResult; }</code><technical_language>classic</technical_language>

Target:
public Result<Storage> setDefaultStorage(final String defaultStorageId) { final Result<Storage> storageResult = getStorage(defaultStorageId); if (storageResult.isSuccessful()) { try { curator.setData().forPath(ZK_TIMELINES_DEFAULT_STORAGE, defaultStorageId.getBytes(Charsets.UTF_8)); } catch (final Exception e) { LOG.error("Error while setting default storage in zk ", e.getMessage(), e); return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, "Error while setting default storage in zk")); } } return storageResult; }
Source:
<code>public void testFastqSerialize(final String basename) throws Exception { <START> final File tmpFile = File.createTempFile("test.", ".fastq"); <END> tmpFile.deleteOnExit(); int count=0; final FastqReader fastqReader = new FastqReader(new File(TEST_DATA_DIR,basename)); final ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream(tmpFile)); for(final FastqRecord rec: fastqReader) { objectOut.writeObject(rec); ++count; } objectOut.flush(); objectOut.close(); fastqReader.close(); final ObjectInputStream objectIn = new ObjectInputStream(new FileInputStream(tmpFile)); for(int i=0;i< count;++i) { final Object o = objectIn.readObject(); Assert.assertTrue(o instanceof FastqRecord,"instance of FastqRecord ?" +o.getClass()); } objectIn.close(); }</code><technical_language>a test method this. TestUtils.serializeAndDeserialize()</technical_language>

Target:
public void testFastqSerialize(final String basename) throws Exception { final ArrayList<FastqRecord> records = new ArrayList<>(); final FastqReader fastqReader = new FastqReader(new File(TEST_DATA_DIR,basename)); for(final FastqRecord rec: fastqReader) { records.add(rec); if(records.size()>100) break; } fastqReader.close(); Assert.assertEquals(TestUtil.serializeAndDeserialize(records),records); }
Source:
<code>public PermissionBlueprintDTO populate(ModelTranslator translator, PermissionBlueprintInfo source, PermissionBlueprintDTO dest) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (dest == null) { throw new IllegalArgumentException("dest is null"); } dest.setId(null); dest.setType(source.getTypeName()); dest.setAccess(source.getAccessLevel()); <START> if (translator != null) { if (source.getOwner() != null) { <END> OwnerDTO owner = translator.translate(source.getOwner(), OwnerDTO.class); NestedOwnerDTO ownerDTO = new NestedOwnerDTO() .displayName(owner.getDisplayName()) .href(owner.getHref()) .id(owner.getId()) .key(owner.getKey()); dest.setOwner(ownerDTO); } } else { dest.setOwner(null); } return dest; }</code><technical_language>If longer a translator translate owner, owner translation move of if(translator != null) block. other entities translated a translator, block removed completely</technical_language>

Target:
public PermissionBlueprintDTO populate(ModelTranslator translator, PermissionBlueprintInfo source, PermissionBlueprintDTO dest) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (dest == null) { throw new IllegalArgumentException("dest is null"); } dest.setId(null); dest.setType(source.getTypeName()); dest.setAccess(source.getAccessLevel()); if (source.getOwner() != null) { dest.setOwner(new NestedOwnerDTO().key(source.getOwner().getKey())); } else { dest.setOwner(null); } return dest; }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.create_key_email_fragment, container, false); mEmailEdit = (EmailEditText) view.findViewById(R.id.create_key_email); <START> View mBackButton = view.findViewById(R.id.create_key_back_button); <END> View mNextButton = view.findViewById(R.id.create_key_next_button); RecyclerView mEmailsRecyclerView = (RecyclerView) view.findViewById(R.id.create_key_emails); mEmailEdit.setText(mCreateKeyActivity.mEmail); if (mCreateKeyActivity.mEmail == null) { mEmailEdit.requestFocus(); } mBackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCreateKeyActivity.loadFragment(null, FragAction.TO_LEFT); } }); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nextClicked(); } }); mEmailsRecyclerView.setHasFixedSize(true); mEmailsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mEmailsRecyclerView.setItemAnimator(new DefaultItemAnimator()); if (mAdditionalEmailModels == null) { mAdditionalEmailModels = new ArrayList<>(); } if (mEmailAdapter == null) { mEmailAdapter = new EmailAdapter(mAdditionalEmailModels, new View.OnClickListener() { @Override public void onClick(View v) { addEmail(); } }); if (mCreateKeyActivity.mAdditionalEmails != null) { mEmailAdapter.addAll(mCreateKeyActivity.mAdditionalEmails); } } mEmailsRecyclerView.setAdapter(mEmailAdapter); return view; }</code><technical_language>if variables longer class variables, remove prefix m</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.create_key_email_fragment, container, false); mEmailEdit = (EmailEditText) view.findViewById(R.id.create_key_email); View backButton = view.findViewById(R.id.create_key_back_button); View nextButton = view.findViewById(R.id.create_key_next_button); RecyclerView emailsRecyclerView = (RecyclerView) view.findViewById(R.id.create_key_emails); mEmailEdit.setText(mCreateKeyActivity.mEmail); if (mCreateKeyActivity.mEmail == null) { mEmailEdit.requestFocus(); } backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCreateKeyActivity.loadFragment(null, FragAction.TO_LEFT); } }); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nextClicked(); } }); emailsRecyclerView.setHasFixedSize(true); emailsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); emailsRecyclerView.setItemAnimator(new DefaultItemAnimator()); if (mAdditionalEmailModels == null) { mAdditionalEmailModels = new ArrayList<>(); } if (mEmailAdapter == null) { mEmailAdapter = new EmailAdapter(mAdditionalEmailModels, new View.OnClickListener() { @Override public void onClick(View v) { addEmail(); } }); if (mCreateKeyActivity.mAdditionalEmails != null) { mEmailAdapter.addAll(mCreateKeyActivity.mAdditionalEmails); } } emailsRecyclerView.setAdapter(mEmailAdapter); return view; }
Source:
<code>public void then_flattened_nested_filterByPredicate() { SearchQuery<DocumentReference> query; <START> String normalField = indexMapping.identicalForFirstTwo.relativeFieldName; <END> String flattenedField = "flattened." + indexMapping.flattenedField.relativeFieldName; String nestedField = "nested." + indexMapping.flattenedField.relativeFieldName; query = indexManager.createScope().query() .predicate( b -> b.match().onField( normalField ).matching( "aaa" ) ) .sort( f -> f.byField( flattenedField ).asc().then().byField( normalField ).asc() ) .toQuery(); assertThat( query.fetch( 2 ) ).hasDocRefHitsExactOrder( INDEX_NAME, DOCUMENT_1, DOCUMENT_2 ); query = indexManager.createScope().query() .predicate( b -> b.match().onField( normalField ).matching( "aaa" ) ) .sort( f -> f.byField( nestedField ).asc().then().byField( flattenedField ).asc() ) .toQuery(); assertThat( query.fetch( 2 ) ).hasDocRefHitsExactOrder( INDEX_NAME, DOCUMENT_2, DOCUMENT_1 ); query = indexManager.createScope().query() .predicate( b -> b.match().onField( normalField ).matching( "aaa" ) ) .sort( f -> f.byField( normalField ).asc().then().byField( nestedField ).asc() ) .toQuery(); assertThat( query.fetch( 2 ) ).hasDocRefHitsExactOrder( INDEX_NAME, DOCUMENT_2, DOCUMENT_1 ); }</code><technical_language>this exhibit bug discussed. I change scenario a bit, I managed trigger bug. force-push update</technical_language>

Target:
public void then_flattened_nested_filterByPredicate() { SearchQuery<DocumentReference> query; String normalField = indexMapping.identicalForFirstTwo.relativeFieldName; String flattenedField = "flattened." + indexMapping.flattenedField.relativeFieldName; String nestedField = "nested." + indexMapping.flattenedField.relativeFieldName; query = indexManager.createScope().query() .predicate( b -> b.match().field( normalField ).matching( "aaa" ) ) .sort( f -> f.field( flattenedField ).asc().then().field( normalField ).asc() ) .toQuery(); assertThat( query.fetch( 2 ) ).hasDocRefHitsExactOrder( INDEX_NAME, DOCUMENT_1, DOCUMENT_2 ); query = indexManager.createScope().query() .predicate( b -> b.match().field( normalField ).matching( "aaa" ) ) .sort( f -> f.field( nestedField ).asc().then().field( flattenedField ).asc() ) .toQuery(); assertThat( query.fetch( 2 ) ).hasDocRefHitsExactOrder( INDEX_NAME, DOCUMENT_2, DOCUMENT_1 ); query = indexManager.createScope().query() .predicate( b -> b.match().field( normalField ).matching( "aaa" ) ) .sort( f -> f.field( normalField ).asc().then().field( nestedField ).asc() ) .toQuery(); assertThat( query.fetch( 2 ) ).hasDocRefHitsExactOrder( INDEX_NAME, DOCUMENT_2, DOCUMENT_1 ); }
Source:
<code>public void ensureInputsPresent(MerkleTree merkleTree, Map<Digest, Message> additionalInputs) throws IOException, InterruptedException { Iterable<Digest> allDigests = Iterables.concat(merkleTree.getAllDigests(), additionalInputs.keySet()); ImmutableSet<Digest> missingDigests = getFromFuture(cacheProtocol.findMissingDigests(allDigests)); List<ListenableFuture<Void>> uploadFutures = new ArrayList<>(); for (Digest missingDigest : missingDigests) { <START> if (!missingDigests.contains(missingDigest)) { <END> continue; } uploadFutures.add(uploadBlob(missingDigest, merkleTree, additionalInputs)); } waitForBulkTransfer(uploadFutures, false); }</code><technical_language>IIUC, missingDigest is element of missingDigests, this statement is false. guess is PRs share missingDigests actions remove this check for this PR I trigger internal checks prevent submitting</technical_language>

Target:
public void ensureInputsPresent(MerkleTree merkleTree, Map<Digest, Message> additionalInputs) throws IOException, InterruptedException { Iterable<Digest> allDigests = Iterables.concat(merkleTree.getAllDigests(), additionalInputs.keySet()); ImmutableSet<Digest> missingDigests = getFromFuture(cacheProtocol.findMissingDigests(allDigests)); List<ListenableFuture<Void>> uploadFutures = new ArrayList<>(); for (Digest missingDigest : missingDigests) { uploadFutures.add(uploadBlob(missingDigest, merkleTree, additionalInputs)); } waitForBulkTransfer(uploadFutures, false); }
Source:
<code>protected final Object handleMissingEntryOnRead(TopologyAffectedCommand command) { CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); int cmdTopology = command.getTopologyId(); if (cmdTopology < currentTopologyId) { <START> return (Object) UnsuccessfulResponse.INSTANCE; <END> } else { throw new OutdatedTopologyException(cmdTopology); } }</code><technical_language>unnecessary cast</technical_language>

Target:
protected final Object handleMissingEntryOnRead(TopologyAffectedCommand command) { CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); int cmdTopology = command.getTopologyId(); if (cmdTopology < currentTopologyId) { return UnsuccessfulResponse.INSTANCE; } else { throw new OutdatedTopologyException(cmdTopology); } }
Source:
<code>public List<FileDownloadInfo> getAllDownloadsFor(long batchId) { Cursor downloadsCursor = contentResolver.query( downloadsUriProvider.getAllDownloadsUri(), null, batchId == NO_BATCH_ID ? null : DownloadContract.Downloads.COLUMN_BATCH_ID + " = ?", batchId == NO_BATCH_ID ? null : new String[] { String.valueOf(batchId) }, DownloadContract.Batches._ID + " ASC" ); try { List<FileDownloadInfo> downloads = new ArrayList<>(); FileDownloadInfo.Reader reader = new FileDownloadInfo.Reader(contentResolver, downloadsCursor); while (downloadsCursor.moveToNext()) { downloads.add(downloadInfoCreator.create(reader)); } return downloads; } finally { <START> if (downloadsCursor != null) downloadsCursor.close(); <END> } }</code><technical_language>if this repo code style do liner if statements</technical_language>

Target:
public List<FileDownloadInfo> getAllDownloadsFor(long batchId) { Cursor downloadsCursor = contentResolver.query( downloadsUriProvider.getAllDownloadsUri(), null, batchId == NO_BATCH_ID ? null : DownloadContract.Downloads.COLUMN_BATCH_ID + " = ?", batchId == NO_BATCH_ID ? null : new String[] { String.valueOf(batchId) }, DownloadContract.Batches._ID + " ASC" ); try { List<FileDownloadInfo> downloads = new ArrayList<>(); FileDownloadInfo.Reader reader = new FileDownloadInfo.Reader(contentResolver, downloadsCursor); while (downloadsCursor.moveToNext()) { downloads.add(downloadInfoCreator.create(reader)); } return downloads; } finally { if (downloadsCursor != null) { downloadsCursor.close(); } } }
Source:
<code>public String toString() { <START> return "ClientCacheEntryExpiredEvent(" + "key=" + key + ")"; <END> }</code><technical_language>Wrong class name now</technical_language>

Target:
public String toString() { return "ExpiredEventImpl(" + "key=" + key + ")"; }
Source:
<code>private StringBuilder filterAnonVarsAndPrint(K result, Set<String> filterSet, CompiledDefinition compiledDef, KRunOptions options) { StringBuilder sb = new StringBuilder(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); <START> if (result instanceof KApply && ((KApply) result).klabel().toString().equals(KLabels.AND)) { <END> List<K> conjunctions = mutable(Assoc.flatten(KLabel(KLabels.AND), immutable(((KApply) result).items()), KLabel(KLabels.ML_TRUE))); conjunctions = conjunctions.stream().filter(x -> { if (x.getClass().toString().contains("BoolToken")) { return false; } if ((options.pattern != null) && x instanceof KApply && ((KApply) x).klabel().toString().equals(KLabels.EQUALS)) { K var = ((KApply) x).klist().items().get(0); if (var instanceof KVariable) { return filterSet.contains(((KVariable) var).name()); } } return true; }).collect(Collectors.toList()); conjunctions.sort(Comparator.comparing(K::toString)); if (conjunctions.size() > 1) { conjunctions.subList(0, conjunctions.size() - 1).forEach(x -> { prettyPrint(compiledDef, options.output, s -> bs.write(s, 0, s.length), x); sb.append(new String(bs.toByteArray())); sb.append(" " + KLabels.AND + " "); }); } if (!conjunctions.isEmpty()) { bs.reset(); prettyPrint(compiledDef, options.output, s -> bs.write(s, 0, s.length), conjunctions.get(conjunctions.size() - 1)); sb.append(new String(bs.toByteArray())); } return sb; } else { prettyPrint(compiledDef, options.output, s -> bs.write(s, 0, s.length), result); sb.append(new String(bs.toByteArray())); return sb; } }</code><technical_language>do check string-based equality</technical_language>

Target:
private StringBuilder filterAnonVarsAndPrint(K result, Set<String> filterSet, CompiledDefinition compiledDef, KRunOptions options) { StringBuilder sb = new StringBuilder(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); if (result instanceof KApply && ((KApply) result).klabel().toString().equals(KLabels.ML_AND)) { List<K> conjunctions = mutable(Assoc.flatten(KLabel(KLabels.ML_AND), immutable(((KApply) result).items()), KLabel(KLabels.ML_TRUE))); conjunctions = conjunctions.stream().filter(x -> { if ((options.pattern != null) && x instanceof KApply && ((KApply) x).klabel().name().equals(KLabels.EQUALS)) { K var = ((KApply) x).klist().items().get(0); if (var instanceof KVariable) { return filterSet.contains(((KVariable) var).name()); } } return true; }).collect(Collectors.toList()); conjunctions.sort(Comparator.comparing(K::toString)); if (conjunctions.size() > 1) { conjunctions.subList(0, conjunctions.size() - 1).forEach(x -> { prettyPrint(compiledDef, options.output, s -> bs.write(s, 0, s.length), x); sb.append(new String(bs.toByteArray())); sb.append(" " + KLabels.ML_AND + " "); }); } if (!conjunctions.isEmpty()) { bs.reset(); prettyPrint(compiledDef, options.output, s -> bs.write(s, 0, s.length), conjunctions.get(conjunctions.size() - 1)); sb.append(new String(bs.toByteArray())); } return sb; } else { prettyPrint(compiledDef, options.output, s -> bs.write(s, 0, s.length), result); sb.append(new String(bs.toByteArray())); return sb; } }
Source:
<code>public synchronized ZoneId deserialize(JsonElement element, Type type, JsonDeserializationContext context) { try { return ZoneId.of(element.getAsString()); <START> } catch (DateTimeParseException e) { <END> throw new JsonSyntaxException(element.getAsString(), e); } }</code><technical_language>I forgot update this DateTimeException</technical_language>

Target:
public synchronized ZoneId deserialize(JsonElement element, Type type, JsonDeserializationContext context) { try { return ZoneId.of(element.getAsString()); } catch (DateTimeException e) { throw new JsonSyntaxException(element.getAsString(), e); } }
Source:
<code>public Object getTransactionId() { <START> return tx != null ? tx.getId() : null; <END> }</code><technical_language>Transaction is mandatory. kind of error show in case a transaction is present? If clear enough improve it. Anyway, this a separate issue</technical_language>

Target:
public Object getTransactionId() { return tx.getId(); }
Source:
<code>public void getSourceFile(OutputStream output, OrcsApi orcsApi, String urlToSource, boolean offline) throws IOException { ResourceToken pageToken = offline ? AtsRestTemplateTokens.OfflineSourceFileTemplateHtml : AtsRestTemplateTokens.SourceFileTemplateHtml; Writer writer = new OutputStreamWriter(output); Client client = Client.create(); URI.create(urlToSource); WebResource service = client.resource(urlToSource); PageCreator page = new PageCreator(orcsApi.getResourceRegistry()); page.addKeyValuePair("fileContents", service.get(String.class)); page.realizePage(pageToken, writer); <START> writer.close(); <END> }</code><technical_language>this in a finally clause in case of exception</technical_language>

Target:
public void getSourceFile(OutputStream output, OrcsApi orcsApi, String urlToSource, boolean offline) { ResourceToken pageToken = offline ? AtsRestTemplateTokens.OfflineSourceFileTemplateHtml : AtsRestTemplateTokens.SourceFileTemplateHtml; Writer writer = null; try { writer = new OutputStreamWriter(output); Client client = Client.create(); URI.create(urlToSource); WebResource service = client.resource(urlToSource); PageCreator page = new PageCreator(orcsApi.getResourceRegistry()); page.addKeyValuePair("fileContents", service.get(String.class)); page.realizePage(pageToken, writer); } finally { Lib.close(writer); } }
Source:
<code><START> void writeData(Http2Stream stream, ByteBuf chunk, boolean end, Handler<AsyncResult<Void>> handler) { <END> EventExecutor executor = chctx.executor(); ChannelPromise promise = chctx.newPromise(); promise.addListener((future -> { if(future.isSuccess()) { handler.handle(Future.succeededFuture()); } else { handler.handle(Future.failedFuture(future.cause())); } })); if (executor.inEventLoop()) { _writeData(stream, chunk, end, promise); } else { executor.execute(() -> { _writeData(stream, chunk, end, promise); }); } }</code><technical_language>a single writeData method add handler listener of promise null remove void writeData(Http2Stream stream, ByteBuf chunk, boolean end)</technical_language>

Target:
void writeData(Http2Stream stream, ByteBuf chunk, boolean end, Handler<AsyncResult<Void>> handler) { EventExecutor executor = chctx.executor(); ChannelPromise promise = chctx.newPromise(); if (handler != null) { promise.addListener((future) -> { if(future.isSuccess()) { handler.handle(Future.succeededFuture()); } else { handler.handle(Future.failedFuture(future.cause())); } }); } if (executor.inEventLoop()) { _writeData(stream, chunk, end, promise); } else { executor.execute(() -> { _writeData(stream, chunk, end, promise); }); } }
Source:
<code><START> public void get( String key, AsyncCallback<Object> callback ) <END> { get( key, callback ); }</code><technical_language>return void</technical_language>

Target:
public void get( String key, AsyncCallback<Object> callback ) { get( key, Object.class, callback ); }
Source:
<code>private static Storage getService(String credentialsPath) throws Exception { <START> if (null == mStorageService) { <END> HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential; try { credential = GoogleCredential.fromStream(new FileInputStream(credentialsPath), httpTransport, JSON_FACTORY) .createScoped(Collections.singleton(StorageScopes.CLOUD_PLATFORM)); } catch (IOException e) { throw new RuntimeException("Failed to load Google credentials : " + credentialsPath, e); } mStorageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName("com.pinterest.secor") .build(); } return mStorageService; }</code><technical_language>if (mStorageService == null)</technical_language>

Target:
private static Storage getService(String credentialsPath) throws Exception { if (mStorageService == null) { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential; try { if (credentialsPath != null) { credential = GoogleCredential.fromStream(new FileInputStream(credentialsPath), httpTransport, JSON_FACTORY) .createScoped(Collections.singleton(StorageScopes.CLOUD_PLATFORM)); } else { credential = GoogleCredential.getApplicationDefault(httpTransport, JSON_FACTORY); } } catch (IOException e) { throw new RuntimeException("Failed to load Google credentials : " + credentialsPath, e); } mStorageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName("com.pinterest.secor") .build(); } return mStorageService; }
Source:
<code>public void testUsesInitialDelegateAndUpdatesDelegatesWhenRefreshableChanges() throws Exception { Object object1 = new Object(); Object object2 = new Object(); when(supplier.apply(object1)).thenReturn(delegate1); Refreshable<Object> refreshable = Refreshable.of(object1); RefreshableProxyInvocationHandler<Object, Callable> handler = RefreshableProxyInvocationHandler.create(refreshable, supplier); verify(supplier).apply(object1); Mockito.reset(supplier); Callable proxy = Reflection.newProxy(Callable.class, handler); proxy.call(); verify(delegate1).call(); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); <START> Mockito.reset(delegate1, delegate2, supplier); <END> proxy.call(); verify(delegate1).call(); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); Mockito.reset(delegate1, delegate2, supplier); refreshable.set(object2); when(supplier.apply(object2)).thenReturn(delegate2); proxy.call(); verify(delegate2).call(); verify(supplier).apply(object2); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); Mockito.reset(delegate1, delegate2, supplier); proxy.call(); verify(delegate2).call(); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); Mockito.reset(delegate1, delegate2, supplier); }</code><technical_language>hmm reset generally means split out a test multiple tests.</technical_language>

Target:
public void testUsesInitialDelegateAndUpdatesDelegatesWhenRefreshableChanges() throws Exception { Object object1 = new Object(); Object object2 = new Object(); when(supplier.apply(object1)).thenReturn(delegate1); Refreshable<Object> refreshable = Refreshable.of(object1); RefreshableProxyInvocationHandler<Object, Callable> handler = RefreshableProxyInvocationHandler.create(refreshable, supplier); verify(supplier).apply(object1); Callable proxy = Reflection.newProxy(Callable.class, handler); proxy.call(); verify(delegate1).call(); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); proxy.call(); verify(delegate1, times(2)).call(); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); refreshable.set(object2); when(supplier.apply(object2)).thenReturn(delegate2); proxy.call(); verify(delegate2).call(); verify(supplier).apply(object2); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); proxy.call(); verify(delegate2, times(2)).call(); Mockito.verifyNoMoreInteractions(delegate1, delegate2, supplier); }
Source:
<code>protected void defaultButtonInitialization(){ saveButton = new TextButton("Save"); saveButton.setPixelSize(60, 22); saveButton.getElement().setMargins(new Margins(0, 0, 0, 0)); <START> <END> cancelButton = new TextButton("Cancel"); cancelButton.setPixelSize(60, 22); cancelButton.getElement().setMargins(new Margins(0, 0, 0, PIXELS_BETWEEN_BUTTONS)); }</code><technical_language>want this ? saveButton.addClickHandler (new ClickHandler() { @onClick(...) { onSave(); } }); i this</technical_language>

Target:
protected void defaultButtonInitialization(){ saveButton = new TextButton("Save"); saveButton.setPixelSize(60, 22); saveButton.getElement().setMargins(new Margins(0, 0, 0, 0)); saveButton.addSelectHandler(new SelectEvent.SelectHandler() { @Override public void onSelect(SelectEvent selectEvent) { onSaveButtonClick(); } }); cancelButton = new TextButton("Cancel"); cancelButton.setPixelSize(60, 22); cancelButton.getElement().setMargins(new Margins(0, 0, 0, PIXELS_BETWEEN_BUTTONS)); cancelButton.addSelectHandler(new SelectEvent.SelectHandler() { @Override public void onSelect(SelectEvent selectEvent) { onCancelButtonClick(); } }); }
Source:
<code><START> public BatchSource<JetInputOutputFormat<KeyIn, ValueIn>> createDataSource(DataStore<KeyIn, ValueIn> dataOutStore, <END> Query<KeyIn, ValueIn> query) { JetEngine.dataInStore = dataOutStore; JetEngine.query = query; BatchSource<JetInputOutputFormat<KeyIn, ValueIn>> source = Sources.batchFromProcessor("gora-jet-source", new JetSource<KeyIn, ValueIn>()); return source; }</code><technical_language>This method package private</technical_language>

Target:
public BatchSource<JetInputOutputFormat<KeyIn, ValueIn>> createDataSource(DataStore<KeyIn, ValueIn> dataOutStore, Query<KeyIn, ValueIn> query) { JetEngine.dataInStore = dataOutStore; JetEngine.query = query; return Sources.batchFromProcessor("gora-jet-source", new JetSource<KeyIn, ValueIn>()); }
Source:
<code>private RestModel replace(ItemRest item, Operation operation) throws PatchBadRequestException, UnprocessableEntityException { checkOperationValue((String) operation.getValue()); <START> Boolean withdraw = BooleanUtils.toBooleanObject((String) operation.getValue()); <END> if (withdraw == null) { throw new PatchBadRequestException( "Boolean value not provided for withdrawn operation.."); } if (withdraw) { if (!item.getWithdrawn() && !item.getInArchive()) { throw new UnprocessableEntityException("Cannot withdraw item when it is not in archive."); } if (item.getWithdrawn()) { return item; } item.setWithdrawn(true); return item; } else { if (!item.getWithdrawn()) { return item; } item.setWithdrawn(false); return item; } }</code><technical_language>accept boolean</technical_language>

Target:
public ItemRest replace(ItemRest item, Operation operation) { Boolean withdraw = getBooleanOperationValue(operation.getValue()); if (withdraw) { if (!item.getWithdrawn() && !item.getInArchive()) { throw new UnprocessableEntityException("Cannot withdraw item when it is not in archive."); } if (item.getWithdrawn()) { return item; } item.setWithdrawn(true); return item; } else { if (!item.getWithdrawn()) { return item; } item.setWithdrawn(false); return item; } }
Source:
<code>public void updatesRequired_shouldAlwaysHaveAValidUpdateToLatestFile() throws Exception { try { DatabaseUpdater.updatesRequired(); } catch (RuntimeException | IOException rex) { <START> log.error("Runtime Exception in test for Validation Errors"); <END> } }</code><technical_language>Is a Runtime exception only</technical_language>

Target:
public void updatesRequired_shouldAlwaysHaveAValidUpdateToLatestFile() throws Exception { try { DatabaseUpdater.updatesRequired(); } catch (Exception ex) { log.error("Exception in test for Validation Errors"); } }
Source:
<code>public ValueMatcher makeMatcher( BitmapIndexSelector selector, ColumnSelectorFactory columnSelectorFactory, RowOffsetMatcherFactory rowOffsetMatcherFactory ) { final List<ValueMatcher> matchers = new ArrayList<>(); final List<ImmutableBitmap> bitmaps = new ArrayList<>(); for (Filter filter : filters) { if (filter.supportsBitmapIndex(selector)) { bitmaps.add(filter.getBitmapIndex(selector)); } else { ValueMatcher matcher = filter.makeMatcher(columnSelectorFactory); matchers.add(matcher); } } if (bitmaps.size() > 0) { ImmutableBitmap combinedBitmap = selector.getBitmapFactory().intersection(bitmaps); ValueMatcher offsetMatcher = rowOffsetMatcherFactory.makeRowOffsetMatcher(combinedBitmap); matchers.add(0, offsetMatcher); } <START> return makeMatcher(matchers.toArray(new ValueMatcher[0])); <END> }</code><technical_language>new ValueMatcher[0] a static constant</technical_language>

Target:
public ValueMatcher makeMatcher( BitmapIndexSelector selector, ColumnSelectorFactory columnSelectorFactory, RowOffsetMatcherFactory rowOffsetMatcherFactory ) { final List<ValueMatcher> matchers = new ArrayList<>(); final List<ImmutableBitmap> bitmaps = new ArrayList<>(); for (Filter filter : filters) { if (filter.supportsBitmapIndex(selector)) { bitmaps.add(filter.getBitmapIndex(selector)); } else { ValueMatcher matcher = filter.makeMatcher(columnSelectorFactory); matchers.add(matcher); } } if (bitmaps.size() > 0) { ImmutableBitmap combinedBitmap = selector.getBitmapFactory().intersection(bitmaps); ValueMatcher offsetMatcher = rowOffsetMatcherFactory.makeRowOffsetMatcher(combinedBitmap); matchers.add(0, offsetMatcher); } return makeMatcher(matchers.toArray(EMPTY_VALUE_MATCHER_ARRAY)); }
Source:
<code>public AnnotatedTypeMirror visitVariable(VariableTree node, AnnotatedTypeFactory f) { AnnotatedTypeMirror result = TypeFromTree.fromTypeTree(f, node.getType()); List<? extends AnnotationTree> annoTrees = node.getModifiers().getAnnotations(); if (annoTrees != null && !annoTrees.isEmpty()) { List<AnnotationMirror> annos = TreeUtils.annotationsFromTypeAnnotationTrees(annoTrees); AnnotatedTypeMirror innerType = AnnotatedTypes.innerMostType(result); for (AnnotationMirror anno : annos) { <START> if (AnnotationUtils.isDeclarationAnnotation(anno)) { <END> result.addAnnotation(anno); } else { innerType.addAnnotation(anno); } } } Element elt = TreeUtils.elementFromDeclaration(node); AnnotatedTypeMirror lambdaParamType = inferLambdaParamAnnotations(f, result, elt); if (lambdaParamType != null) { return lambdaParamType; } return result; }</code><technical_language>Note logic in addAnnotationsFromElement is different: checks annotation is part of org.checkerframework package, is a declaration annotation. logic same</technical_language>

Target:
public AnnotatedTypeMirror visitVariable(VariableTree node, AnnotatedTypeFactory f) { AnnotatedTypeMirror result = TypeFromTree.fromTypeTree(f, node.getType()); List<? extends AnnotationTree> annoTrees = node.getModifiers().getAnnotations(); if (annoTrees != null && !annoTrees.isEmpty()) { List<AnnotationMirror> annos = TreeUtils.annotationsFromTypeAnnotationTrees(annoTrees); AnnotatedTypeMirror innerType = AnnotatedTypes.innerMostType(result); for (AnnotationMirror anno : annos) { if (AnnotationUtils.isDeclarationAnnotation(anno) && !AnnotationUtils.annotationName(anno) .startsWith("org.checkerframework")) { result.addAnnotation(anno); } else { innerType.addAnnotation(anno); } } } Element elt = TreeUtils.elementFromDeclaration(node); AnnotatedTypeMirror lambdaParamType = inferLambdaParamAnnotations(f, result, elt); if (lambdaParamType != null) { return lambdaParamType; } return result; }
Source:
<code>public void testAlterStreamAddDropColumn() throws Exception { Client client = getClient(m_cluster); for (int i = 0; i < 100; i++) { Object[] data = new Object[3]; <START> data[0] = 1; <END> data[1] = i; data[2] = 1; m_verifier.addRow(client, "t", i, data); client.callProcedure("@AdHoc", "insert into t values(" + i + ", 1)"); } ClientResponse response = client.callProcedure("@AdHoc", "ALTER STREAM t ADD COLUMN new_column int BEFORE b"); assertEquals(ClientResponse.SUCCESS, response.getStatus()); for (int i = 100; i < 200; i++) { Object[] data = new Object[4]; data[0] = 1; data[1] = i; data[2] = i; data[3] = 1; m_verifier.addRow(client, "t", i, data); client.callProcedure("@AdHoc", "insert into t values(" + i + "," + i + ",1)"); } response = client.callProcedure("@AdHoc", "ALTER STREAM t DROP COLUMN new_column"); assertEquals(ClientResponse.SUCCESS, response.getStatus()); for (int i = 200; i < 300; i++) { Object[] data = new Object[3]; data[0] = 1; data[1] = i; data[2] = 1; m_verifier.addRow(client, "t", i, data); client.callProcedure("@AdHoc", "insert into t values(" + i + ", 1)"); } client.drain(); TestExportBaseSocketExport.waitForStreamedTargetAllocatedMemoryZero(client); m_verifier.verifyRows(); }</code><technical_language>Arrays.fill(data, i) for other places do thing</technical_language>

Target:
public void testAlterStreamAddDropColumn() throws Exception { Client client = getClient(m_cluster); Object[] data = new Object[3]; Arrays.fill(data, 1); insertToStream(0, 100, client, data); ClientResponse response = client.callProcedure("@AdHoc", "ALTER STREAM t ADD COLUMN new_column int BEFORE b"); assertEquals(ClientResponse.SUCCESS, response.getStatus()); Object[] data2 = new Object[4]; Arrays.fill(data2, 1); insertToStreamWithNewColumn(100, 100, client, data2); response = client.callProcedure("@AdHoc", "ALTER STREAM t DROP COLUMN new_column"); assertEquals(ClientResponse.SUCCESS, response.getStatus()); insertToStream(200, 100, client, data); client.drain(); TestExportBaseSocketExport.waitForStreamedTargetAllocatedMemoryZero(client); m_verifier.verifyRows(); }
Source:
<code><START> public static <M extends MessageEnvelope> WindowFunction<M, Void, WindowKey<Void>, Collection<M>, WindowOutput<WindowKey<Void>, Collection<M>>> globalWindow() { <END> BiFunction<M, Collection<M>, Collection<M>> aggregator = (m, c) -> { c.add(m); return c; }; return globalWindow(aggregator); }</code><technical_language>question here: start end, means continuous, pane</technical_language>

Target:
public static <M extends MessageEnvelope> Window<M, Void, Collection<M>, WindowPane<Void, Collection<M>>> globalWindow() { BiFunction<M, Collection<M>, Collection<M>> aggregator = (m, c) -> { c.add(m); return c; }; return globalWindow(aggregator); }
Source:
<code>static Result search(final Index index, final Parameter parameter, final String queryParameter, final String formatParameter, final int from, final int size) { List<Document> docs = new ArrayList<>(); final String field = formatParameter.contains(".") ? formatParameter.split("\\.")[1] : ""; final String format = formatParameter.contains(".") ? "full" : formatParameter; <START> try { <END> docs = Search.documents(queryParameter, index, parameter, from, size, field); } catch (IllegalArgumentException e) { Logger.error(e.getMessage(), e); return badRequest(e.getMessage()); } final ImmutableMap<ResultFormat, Result> results = results(parameter, queryParameter, docs, index, field); try { return results.get(ResultFormat.valueOf(format.toUpperCase())); } catch (IllegalArgumentException e) { Logger.error(e.getMessage(), e); return badRequest("Invalid 'format' parameter, use one of: " + Joiner.on(", ").join(results.keySet()).toLowerCase()); } }</code><technical_language>is, <LINK_0> result in format short. In fact, in parameter "format" a dot '.' result in format short . if this is a problem, though</technical_language>

Target:
static Result search(final Index index, final Parameter parameter, final String queryParameter, final String formatParameter, final int from, final int size) { List<Document> docs = new ArrayList<>(); Pair<String, String> fieldAndFormat; try { fieldAndFormat = getFieldAndFormat(formatParameter); docs = Search.documents(queryParameter, index, parameter, from, size, fieldAndFormat.getLeft()); } catch (IllegalArgumentException e) { Logger.error(e.getMessage(), e); return badRequest(e.getMessage()); } final ImmutableMap<ResultFormat, Result> results = results(parameter, queryParameter, docs, index, fieldAndFormat.getLeft()); try { return results.get(ResultFormat.valueOf(fieldAndFormat.getRight() .toUpperCase())); } catch (IllegalArgumentException e) { Logger.error(e.getMessage(), e); return badRequest("Invalid 'format' parameter, use one of: " + Joiner.on(", ").join(results.keySet()).toLowerCase()); } }
Source:
<code>private Optional<Encryption> toEncryption(DwrfProto.Encryption encryption) { <START> if (encryption.getEncryptionGroupsCount() == 0) { <END> return Optional.empty(); } KeyProvider keyProvider = toKeyProvider(encryption.getKeyProvider()); List<EncryptionGroup> encryptionGroups = toEncryptionGroups(encryption.getEncryptionGroupsList()); return Optional.of(new Encryption(keyProvider, encryptionGroups)); }</code><technical_language>contract is proto.encryption is optional. If exists, encryption group</technical_language>

Target:
private static DwrfEncryption toEncryption(DwrfProto.Encryption encryption) { KeyProvider keyProvider = toKeyProvider(encryption.getKeyProvider()); List<EncryptionGroup> encryptionGroups = toEncryptionGroups(encryption.getEncryptionGroupsList()); return new DwrfEncryption(keyProvider, encryptionGroups); }
Source:
<code>private String messageFormatter(String msg, String vmid) { ObjectNode vmDetailNode = new ObjectMapper().createObjectNode(); vmDetailNode.put("status", msg); vmDetailNode.put("hash", Integer.toString(vmid.hashCode())); ObjectNode paramsNode = new ObjectMapper().createObjectNode(); paramsNode.put(vmid.toString(), vmDetailNode); paramsNode.put("notify_time", <START> System.currentTimeMillis()); <END> ObjectNode node = new ObjectMapper().createObjectNode(); node.put("params", paramsNode); node.put("jsonrpc","2.0"); node.put("method", "|virt|VM_status|" + vmid); return node.toString(); }</code><technical_language>AFAIR, Piotr suggested nano time, double check it</technical_language>

Target:
private String messageFormatter(String msg, String vmid) { ObjectNode vmDetailNode = new ObjectMapper().createObjectNode(); vmDetailNode.put("status", msg); vmDetailNode.put("hash", Integer.toString(vmid.hashCode())); ObjectNode paramsNode = new ObjectMapper().createObjectNode(); paramsNode.put(vmid.toString(), vmDetailNode); paramsNode.put("notify_time", System.nanoTime()); ObjectNode node = new ObjectMapper().createObjectNode(); node.put("params", paramsNode); node.put("jsonrpc","2.0"); node.put("method", "|virt|VM_status|" + vmid); return node.toString(); }
Source:
<code>private void setupExpectedGlusterServersInfo() { expectedServers = new ArrayList<GlusterServerInfo>(); GlusterServerInfo server = new GlusterServerInfo(); <START> server = new GlusterServerInfo(); <END> server.setUuid(server_id3); server.setHostnameOrIp(TEST_SERVER3); server.setStatus(PeerStatus.CONNECTED); expectedServers.add(server); }</code><technical_language>a reason reduce expected server list 1</technical_language>

Target:
private void setupExpectedGlusterServersInfo() { expectedServers = new ArrayList<GlusterServerInfo>(); GlusterServerInfo server = new GlusterServerInfo(); server.setUuid(server_id3); server.setHostnameOrIp(TEST_SERVER3); server.setStatus(PeerStatus.CONNECTED); expectedServers.add(server); }
Source:
<code>public String getAllExtractedLines() throws NuxeoException { if (extractedAllAsString == null) { PDDocument pdfDoc = null; <START> try { <END> pdfDoc = PDFUtils.load(pdfBlob, password); PDFTextStripper stripper = new PDFTextStripper(); extractedAllAsString = stripper.getText(pdfDoc); } catch (IOException e) { throw new NuxeoException("Failed to handle the pdf", e); } finally { PDFUtils.closeSilently(pdfDoc); } } return extractedAllAsString; }</code><technical_language>try resource</technical_language>

Target:
public String getAllExtractedLines() throws NuxeoException { if (extractedAllAsString == null) { try (PDDocument pdfDoc = PDFUtils.load(pdfBlob, password)) { PDFTextStripper stripper = new PDFTextStripper(); extractedAllAsString = stripper.getText(pdfDoc); } catch (IOException e) { throw new NuxeoException("Failed to handle the pdf", e); } } return extractedAllAsString; }
Source:
<code>public void testCancelConsumerBeforeConsumeOk() throws Exception { ConnectionFactory mockCF = mock(ConnectionFactory.class); Connection connection = mock(Connection.class); Channel channel = mock(Channel.class); given(connection.isOpen()).willReturn(true); given(mockCF.createConnection()).willReturn(connection); given(connection.createChannel(false)).willReturn(channel); given(channel.isOpen()).willReturn(true); final CountDownLatch latch1 = new CountDownLatch(1); ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class); final String tag = "tag"; willAnswer(i -> { latch1.countDown(); return tag; }).given(channel).basicConsume(eq("foo"), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), consumerCaptor.capture()); DirectMessageListenerContainer container = new DirectMessageListenerContainer(mockCF); container.setQueueNames("foo"); container.setBeanName("backOff"); container.setConsumerTagStrategy(q -> "tag"); container.afterPropertiesSet(); container.start(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); Consumer consumer = consumerCaptor.getValue(); <START> Executors.newSingleThreadExecutor().execute(() -> container.stop()); <END> verify(channel).basicCancel(tag); consumer.handleCancelOk(tag); }</code><technical_language>Method reference :smile: Executors.newSingleThreadExecutor().execute(container::stop);</technical_language>

Target:
public void testCancelConsumerBeforeConsumeOk() throws Exception { ConnectionFactory mockCF = mock(ConnectionFactory.class); Connection connection = mock(Connection.class); Channel channel = mock(Channel.class); given(connection.isOpen()).willReturn(true); given(mockCF.createConnection()).willReturn(connection); given(connection.createChannel(false)).willReturn(channel); given(channel.isOpen()).willReturn(true); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class); final String tag = "tag"; willAnswer(i -> { latch1.countDown(); return tag; }).given(channel).basicConsume(eq("foo"), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), consumerCaptor.capture()); DirectMessageListenerContainer container = new DirectMessageListenerContainer(mockCF); container.setQueueNames("foo"); container.setBeanName("backOff"); container.setConsumerTagStrategy(q -> "tag"); container.setShutdownTimeout(1); container.afterPropertiesSet(); container.start(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); Consumer consumer = consumerCaptor.getValue(); Executors.newSingleThreadExecutor().execute(() -> { container.stop(); latch2.countDown(); }); assertTrue(latch2.await(10, TimeUnit.SECONDS)); verify(channel).basicCancel(tag); consumer.handleCancelOk(tag); }
Source:
<code>public boolean matches(Object item) { if(item instanceof Shell){ if(new WindowMatcher(org.eclipse.jface.dialogs.TitleAreaDialog.class).matches(item)){ DefaultShell shell = new DefaultShell((Shell)item); <START> TitleAreaDialog ta = new TitleAreaDialog(shell); <END> return matcher.matches(ta.getTitle()); } } return false; }</code><technical_language>if wrong SWT widget, e.g. disposed? fails exception - is this desired</technical_language>

Target:
public boolean matches(Object item) { if(item instanceof Shell){ try{ if(new WindowMatcher(org.eclipse.jface.dialogs.TitleAreaDialog.class).matches(item)){ DefaultShell shell = new DefaultShell((Shell)item); TitleAreaDialog ta = new TitleAreaDialog(shell); return matcher.matches(ta.getTitle()); } } catch (RedDeerException e) { if(((Shell) item).isDisposed()){ return false; } throw e; } } return false; }