auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void getBitstreamFormat() throws Exception { getClient().perform(get("/api/core/bitstreams/" + bitstream.getID() + "/format")) .andExpect(status().isUnauthorized()); getClient(getAuthToken(eperson.getEmail(), password)) .perform(get("/api/core/bitstreams/" + bitstream.getID() + "/format")) .andExpect(status().isForbidden()); context.turnOffAuthorisationSystem(); resourcePolicy = resourcePolicyService.create(context); resourcePolicy.setEPerson(eperson); resourcePolicy.setAction(READ); resourcePolicy.setdSpaceObject(bitstream); <START> context.commit(); <END> getClient(getAuthToken(eperson.getEmail(), password)) .perform(get("/api/core/bitstreams/" + bitstream.getID() + "/format")) .andExpect(status().isOk()); getClient(getAuthToken(admin.getEmail(), password)) .perform(get("/api/core/bitstreams/" + bitstream.getID() + "/format")) .andExpect(status().isOk()) .andExpect(jsonPath("$", matchBitstreamFormat( supportedFormat.getID(), supportedFormat.getMIMEType(), supportedFormat.getDescription(), supportedFormat.getShortDescription(), "SUPPORTED" ))); }</code><technical_language>This a commit(). instead a context.restoreAuthSystemState();</technical_language>

Target:
public void getBitstreamFormat() throws Exception { getClient() .perform(get("/api/core/bitstreams/" + bitstream.getID() + "/format")) .andExpect(status().isOk()) .andExpect(jsonPath("$", matchBitstreamFormat( supportedFormat.getID(), supportedFormat.getMIMEType(), supportedFormat.getDescription(), supportedFormat.getShortDescription(), "SUPPORTED" ))); }
Source:
<code>private ClientConfig getConfigFromLocation(URI location, ClassLoader classLoader, String instanceName) throws URISyntaxException, IOException { String scheme = location.getScheme(); if (scheme == null) { location = new URI(System.getProperty(location.getRawSchemeSpecificPart())); scheme = location.getScheme(); } ClassLoader theClassLoader = classLoader == null ? getDefaultClassLoader() : classLoader; URL configURL; if ("classpath".equals(scheme)) { configURL = theClassLoader.getResource(location.getRawSchemeSpecificPart()); } else if ("file".equals(scheme) || "http".equals(scheme) || "https".equals(scheme)) { configURL = location.toURL(); } else { throw new URISyntaxException(location.toString(), "Unsupported protocol in configuration location URL"); } try { <START> return getConfig(configURL, classLoader, instanceName); <END> } catch (Exception e) { throw rethrow(e); } }</code><technical_language>a discrepancy server-side, effect all: classLoader is null, theClassLoader is assigned loaded hazelcast classes. A null classloader in ClientConfig essentially effect - ends resolve classes ClassLoaderUtil#newInstance -- a null classloader, loaded Hazelcast classes for class resolution. Nevertheless, for uniformity's sake, client-side theClassLoader</technical_language>

Target:
private ClientConfig getConfigFromLocation(URI location, ClassLoader classLoader, String instanceName) throws URISyntaxException, IOException { String scheme = location.getScheme(); if (scheme == null) { location = new URI(System.getProperty(location.getRawSchemeSpecificPart())); scheme = location.getScheme(); } ClassLoader theClassLoader = classLoader == null ? getDefaultClassLoader() : classLoader; URL configURL; if ("classpath".equals(scheme)) { configURL = theClassLoader.getResource(location.getRawSchemeSpecificPart()); } else if ("file".equals(scheme) || "http".equals(scheme) || "https".equals(scheme)) { configURL = location.toURL(); } else { throw new URISyntaxException(location.toString(), "Unsupported protocol in configuration location URL"); } try { return getConfig(configURL, theClassLoader, instanceName); } catch (Exception e) { throw rethrow(e); } }
Source:
<code>public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { String entityName = context.field.getName(); String aliasName = context.field.getAlias(); <START> String keyName = (aliasName == null ? "" : aliasName) + ":" + entityName; <END> return fetcher.fetchObject( context.requestScope, context.requestScope .getProjectionInfo() .getProjections() .get(keyName), context.ids ); }</code><technical_language>put this a static function logic duplicated</technical_language>

Target:
public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { String entityName = context.field.getName(); String aliasName = context.field.getAlias(); return fetcher.fetchObject( context.requestScope, context.requestScope .getProjectionInfo() .getProjection(aliasName, entityName), context.ids ); }
Source:
<code>protected TokenResponse executeRefreshToken() throws IOException { GenerateAccessTokenResponse accessTokenResponse = null; try { accessTokenResponse = generateAccessToken(); } catch (GeneralSecurityException e) { throw new RuntimeException("Failed to get access token", e); } String accessToken = <START> Preconditions.checkNotNull( <END> accessTokenResponse.getAccessToken(), "Access Token cannot be null!"); Instant expirationTimeInInstant = Instant.parse(accessTokenResponse.getExpireTime()); Long expirationTimeMilliSeconds = expirationTimeInInstant.toEpochMilli(); return new TokenResponse() .setAccessToken(accessToken) .setExpiresInSeconds( expirationTimeMilliSeconds == null ? null : (expirationTimeMilliSeconds - clock.currentTimeMillis()) / 1000); }</code><technical_language>Statically import checkNotNull instead</technical_language>

Target:
protected TokenResponse executeRefreshToken() throws IOException { GenerateAccessTokenResponse accessTokenResponse = generateAccessToken(); TokenResponse tokenResponse = new TokenResponse().setAccessToken(accessTokenResponse.getAccessToken()); if (isNullOrEmpty(accessTokenResponse.getExpireTime())) { return tokenResponse; } Instant expirationTimeInInstant = Instant.parse(accessTokenResponse.getExpireTime()); long expirationTimeMilliSeconds = expirationTimeInInstant.getEpochSecond(); return tokenResponse.setExpiresInSeconds( expirationTimeMilliSeconds - clock.currentTimeMillis() / 1000); }
Source:
<code>public Class<? extends Compressor> getCompressorType() { <START> return LzopCodec.HadoopLzopCompressor.class; <END> }</code><technical_language>I createCompressor returns HadoopLzoCompressor(). in sync</technical_language>

Target:
public Class<? extends Compressor> getCompressorType() { return LzopCompressor.class; }
Source:
<code>protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { if (anyFailed) { <START> setCommandEndStatus(command, anyFailed, status, childCmdIds); <END> return; } else { RemoveVmPoolCommand<? extends VmPoolParametersBase> removeVmPoolCommand = (RemoveVmPoolCommand) command; VmPool pool = DbFacade.getInstance().getVmPoolDao().get(removeVmPoolCommand.getVmPoolId()); if (pool == null || pool.getRunningVmsCount() == 0) { setCommandEndStatus(command, false, status, childCmdIds); return; } } }</code><technical_language>anyFailed is true here</technical_language>

Target:
protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { if (anyFailed) { setCommandEndStatus(command, true, status, childCmdIds); } else { RemoveVmPoolCommand<? extends VmPoolParametersBase> removeVmPoolCommand = (RemoveVmPoolCommand<? extends VmPoolParametersBase>) command; VmPool pool = DbFacade.getInstance().getVmPoolDao().get(removeVmPoolCommand.getVmPoolId()); if (pool == null || pool.getRunningVmsCount() == 0) { setCommandEndStatus(command, false, status, childCmdIds); } } }
Source:
<code>protected boolean validate() { if (!super.validate()) { return false; } if (!getGlusterVolume().getVolumeType().isReplicatedType()) { addValidationMessage(EngineMessage.ACTION_TYPE_NOT_SUPPORTED_FOR_VOLUME_TYPE); return false; } if (!getGlusterVolume().isOnline()) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); return false; } if (getGlusterVolume().getAsyncTask() != null && getGlusterVolume().getAsyncTask().getStatus() == <START> JobExecutionStatus.STARTED) { <END> addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_VOLUME_HAS_RUNNING_TASKS); return false; } if (getParameters().getExistingBrick() == null || getParameters().getNewBrick() == null) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_BRICKS_REQUIRED); return false; } if (!isValidVolumeBrick(getParameters().getExistingBrick())) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_NOT_A_GLUSTER_VOLUME_BRICK); return false; } if (!updateBrickServerAndInterfaceName(getParameters().getNewBrick(), true)) { return false; } return true; }</code><technical_language>remove brick action finished status?. Remove brick committed retained enable other operations i think. VolumeBrickListModel.java line 210</technical_language>

Target:
protected boolean validate() { if (!super.validate()) { return false; } if (!getGlusterVolume().getVolumeType().isReplicatedType()) { addValidationMessage(EngineMessage.ACTION_TYPE_NOT_SUPPORTED_FOR_VOLUME_TYPE); return false; } if (!getGlusterVolume().isOnline()) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); return false; } if (getGlusterVolume().getAsyncTask() != null && (getGlusterVolume().getAsyncTask().getStatus() == JobExecutionStatus.STARTED || getGlusterVolume().getAsyncTask().getType() == GlusterTaskType.REMOVE_BRICK && getGlusterVolume().getAsyncTask().getStatus() == JobExecutionStatus.FINISHED)) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_VOLUME_OPERATION_IN_PROGRESS); return false; } if (getParameters().getExistingBrick() == null || getParameters().getNewBrick() == null) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_BRICKS_REQUIRED); return false; } if (!isValidVolumeBrick(getParameters().getExistingBrick())) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_NOT_A_GLUSTER_VOLUME_BRICK); return false; } if (!updateBrickServerAndInterfaceName(getParameters().getNewBrick(), true)) { return false; } return true; }
Source:
<code>public void doDecrypt(String productBranding, String productVersion) { <START> Validate.notNull(productBranding, "invalid null product branding"); <END> Validate.notNull(productVersion, "invalid null product version"); final String ddfHome = System.getProperty("ddf.home"); LOGGER.debug( "Decrypting product under from to [{}]...", productBranding, productVersion, ddfHome, exportFile, decryptFile); zip.stream().forEach(this::decrypt); }</code><technical_language>Do accept blank branding versions</technical_language>

Target:
public void doDecrypt(String productBranding, String productVersion) { Validate.notNull(productBranding, "invalid null product branding"); Validate.notNull(productVersion, "invalid null product version"); final String ddfHome = System.getProperty("ddf.home"); LOGGER.debug( "Decrypting product under from to [{}]...", productBranding, productVersion, ddfHome, exportFile, decryptFile); zip.stream().forEach(this::copyToOutputZipFile); }
Source:
<code>public ChromeOptions merge(Capabilities extraCapabilities) { super.merge(extraCapabilities); if (extraCapabilities instanceof ChromeOptions) { <START> Map options = (Map) extraCapabilities.asMap().get("goog:chromeOptions"); <END> mergeArguments(options); mergeExtensions(options); mergeExtensionFiles(extraCapabilities); mergeBinary(options); mergeExperimentalOptions(extraCapabilities); } return this; }</code><technical_language>Please generics. If obvious type, Map<?, ?> prevents compiler warnings, is correct, is equally meaningless :)</technical_language>

Target:
public ChromeOptions merge(Capabilities extraCapabilities) { super.merge(extraCapabilities); return this; }
Source:
<code>public int hashCode() { <START> return messageId() != null ? messageId().hashCode() : 0; <END> }</code><technical_language>In equals method check for null... message id null anyway</technical_language>

Target:
public int hashCode() { return messageId().hashCode(); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GenericArrayData that = (GenericArrayData) o; return size == that.size && isPrimitiveArray == that.isPrimitiveArray && <START> Arrays.deepEquals(new Object[] {array}, new Object[]{that.array}); <END> }</code><technical_language>need Arrays.deepEquals for GenericRowData.equals</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GenericArrayData that = (GenericArrayData) o; return size == that.size && isPrimitiveArray == that.isPrimitiveArray && Objects.deepEquals(array, that.array); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { AdapterFactory adapterFactory = new ComposedAdapterFactory( ComposedAdapterFactory.Descriptor.Registry.INSTANCE); final IWorkbenchPart activePart = HandlerUtil.getActivePart(event); final ISelection currentSelection = HandlerUtil.getCurrentSelection(event); if (currentSelection instanceof IStructuredSelection) { Iterator<?> iterator = ((IStructuredSelection)currentSelection).iterator(); Notifier left = null; Notifier right = null; Notifier origin = null; left = (Notifier)iterator.next(); if (iterator.hasNext()) { right = (Notifier)iterator.next(); } if (iterator.hasNext()) { origin = (Notifier)iterator.next(); } if (origin != null) { Shell shell = HandlerUtil.getActiveShell(event); SelectAncestorDialog dialog = new SelectAncestorDialog(shell, adapterFactory, new Notifier[] { left, right, origin }); if (dialog.open() == Window.CANCEL) { return null; } else { left = dialog.leftNotifier; right = dialog.rightNotifier; origin = dialog.originNotifier; } } <START> if (isContained(left, right) || isContained(right, left)) { <END> MessageDialog .openInformation(activePart.getSite().getShell(), "EMF Compare", "Can't run a comparison between an object and one of its direct or indirect container."); } else { final CompareEditorInput input = createCompareEditorInput(activePart, adapterFactory, left, right, origin); CompareUI.openCompareDialog(input); } } return null; }</code><technical_language>please, replace EcoreUtil.isAncestor(EObject, EObject) more efficient future proof method</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { AdapterFactory adapterFactory = new ComposedAdapterFactory( ComposedAdapterFactory.Descriptor.Registry.INSTANCE); final IWorkbenchPart activePart = HandlerUtil.getActivePart(event); final ISelection currentSelection = HandlerUtil.getCurrentSelection(event); if (currentSelection instanceof IStructuredSelection) { Iterator<?> iterator = ((IStructuredSelection)currentSelection).iterator(); Notifier left = null; Notifier right = null; Notifier origin = null; left = (Notifier)iterator.next(); if (iterator.hasNext()) { right = (Notifier)iterator.next(); } if (iterator.hasNext()) { origin = (Notifier)iterator.next(); } if (origin != null) { Shell shell = HandlerUtil.getActiveShell(event); SelectAncestorDialog dialog = new SelectAncestorDialog(shell, adapterFactory, new Notifier[] { left, right, origin }); if (dialog.open() == Window.CANCEL) { return null; } else { left = dialog.leftNotifier; right = dialog.rightNotifier; origin = dialog.originNotifier; } } if (left instanceof EObject && right instanceof EObject && (EcoreUtil.isAncestor((EObject)left, (EObject)right) || EcoreUtil.isAncestor( (EObject)right, (EObject)left))) { MessageDialog.openInformation(activePart.getSite().getShell(), "EMF Compare", "Can't run a comparison between an object and one of its ancestor."); } else { final CompareEditorInput input = createCompareEditorInput(activePart, adapterFactory, left, right, origin); CompareUI.openCompareDialog(input); } } return null; }
Source:
<code>public static StreamRecord toStreamRecordV2(final com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord streamRecord) { StreamRecord.Builder streamRecordBuilder = StreamRecord.builder() .approximateCreationDateTime( streamRecord.getApproximateCreationDateTime().toInstant() ) .keys( <START> DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getKeys()) ) .sequenceNumber(streamRecord.getSequenceNumber()) <END> .sizeBytes(streamRecord.getSizeBytes()) .streamViewType(streamRecord.getStreamViewType()); Map<String, com.amazonaws.services.lambda.runtime.events.models.dynamodb.AttributeValue> newImage = streamRecord.getNewImage(); if (newImage != null) { streamRecordBuilder.newImage( DynamodbAttributeValueTransformer.toAttributeValueMapV2(newImage) ); } Map<String, com.amazonaws.services.lambda.runtime.events.models.dynamodb.AttributeValue> oldImage = streamRecord.getOldImage(); if (oldImage != null) { streamRecordBuilder.oldImage( DynamodbAttributeValueTransformer.toAttributeValueMapV2(oldImage) ); } return streamRecordBuilder.build(); }</code><technical_language>ternary operator for a null check instead, such: java .newImage( streamRecord.getNewImage() != null ? DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getNewImage()) : null )</technical_language>

Target:
public static StreamRecord toStreamRecordV2(final com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord streamRecord) { return StreamRecord.builder() .approximateCreationDateTime( streamRecord.getApproximateCreationDateTime().toInstant() ) .keys( DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getKeys()) ) .newImage( streamRecord.getNewImage() != null ? DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getNewImage()) : null ) .oldImage( streamRecord.getOldImage() != null ? DynamodbAttributeValueTransformer.toAttributeValueMapV2(streamRecord.getOldImage()) : null ) .sequenceNumber(streamRecord.getSequenceNumber()) .sizeBytes(streamRecord.getSizeBytes()) .streamViewType(streamRecord.getStreamViewType()) .build(); }
Source:
<code>public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("plan", "plan_123"); params.put("subscription", "cus_123"); params.put("quantity", 99); <START> SubscriptionItem subscriptionItem = SubscriptionItem.create(params); <END> assertNotNull(subscriptionItem); verifyRequest( APIResource.RequestMethod.POST, "/v1/subscription_items", params ); }</code><technical_language>called resource</technical_language>

Target:
public void testCreate() throws StripeException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("plan", "plan_123"); params.put("subscription", "cus_123"); params.put("quantity", 99); final SubscriptionItem subscriptionItem = SubscriptionItem.create(params); assertNotNull(subscriptionItem); verifyRequest( APIResource.RequestMethod.POST, "/v1/subscription_items", params ); }
Source:
<code>public static ComputerSystem logicalRouter2ComputerSystem(String logicalRouterName, InterfacesNamesList interfacesNames) { ComputerSystem logicalRouter = new ComputerSystem(); logicalRouter.setName(logicalRouterName); <START> <END> if (interfacesNames != null) { for (String interfaceName : interfacesNames.getInterfaces()) { logicalRouter.addLogicalDevice(subInterfaceName2NetworkPort(interfaceName)); } } return logicalRouter; }</code><technical_language>I add ElementName for logical routers</technical_language>

Target:
public static ComputerSystem logicalRouter2ComputerSystem(String logicalRouterName, InterfacesNamesList interfacesNames) { ComputerSystem logicalRouter = new ComputerSystem(); logicalRouter.setName(logicalRouterName); logicalRouter.setElementName(logicalRouterName); if (interfacesNames != null) { for (String interfaceName : interfacesNames.getInterfaces()) { logicalRouter.addLogicalDevice(subInterfaceName2NetworkPort(interfaceName)); } } return logicalRouter; }
Source:
<code>public void close() { if (mCompressedInputStream != null) { try { mCompressedInputStream.close(); } catch (IOException e) { <START> throw new SAMException("Exception closing compressed input stream.", e); <END> } } if (mStream != null) { mStream.close(); } if (mIndex != null) { mIndex.close(); } mStream = null; mFileHeader = null; mIndex = null; }</code><technical_language>more specific RuntimeIOException</technical_language>

Target:
public void close() { if (mCompressedInputStream != null) { try { mCompressedInputStream.close(); } catch (IOException e) { throw new RuntimeIOException("Exception closing compressed input stream.", e); } } if (mStream != null) { mStream.close(); } if (mIndex != null) { mIndex.close(); } mStream = null; mFileHeader = null; mIndex = null; }
Source:
<code>void scheduleNext() { synchronized (this) { if (pendingTasks.size() <= 0) { return; } do { pendingTasks.remove(); final InstrumentedTask task = pendingTasks.peek(); if (task == null) { return; } executeTask(task); } <START> while (spaceAvailable()); <END> } }</code><technical_language>in case multiple tasks pile pending task queue, executes pushed out of space again. this method exit completing all. space is again</technical_language>

Target:
void scheduleNext() { synchronized (this) { if (pendingTasks.size() <= 0) { return; } pendingTasks.remove(); try { while (true) { final InstrumentedTask task = pendingTasks.peek(); if (task == null) { return; } if (!spaceAvailable()) { break; } task.setCompletion(this::finishTask); executeTask(task); pendingTasks.remove(); } } catch (RejectedExecutionException ignore) { } restartQueue(); } }
Source:
<code>public DynamicBucketNodeMap(ToIntFunction<Split> splitToBucket, int bucketCount) { super(splitToBucket); this.bucketCount = bucketCount; <START> } <END></code><technical_language>Assert bucketCount is positive</technical_language>

Target:
public DynamicBucketNodeMap(ToIntFunction<Split> splitToBucket, int bucketCount) { super(splitToBucket); checkArgument(bucketCount > 0, "bucketCount must be positive"); this.bucketCount = bucketCount; }
Source:
<code>public void testListWithOptions() throws Exception { String lexicographicallyBeforeName = name.substring(0, name.length() - 1); for (String regionId : regions) { ListContainerOptions options = ListContainerOptions.Builder.marker(lexicographicallyBeforeName); Container container = api.getContainerApi(regionId).list(options).firstMatch(new Predicate<Container>() { @Override public boolean apply(Container container) { return container.getName().equals(name); } }).get(); assertNotNull(container); <START> assertEquals(container.getName(), name); <END> assertTrue(container.getObjectCount() == 0); assertTrue(container.getBytesUsed() == 0); } }</code><technical_language>This is true</technical_language>

Target:
public void testListWithOptions() throws Exception { String lexicographicallyBeforeName = name.substring(0, name.length() - 1); for (String regionId : regions) { ListContainerOptions options = ListContainerOptions.Builder.marker(lexicographicallyBeforeName); Container container = api.getContainerApi(regionId).list(options).firstMatch(new Predicate<Container>() { @Override public boolean apply(Container container) { return container.getName().equals(name); } }).get(); assertTrue(container.getObjectCount() == 0); assertTrue(container.getBytesUsed() == 0); } }
Source:
<code>private void init() { try{ migrateDatasets(); migratePerspectives(); migrateNavigation(); } catch (Exception e) { <START> LOGGER.error("Failed during dashbuilder migration process."); <END> } }</code><technical_language>I print original exception stack trace in debug mode</technical_language>

Target:
private void init() { try{ if (!clusterParameters.isAppFormerClustered()) { migrateDatasets(); migratePerspectives(); migrateNavigation(); } } catch (Exception e) { LOGGER.error("Failed during dashbuilder migration process."); LOGGER.debug("Error during dashbuilder migration", e); } }
Source:
<code>public void testFetchSkipsBlackedOutNodes() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); <START> client.updateMetadata(initialUpdateResponseWithLeaderEpoch); <END> Node node = initialUpdateResponse.brokers().iterator().next(); client.blackout(node, 500); assertEquals(0, fetcher.sendFetches()); time.sleep(500); assertEquals(1, fetcher.sendFetches()); }</code><technical_language>Do need change some of other tests? initialUpdateResponse in assignFromUser below</technical_language>

Target:
public void testFetchSkipsBlackedOutNodes() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); Node node = initialUpdateResponse.brokers().iterator().next(); client.blackout(node, 500); assertEquals(0, fetcher.sendFetches()); time.sleep(500); assertEquals(1, fetcher.sendFetches()); }
Source:
<code>private void analyzeReplLoad(ASTNode ast) throws SemanticException { try { initReplLoad(ast); } catch (HiveException e) { throw new SemanticException(e); } try { assert(sourceDbNameOrPattern != null); Path loadPath = getCurrentLoadPath(); try { Warehouse wh = new Warehouse(conf); Path filePath = wh.getWhRoot(); if (ifEnableMoveOptimization(filePath, conf)) { conf.setBoolVar(REPL_ENABLE_MOVE_OPTIMIZATION, true); LOG.info(" Set move optimization to true for warehouse " + filePath.toString()); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } <START> if (isTargetAlreadyLoaded) { <END> return; } else { DumpMetaData dmd = new DumpMetaData(loadPath, conf); boolean evDump = false; if (dmd.isIncrementalDump()) { LOG.debug("{} contains an incremental dump", loadPath); evDump = true; } else { LOG.debug("{} contains an bootstrap dump", loadPath); } ReplLoadWork replLoadWork = new ReplLoadWork(conf, loadPath.toString(), replScope.getDbName(), dmd.getReplScope(), queryState.getLineageState(), evDump, dmd.getEventTo(), dirLocationsToCopy(loadPath, evDump)); rootTasks.add(TaskFactory.get(replLoadWork, conf)); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }</code><technical_language>do a !isTargetAlreadyLoaded conditional {}</technical_language>

Target:
private void analyzeReplLoad(ASTNode ast) throws SemanticException { try { initReplLoad(ast); } catch (HiveException e) { throw new SemanticException(e); } try { assert(sourceDbNameOrPattern != null); Path loadPath = getCurrentLoadPath(); try { Warehouse wh = new Warehouse(conf); Path filePath = wh.getWhRoot(); if (ifEnableMoveOptimization(filePath, conf)) { conf.setBoolVar(REPL_ENABLE_MOVE_OPTIMIZATION, true); LOG.info(" Set move optimization to true for warehouse " + filePath.toString()); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } if (!isTargetAlreadyLoaded) { DumpMetaData dmd = new DumpMetaData(loadPath, conf); boolean evDump = false; if (dmd.isIncrementalDump()) { LOG.debug("{} contains an incremental dump", loadPath); evDump = true; } else { LOG.debug("{} contains an bootstrap dump", loadPath); } ReplLoadWork replLoadWork = new ReplLoadWork(conf, loadPath.toString(), replScope.getDbName(), dmd.getReplScope(), queryState.getLineageState(), evDump, dmd.getEventTo(), dirLocationsToCopy(loadPath, evDump)); rootTasks.add(TaskFactory.get(replLoadWork, conf)); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }
Source:
<code>public void testVcf42Roundtrip() throws Exception { File expectedFile = new File("src/test/resources/htsjdk/variant/Vcf4.2WithSourceVersionInfoFields.vcf"); final VCFFileReader originalFileReader = new VCFFileReader(expectedFile, false); final VCFHeader originalHeader = originalFileReader.getFileHeader(); final File actualFile = File.createTempFile("testVcf4.2roundtrip.", IOUtil.VCF_FILE_EXTENSION); actualFile.deleteOnExit(); final VariantContextWriter copyWriter = new VariantContextWriterBuilder() .setOutputFile(actualFile) .setReferenceDictionary(createArtificialSequenceDictionary()) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY)) .build(); copyWriter.writeHeader(originalHeader); final CloseableIterator<VariantContext> firstCopyVariantIterator = originalFileReader.iterator(); while (firstCopyVariantIterator.hasNext()) { VariantContext variantContext = firstCopyVariantIterator.next(); copyWriter.add(variantContext); } originalFileReader.close(); <START> copyWriter.close(); <END> final String actualContents = new String(Files.readAllBytes(actualFile.toPath()), StandardCharsets.UTF_8); final String expectedContents = new String(Files.readAllBytes(expectedFile.toPath()), StandardCharsets.UTF_8); Assert.assertEquals(actualContents, expectedContents); }</code><technical_language>try-with-resources for of avoid manual closing</technical_language>

Target:
public void testVcf42Roundtrip() throws Exception { File expectedFile = new File("src/test/resources/htsjdk/variant/Vcf4.2WithSourceVersionInfoFields.vcf"); final File actualFile = File.createTempFile("testVcf4.2roundtrip.", IOUtil.VCF_FILE_EXTENSION); actualFile.deleteOnExit(); try (final VCFFileReader originalFileReader = new VCFFileReader(expectedFile, false); final VariantContextWriter copyWriter = new VariantContextWriterBuilder() .setOutputFile(actualFile) .setReferenceDictionary(createArtificialSequenceDictionary()) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY)) .build() ) { final VCFHeader originalHeader = originalFileReader.getFileHeader(); copyWriter.writeHeader(originalHeader); for (final VariantContext variantContext : originalFileReader) { copyWriter.add(variantContext); } } final String actualContents = new String(Files.readAllBytes(actualFile.toPath()), StandardCharsets.UTF_8); final String expectedContents = new String(Files.readAllBytes(expectedFile.toPath()), StandardCharsets.UTF_8); Assert.assertEquals(actualContents, expectedContents); }
Source:
<code>public boolean add(E e) { if (this.underlyingQueue.add(new ThroughputElement<E>(e))) { this.elementsAdded.incrementAndGet(); <START> synchronized (this) { <END> if (!this.active) { this.startTime.set(System.currentTimeMillis()); this.active = true; } } return true; } return false; }</code><technical_language>this abstracted a common method this.elementsAdded.incrementAndGet(); synchronized (this) { if (!this.active) { this.startTime.set(System.currentTimeMillis()); this.active = true; } }</technical_language>

Target:
public boolean add(E e) { if (this.underlyingQueue.add(new ThroughputElement<E>(e))) { internalAddElement(); return true; } return false; }
Source:
<code>public void shouldConstructANewEntity() { ChargeEntity chargeEntity = aValidChargeEntity().build(); Long amount = 100L; <START> RefundEntity refundEntity = new RefundEntity(chargeEntity, amount, null); <END> assertNotNull(refundEntity.getExternalId()); assertThat(refundEntity.getChargeEntity(), is(chargeEntity)); assertThat(refundEntity.getReference(), is(nullValue())); assertThat(refundEntity.getAmount(), is(amount)); assertThat(refundEntity.getStatus(), is(RefundStatus.CREATED)); assertNotNull(refundEntity.getCreatedDate()); }</code><technical_language>Again, this actual assert refund stores this</technical_language>

Target:
public void shouldConstructANewEntity() { ChargeEntity chargeEntity = aValidChargeEntity().build(); Long amount = 100L; RefundEntity refundEntity = new RefundEntity(chargeEntity, amount, userExternalId); assertNotNull(refundEntity.getExternalId()); assertThat(refundEntity.getChargeEntity(), is(chargeEntity)); assertThat(refundEntity.getReference(), is(nullValue())); assertThat(refundEntity.getAmount(), is(amount)); assertThat(refundEntity.getStatus(), is(RefundStatus.CREATED)); assertThat(refundEntity.getUserExternalId(), is(userExternalId)); assertNotNull(refundEntity.getCreatedDate()); }
Source:
<code>private void schedule() { int delay = initialDelay * (int) Math.pow(delayGrowth, failedAttempts); if (maxDelay != -1 && delay > maxDelay) { log.debug("Maximum delay reached", maxDelay); delay = maxDelay; } log.debug("Next Transitioner check will run after seconds", delay); <START> if (failedAttempts > 3) { <END> log.info("SuspendModeTransitioner failed to reconnect to the Qpid Broker " + "{} times, backing off with next reconnect seconds", failedAttempts, delay); } execService.schedule(this, delay, TimeUnit.SECONDS); }</code><technical_language>wait 3rd attempt log a message</technical_language>

Target:
private void schedule() { BigInteger delay = BigInteger.valueOf(initialDelay) .add(BigInteger.valueOf(delayGrowth) .multiply(failedAttempts)); if (maxDelay != -1 && delay.compareTo(BigInteger.valueOf(maxDelay)) > 0) { log.debug("Maximum delay reached", maxDelay); delay = BigInteger.valueOf(maxDelay); } log.debug("Next Transitioner check will run after seconds", delay); if (failedAttempts.compareTo(BigInteger.ZERO) > 0) { log.info("SuspendModeTransitioner failed to reconnect to the Qpid Broker " + "{} times, backing off with next reconnect seconds", failedAttempts, delay); } execService.schedule(this, delay.longValue(), TimeUnit.SECONDS); }
Source:
<code>public static MultiFactorAuthenticationSupportingWebApplicationService createServiceFrom(final HttpServletRequest request, final HttpClient httpClient, final List<String> supportedLevelsOfAuthentication) { LOGGER.debug("Attempting to extract multifactor authentication parameters from the request"); final String targetService = request.getParameter(CONST_PARAM_TARGET_SERVICE); <START> final String loa = request.getParameter(CONST_PARAM_AUTHN_METHOD); <END> final String serviceToUse = StringUtils.hasText(targetService) ? targetService : request.getParameter(CONST_PARAM_SERVICE); if (!StringUtils.hasText(serviceToUse)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_SERVICE); return null; } if (!StringUtils.hasText(loa)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_AUTHN_METHOD); return null; } if (!supportedLevelsOfAuthentication.contains(loa)) { LOGGER.debug("Multifactor authentication service does not support parameter value [{}].", CONST_PARAM_AUTHN_METHOD, loa); return null; } final String id = cleanupUrl(serviceToUse); final String artifactId = request.getParameter(CONST_PARAM_TICKET); final MultiFactorAuthenticationSupportingWebApplicationService svc = new DefaultMultiFactorAuthenticationSupportingWebApplicationService( id, serviceToUse, artifactId, httpClient, loa); LOGGER.debug("Created multifactor authentication request for with as [{}].", svc.getId(), CONST_PARAM_AUTHN_METHOD, svc.getAuthenticationMethod()); return svc; }</code><technical_language>rename this String authenticationMethod ? :)</technical_language>

Target:
public static MultiFactorAuthenticationSupportingWebApplicationService createServiceFrom(final HttpServletRequest request, final HttpClient httpClient, final List<String> supportedLevelsOfAuthentication) { LOGGER.debug("Attempting to extract multifactor authentication parameters from the request"); final String targetService = request.getParameter(CONST_PARAM_TARGET_SERVICE); final String authenticationMethod = request.getParameter(CONST_PARAM_AUTHN_METHOD); final String serviceToUse = StringUtils.hasText(targetService) ? targetService : request.getParameter(CONST_PARAM_SERVICE); if (!StringUtils.hasText(serviceToUse)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_SERVICE); return null; } if (!StringUtils.hasText(authenticationMethod)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_AUTHN_METHOD); return null; } if (!supportedLevelsOfAuthentication.contains(authenticationMethod)) { LOGGER.debug("Multifactor authentication service does not support parameter value [{}].", CONST_PARAM_AUTHN_METHOD, authenticationMethod); return null; } final String id = cleanupUrl(serviceToUse); final String artifactId = request.getParameter(CONST_PARAM_TICKET); final MultiFactorAuthenticationSupportingWebApplicationService svc = new DefaultMultiFactorAuthenticationSupportingWebApplicationService( id, serviceToUse, artifactId, httpClient, authenticationMethod); LOGGER.debug("Created multifactor authentication request for with as [{}].", svc.getId(), CONST_PARAM_AUTHN_METHOD, svc.getAuthenticationMethod()); return svc; }
Source:
<code>public static String getKeyBytesSha(byte[] keyBytes) { String keyBytesSha; try { <START> MessageDigest digest = MessageDigest.getInstance("SHA-256"); <END> byte[] sha = digest.digest(keyBytes); keyBytesSha = Base64.encodeBytes(sha); } catch(NoSuchAlgorithmException e) { throw new JpaStoreException("Failed to create SHA hash of metadata key", e); } return keyBytesSha; }</code><technical_language>Turn "SHA-256" a constant</technical_language>

Target:
public static String getKeyBytesSha(byte[] keyBytes) { String keyBytesSha; try { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALG); byte[] sha = digest.digest(keyBytes); keyBytesSha = Base64.encodeBytes(sha); } catch(NoSuchAlgorithmException e) { throw new JpaStoreException("Failed to create SHA hash of metadata key", e); } return keyBytesSha; }
Source:
<code>static boolean canHandle(final URIish uri, FS fs) throws NotSupportedException { if (uri.getHost() != null || uri.getPort() > 0 || uri.getUser() != null || uri.getPass() != null || uri.getPath() == null) return false; if ("file".equals(uri.getScheme()) || uri.getScheme() == null) { if (fs.resolve(new File(PWD), uri.getPath()).isDirectory()) { return true; } else { <START> throw new NotSupportedException(uri.getPath() + " does not exist"); <END> } } return false; }</code><technical_language>This message translated MessageFormat JGitText</technical_language>

Target:
static boolean canHandle(final URIish uri, FS fs) throws NotSupportedException { if (uri.getHost() != null || uri.getPort() > 0 || uri.getUser() != null || uri.getPass() != null || uri.getPath() == null) return false; if ("file".equals(uri.getScheme()) || uri.getScheme() == null) { if (fs.resolve(new File(PWD), uri.getPath()).isDirectory()) { return true; } else { throw new NotSupportedException(MessageFormat.format( JGitText.get().cannotFindRepository, uri.getPath())); } } return false; }
Source:
<code>protected int run() throws Exception { <START> Jenkins.getActiveInstance().checkPermission(Jenkins.ADMINISTER); <END> Binding binding = new Binding(); binding.setProperty("out",new PrintWriter(stdout,true)); binding.setProperty("stdin",stdin); binding.setProperty("stdout",stdout); binding.setProperty("stderr",stderr); GroovyShell groovy = new GroovyShell(Jenkins.get().getPluginManager().uberClassLoader, binding); groovy.run(loadScript(),"RemoteClass",remaining.toArray(new String[0])); return 0; }</code><technical_language>is this change active instance required</technical_language>

Target:
protected int run() throws Exception { Jenkins.get().checkPermission(Jenkins.ADMINISTER); Binding binding = new Binding(); binding.setProperty("out",new PrintWriter(stdout,true)); binding.setProperty("stdin",stdin); binding.setProperty("stdout",stdout); binding.setProperty("stderr",stderr); GroovyShell groovy = new GroovyShell(Jenkins.get().getPluginManager().uberClassLoader, binding); groovy.run(loadScript(),"RemoteClass",remaining.toArray(new String[0])); return 0; }
Source:
<code>public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { <START> getTempFile().delete(); <END> tmpFile.close(); tmpFile = null; txFile = null; } freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; }</code><technical_language>this temp file delete close of RandomAccessFile</technical_language>

Target:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { tmpFile.close(); getTempFile().delete(); tmpFile = null; txFile = null; } freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; }
Source:
<code>public void addEntries(ISourceContainer[] entries) { int index = 0; IStructuredSelection sel = getStructuredSelection(); if (!sel.isEmpty()) { index = fEntries.indexOf(sel.getFirstElement()); } for (ISourceContainer <START> entrie : <END> entries) { if (!fEntries.contains(entrie)) { fEntries.add(index, entrie); index++; } } refresh(); if(entries.length > 0) { setSelection(new StructuredSelection(entries)); } fPanel.setDirty(true); fPanel.updateLaunchConfigurationDialog(); }</code><technical_language>rename entry</technical_language>

Target:
public void addEntries(ISourceContainer[] entries) { int index = 0; IStructuredSelection sel = getStructuredSelection(); if (!sel.isEmpty()) { index = fEntries.indexOf(sel.getFirstElement()); } for (ISourceContainer entry : entries) { if (!fEntries.contains(entry)) { fEntries.add(index, entry); index++; } } refresh(); if(entries.length > 0) { setSelection(new StructuredSelection(entries)); } fPanel.setDirty(true); fPanel.updateLaunchConfigurationDialog(); }
Source:
<code>private void setConflictsWith(GerritClient gerritClient, ChangeInfo element) { ChangeInfo[] conflictsWithChangeInfo = null; if (!("MERGED".equals(element.getStatus())) && !("ABANDONED".equals(element.getStatus()))) { try { conflictsWithChangeInfo = queryConflictsWith(gerritClient, element.getChange_id(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(gerritClient.getRepository().formatGerritVersion() + e.getMessage()); } List<ChangeInfo> conflictsWithChangeInfolistNew = new ArrayList<ChangeInfo>(); if (conflictsWithChangeInfo != null) { <START> for (ChangeInfo element2 : conflictsWithChangeInfo) { <END> if (element2.getChange_id().compareTo(fChangeInfo.getChange_id()) != 0) { conflictsWithChangeInfolistNew.add(element2); } } } fChangeInfo.getConflictsWith().clear(); fChangeInfo.getConflictsWith().addAll(conflictsWithChangeInfolistNew); } }</code><technical_language>Please rename variable element2</technical_language>

Target:
private void setConflictsWith(GerritClient gerritClient, ChangeInfo element) { ChangeInfo[] conflictsWithChangeInfo = null; if (!("MERGED".equals(element.getStatus())) && !("ABANDONED".equals(element.getStatus()))) { try { conflictsWithChangeInfo = queryConflictsWith(gerritClient, element.getChange_id(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(gerritClient.getRepository().formatGerritVersion() + e.getMessage()); } List<ChangeInfo> conflictsWithChangeInfolistNew = new ArrayList<ChangeInfo>(); if (conflictsWithChangeInfo != null) { for (ChangeInfo conflictChangeInfo : conflictsWithChangeInfo) { if (conflictChangeInfo.getChange_id().compareTo(fChangeInfo.getChange_id()) != 0) { conflictsWithChangeInfolistNew.add(conflictChangeInfo); } } } fChangeInfo.getConflictsWith().clear(); fChangeInfo.getConflictsWith().addAll(conflictsWithChangeInfolistNew); } }
Source:
<code>public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } List<CompletableFuture> futures = new ArrayList<>(MAX_ASYNC_EXPIRATIONS); long currentTimeMillis = timeService.wallClockTime(); dataContainer.forEachExpired((ice, segment) -> { if (ice.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; long maxIdle; <START> synchronized (ice) { <END> value = ice.getValue(); lifespan = ice.getLifespan(); maxIdle = ice.getMaxIdle(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, ice.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, ice.getLastUsed(), currentTimeMillis); } if (expiredMortal) { addAndWaitIfFull(handleLifespanExpireEntry(ice.getKey(), value, lifespan), futures); } else if (expiredTransient) { addAndWaitIfFull(actualRemoveMaxIdleExpireEntry(ice.getKey(), value, maxIdle), futures); } } }); if (!futures.isEmpty()) { futures.forEach(CompletableFuture::join); } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }</code><technical_language>I if this synchronization is necessary</technical_language>

Target:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } List<CompletableFuture> futures = new ArrayList<>(MAX_ASYNC_EXPIRATIONS); long currentTimeMillis = timeService.wallClockTime(); dataContainer.forEachIncludingExpired((ice, segment) -> { if (ice.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; long maxIdle; synchronized (ice) { value = ice.getValue(); lifespan = ice.getLifespan(); maxIdle = ice.getMaxIdle(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, ice.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, ice.getLastUsed(), currentTimeMillis); } if (expiredMortal) { addAndWaitIfFull(handleLifespanExpireEntry(ice.getKey(), value, lifespan), futures); } else if (expiredTransient) { addAndWaitIfFull(actualRemoveMaxIdleExpireEntry(ice.getKey(), value, maxIdle), futures); } } }); if (!futures.isEmpty()) { futures.forEach(CompletableFuture::join); } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }
Source:
<code><START> public int read() throws IOException { <END> return input.read(); }</code><technical_language>Please do annotate methods override @Override</technical_language>

Target:
public int read() throws IOException { return zipInput.read(); }
Source:
<code>protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { final String additionalPath = request.getPathInfo(); if (additionalPath.equals(CREATE_URL) || additionalPath.equals(INFO_URL)) { String configProp = request.getParameter("config"); Properties initParameters = this.initParametersOrig; if (configProp != null) { LOG.info("Set config to '" + configProp + "'"); } else { LOG.info("Use original config '" + this.configPropOrig + "'"); configProp = this.configPropOrig; } initParameters = setConfig(initParameters, configProp); <START> super.setInitParameters(initParameters); <END> super.afterPropertiesSet(); } return super.handleRequestInternal(request, response); }</code><technical_language>difficult, setInitParameters afterPropertiesSet modify internal state of controller (leading potential concurrency problems.) I easiest fix is simply create a new PrintingServletWrappingController initialize temporary configuration. handleRequestInternal instead of super.handleRequestInternal</technical_language>

Target:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { final String additionalPath = request.getPathInfo(); synchronized (additionalPath) { if (additionalPath.equals(CREATE_URL) || additionalPath.equals(INFO_URL)) { String configProp = request.getParameter("config"); Properties initParameters = this.initParametersOrig; if (configProp != null) { LOG.info("Set config to '" + configProp + "'"); } else { LOG.info("Use original config '" + this.configPropOrig + "'"); configProp = this.configPropOrig; } initParameters = setConfig(initParameters, configProp); super.setInitParameters(initParameters); super.afterPropertiesSet(); } return super.handleRequestInternal(request, response); } }