auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); if (feedbackSession == null) { throw new EntityNotFoundException(new EntityDoesNotExistException("Feedback session not found")); <START> } <END> verifySessionOpenExceptForModeration(feedbackSession); verifyNotPreview(); Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case STUDENT_SUBMISSION: StudentAttributes studentAttributes = getStudentOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForStudentFeedbackSubmission(studentAttributes, feedbackSession); break; case INSTRUCTOR_SUBMISSION: InstructorAttributes instructorAttributes = getInstructorOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForInstructorFeedbackSubmission(instructorAttributes, feedbackSession); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }</code><technical_language>This entire PR screams "DRY". abstract this entire method (get feedback session, throw EntityNotFoundException if found) parent Action class. While it, if employ method for course, instructor, and/or student objects</technical_language>

Target:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes feedbackSession = getNonNullFeedbackSession(feedbackSessionName, courseId); verifySessionOpenExceptForModeration(feedbackSession); verifyNotPreview(); Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case STUDENT_SUBMISSION: StudentAttributes studentAttributes = getStudentOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForStudentFeedbackSubmission(studentAttributes, feedbackSession); break; case INSTRUCTOR_SUBMISSION: InstructorAttributes instructorAttributes = getInstructorOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForInstructorFeedbackSubmission(instructorAttributes, feedbackSession); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }
Source:
<code><START> private boolean isSuspiciousClassInstantiation(ExpressionTree callee) { <END> if (callee.is(Tree.Kind.NAMESPACE_NAME)) { NamespaceNameTree classNameTree = (NamespaceNameTree) callee; QualifiedName className = getFullyQualifiedName(classNameTree); return SUSPICIOUS_CLASS_INSTANTIATIONS.stream().anyMatch(className::equals); } return false; }</code><technical_language>I put this method isGlobalGetOptMethod(), group methods in logical call order</technical_language>

Target:
private boolean isSuspiciousClassInstantiation(ExpressionTree callee) { if (callee.is(Tree.Kind.NAMESPACE_NAME)) { QualifiedName className = getFullyQualifiedName((NamespaceNameTree) callee); return SUSPICIOUS_CLASS_INSTANTIATIONS.stream().anyMatch(className::equals); } return false; }
Source:
<code>public synchronized BigtableClient getDataClient() throws IOException { if (this.client == null) { Channel generalChannel = createChannel(options.getDataHost(), options.getChannelCount()); <START> Channel scanChannel = createChannel(options.getDataHost(), 1); <END> this.client = new BigtableGrpcClient(generalChannel, scanChannel, batchPool, options.getRetryOptions()); } return client; }</code><technical_language>for read, 1 channel is enough</technical_language>

Target:
public synchronized BigtableClient getDataClient() throws IOException { if (this.client == null) { Channel writeChannel = createChannel(options.getDataHost(), options.getChannelCount()); Channel readChannel = createChannel(options.getDataHost(), 1); RetryOptions retryOptions = options.getRetryOptions(); this.client = new BigtableGrpcClient(readChannel, writeChannel, batchPool, retryOptions); } return client; }
Source:
<code>public int place(World world, BlockPos pos, @Nonnull FluidStack fluidStack, boolean doPlace) { if (fluidStack.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doPlace) { <START> if (!world.isRemote) <END> { IBlockState destBlockState = world.getBlockState(pos); Material destMaterial = destBlockState.getMaterial(); boolean isDestNonSolid = !destMaterial.isSolid(); boolean isDestReplaceable = destBlockState.getBlock().isReplaceable(world, pos); if ((isDestNonSolid || isDestReplaceable) && !destMaterial.isLiquid()) { world.destroyBlock(pos, true); } } world.setBlockState(pos, this.getDefaultState(), 11); } return Fluid.BUCKET_VOLUME; }</code><technical_language>This block of code is repeated times - move a method called places</technical_language>

Target:
public int place(World world, BlockPos pos, @Nonnull FluidStack fluidStack, boolean doPlace) { if (fluidStack.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doPlace) { FluidUtil.destroyBlockOnFluidPlacement(world, pos); world.setBlockState(pos, this.getDefaultState(), 11); } return Fluid.BUCKET_VOLUME; }
Source:
<code>public ItemFile getItemFile(final ZipEntry zipEntry, final ZipFile zipFile) throws IllegalArgumentException { if (null == zipEntry) { throw new IllegalArgumentException("A null ZIP entry was passed."); } if (null == zipFile) { throw new IllegalArgumentException("A null ZIP file was passed."); } return new ItemFile() { private ZipEntry itemEntry = zipEntry; private Image image = null; public Object getItem() throws Exception { if (null == image) { <START> InputStream in = new BufferedInputStream(zipFile <END> .getInputStream(itemEntry), (int) itemEntry .getSize()); byte[] buffer = new byte[(int) itemEntry.getSize()]; in.read(buffer); int index = (int) itemEntry.getSize() - 10; while (itemEntry.getSize() > index) { if (0 != buffer[index]) { break; } index++; } if (itemEntry.getSize() <= index) { throw new IOException( "Error reading " + itemEntry.getName() + "\nYou may want to unzip " + zipFile.getName()); } image = Toolkit.getDefaultToolkit().createImage(buffer); } return ImageUtil.getScaledImage(image, 84, 72); } }; }</code><technical_language>LGTM (and right), close this input stream of call succeeds fails</technical_language>

Target:
public ItemFile getItemFile(final ZipEntry zipEntry, final ZipFile zipFile) throws IllegalArgumentException { if (null == zipEntry) { throw new IllegalArgumentException("A null ZIP entry was passed."); } if (null == zipFile) { throw new IllegalArgumentException("A null ZIP file was passed."); } return new ItemFile() { private ZipEntry itemEntry = zipEntry; private Image image = null; public Object getItem() throws Exception { if (null == image) { try (InputStream in = new BufferedInputStream( zipFile.getInputStream(itemEntry), (int) itemEntry.getSize())) { byte[] buffer = new byte[(int) itemEntry.getSize()]; in.read(buffer); int index = (int) itemEntry.getSize() - 10; while (itemEntry.getSize() > index) { if (0 != buffer[index]) { break; } index++; } if (itemEntry.getSize() <= index) { throw new IOException( "Error reading " + itemEntry.getName() + "\nYou may want to unzip " + zipFile.getName()); } image = Toolkit.getDefaultToolkit().createImage(buffer); } } return ImageUtil.getScaledImage(image, 84, 72); } }; }
Source:
<code>private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); <START> for (ProfileEntry profileEntry : source != null ? new ArrayList<ProfileEntry>((ArrayList<ProfileEntry>) source) <END> : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; }</code><technical_language>I understand need create a new ArrayList for a collection is coming a query - is necessarily else. Also, cast coming backend ArrayList? This means committing a specific implementation. I a cast Collection is more appropriate. If important for end result in specifically ArrayList (and other kind of collection), I create a new ArrayList, cast result backend Collection</technical_language>

Target:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : source != null ? (Collection<ProfileEntry>) source : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; }
Source:
<code>public boolean isEnabled() { <START> return getRepositories().length == 1; <END> }</code><technical_language>commit action is enabled I select a non-project resource. method getRepositories work for projects</technical_language>

Target:
public boolean isEnabled() { IProject[] projects = getProjectsForSelectedResources(); return getRepositoriesFor(projects).length == 1; }
Source:
<code>public APIResult submitAndScheduleExtensionJob(String extensionName, String jobName, String configPath, String doAsUser) { <START> InputStream configStream = FalconClient.getServletInputStream(configPath); <END> String packagePath = ExtensionStore.get().getMetaStore().getDetail(extensionName).getLocation(); try { List<Entity> entities = ExtensionHandler.loadAndPrepare(extensionName, jobName, configStream, packagePath); return localExtensionManager.submitAndSchedulableExtensionJob(extensionName, jobName, configStream, entities); } catch (FalconException | IOException e) { throw new FalconCLIException("Failed in submitting extension job " + jobName); } }</code><technical_language>avoid duplication of code submit submitAndSchedule</technical_language>

Target:
public APIResult submitAndScheduleExtensionJob(String extensionName, String jobName, String configPath, String doAsUser) { InputStream configStream = getServletInputStream(configPath); try { List<Entity> entities = getEntities(extensionName, jobName, configStream); return localExtensionManager.submitAndSchedulableExtensionJob(extensionName, jobName, configStream, entities); } catch (FalconException | IOException e) { throw new FalconCLIException("Failed in submitting extension job " + jobName); } }
Source:
<code><START> public static void setup() { <END> cache = mock(AttributeTypeCache.class); type = mock(AttributeType.class); types.add(CoreAttributeTypes.Active); types.add(CoreAttributeTypes.FavoriteBranch); }</code><technical_language>mockito supports a setup mocks. Mockito.initMocks(this)..</technical_language>

Target:
public void setup() { MockitoAnnotations.initMocks(this); types.add(CoreAttributeTypes.Active); types.add(CoreAttributeTypes.FavoriteBranch); }
Source:
<code>public static List<Property> getNestedPath(org.eclipse.uml2.uml.Class clazz, View view) { List<Property> propertyPath = new ArrayList<>(); View currentView = ViewUtil.getContainerView(view); while (currentView <START> != null <END> && !clazz.equals(currentView.getElement())) { EObject property = currentView.getElement(); if (property instanceof Property) { propertyPath.add((Property) property); } currentView = ViewUtil.getContainerView(currentView); } Collections.reverse(propertyPath); return propertyPath; }</code><technical_language>want amend version this correction is part of service release</technical_language>

Target:
public static List<Property> getNestedPath(org.eclipse.uml2.uml.Class clazz, View view) { List<Property> propertyPath = new ArrayList<>(); View currentView = ViewUtil.getContainerView(view); boolean stop = false; while (!stop && currentView != null) { EObject property = currentView.getElement(); if (property instanceof Property) { if (((Property) property).getType() == clazz) { stop = true; } else { propertyPath.add((Property) property); } } else { if (clazz.equals(currentView.getElement())) { stop = true; } } currentView = ViewUtil.getContainerView(currentView); } Collections.reverse(propertyPath); return propertyPath; }
Source:
<code>@Override protected void setUp() throws Exception { super.setUp(); File file = File.createTempFile("integrity", "dat"); file.deleteOnExit(); expBuf = new ByteBufferExpander(1024, ByteOrder.BIG_ENDIAN); FileIOFactory factory = new RandomAccessFileIOFactory(); fileInput = new FileInput( factory.create(file), expBuf ); ByteBuffer buf = ByteBuffer.allocate(1024); ThreadLocalRandom curr = ThreadLocalRandom.current(); for (int i = 0; i < 1024; i+=16) { buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.position(i); if (oldCrcAlgo) <START> buf.putInt(PureJavaCrc32.calcCrc32(buf, 12)); <END> else buf.putInt(U.calcCrc(buf, 12)); } buf.rewind(); fileInput.io().writeFully(buf); fileInput.io().force(); }</code><technical_language>replace PureJavaCrc32 new method here</technical_language>

Target:
@Override protected void setUp() throws Exception { super.setUp(); File file = File.createTempFile("integrity", "dat"); file.deleteOnExit(); expBuf = new ByteBufferExpander(1024, ByteOrder.BIG_ENDIAN); FileIOFactory factory = new RandomAccessFileIOFactory(); fileInput = new SimpleFileInput( factory.create(file), expBuf ); ByteBuffer buf = ByteBuffer.allocate(1024); ThreadLocalRandom curr = ThreadLocalRandom.current(); for (int i = 0; i < 1024; i+=16) { buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.position(i); buf.putInt(FastCrc.calcCrc(buf, 12)); } buf.rewind(); fileInput.io().writeFully(buf); fileInput.io().force(); }
Source:
<code>void increment(int imp) { <START> imp = imp < 0 ? 0 : imp > NUM_IMPORTANCES -1 ? NUM_IMPORTANCES - 1 : imp; <END> mCount[imp] ++; }</code><technical_language>Fix LGTM I suspect this bug happened this range restriction is hard read in place. I suggest: if (imp < 0) { imp = 0; } if (imp > mCount.length - 1) { imp = mCount.length - 1; } Or: imp = Math.max(0, Math.min(imp, mCount.length - 1)); Also, array length is more robust NUM_IMPORTANCES</technical_language>

Target:
void increment(int imp) { imp = Math.max(0, Math.min(imp, mCount.length - 1)); mCount[imp]++; }
Source:
<code>public void runFlakyTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("flaky-test"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("flaky.FlakyClass"); options.setOption("generated_limit", "1000"); options.setOption("output_limit", "1000"); options.setOption("flaky-test-behavior", "OUTPUT"); CoverageChecker coverageChecker = new CoverageChecker( options, "flaky.FlakyClass.getTwo() include", "flaky.FlakyClass.getThree() include", "flaky.FlakyClass.flakyDefaultHashCode() ignore", "flaky.FlakyClass.multiply(int, int) include"); List<String> expectedFlakyMethodsInOrder = new ArrayList<>(); <START> expectedFlakyMethodsInOrder.add("flaky.FlakyClass.flakyDefaultHashCode(flaky.FlakyClass)"); <END> generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.DONT_CARE, coverageChecker, expectedFlakyMethodsInOrder); }</code><technical_language>This change right me. method flakyDefaultHashCode takes arguments. else Randoop require explicitly giving receiver type. I receiver type listed in this output</technical_language>

Target:
public void runFlakyTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("flaky-test"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("flaky.FlakyClass"); options.setOption("generated_limit", "1000"); options.setOption("output_limit", "1000"); options.setOption("flaky-test-behavior", "OUTPUT"); CoverageChecker coverageChecker = new CoverageChecker( options, "flaky.FlakyClass.getTwo() include", "flaky.FlakyClass.getThree() include", "flaky.FlakyClass.flakyDefaultHashCode() ignore", "flaky.FlakyClass.multiply(int, int) include"); List<String> expectedFlakyMethodsInOrder = new ArrayList<>(); expectedFlakyMethodsInOrder.add("flaky.FlakyClass.flakyDefaultHashCode()"); generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.DONT_CARE, coverageChecker, expectedFlakyMethodsInOrder); }
Source:
<code>private void setupGridView() { final RecyclerView grid = (RecyclerView)findViewById(R.id.wifi_direct_gridview_buttons); grid.setHasFixedSize(true); StaggeredGridLayoutManager gridView = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); grid.setLayoutManager(gridView); grid.setItemAnimator(null); grid.setAdapter(adapter); <START> grid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { <END> @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { grid.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { grid.getViewTreeObserver().removeOnGlobalLayoutListener(this); } grid.requestLayout(); adapter.notifyDataSetChanged(); configUI(); } }); }</code><technical_language>positive, I this listener is needed. @ctsims reason this here? give context is needed home screen adapter? removed too</technical_language>

Target:
private void setupGridView() { final RecyclerView grid = (RecyclerView)findViewById(R.id.wifi_direct_gridview_buttons); grid.setHasFixedSize(true); StaggeredGridLayoutManager gridView = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); grid.setLayoutManager(gridView); grid.setItemAnimator(null); grid.setAdapter(adapter); grid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { grid.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { grid.getViewTreeObserver().removeOnGlobalLayoutListener(this); } grid.requestLayout(); adapter.notifyDataSetChanged(); } }); }
Source:
<code>public int hashCode() { <START> final int prime = 31; <END> int result = 1; result = prime * result + ((backendHintSettings == null) ? 0 : backendHintSettings.hashCode()); result = prime * result + ((queryBackendFactory == null) ? 0 : queryBackendFactory.hashCode()); return result; }</code><technical_language>Objects.hashCode() instead (available Java 7). this kind of code more compact readable</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Objects.hashCode(backendHintSettings); result = prime * result + Objects.hashCode(queryBackendFactory); return result; }
Source:
<code>Optional<ItemDefinition> findItemDefinitionParent(final DataType dataType) { final Optional<ItemDefinition> itemDefinitionParent = Optional.ofNullable(itemDefinitionStore.get(dataType.getParentUUID())); if (itemDefinitionParent.isPresent()) { final ItemDefinition parent = itemDefinitionParent.get(); if (parent.getTypeRef() == null) { return Optional.of(parent); } else { for (final ItemDefinition itemDefinition : itemDefinitions()) { <START> if (itemDefinition.getName().getValue().equals(parent.getTypeRef().getLocalPart())) { <END> return Optional.of(itemDefinition); } } } } return Optional.empty(); }</code><technical_language>Please Objects.equals</technical_language>

Target:
Optional<ItemDefinition> findItemDefinitionParent(final DataType dataType) { final Optional<ItemDefinition> itemDefinitionParent = Optional.ofNullable(itemDefinitionStore.get(dataType.getParentUUID())); if (itemDefinitionParent.isPresent()) { final ItemDefinition parent = itemDefinitionParent.get(); if (parent.getTypeRef() == null) { return Optional.of(parent); } else { for (final ItemDefinition itemDefinition : itemDefinitions()) { if (Objects.equals(itemDefinition.getName().getValue(), parent.getTypeRef().getLocalPart())) { return Optional.of(itemDefinition); } } } } return Optional.empty(); }
Source:
<code>public String toString() { <START> return String.format("AmqpBrokerConfig [host=%s, port=%d, username=%s, password=%s, virtualHost=%s, groupId=%s, durable=%s, consumerThreadPoolSize=%s]", <END> host, port, username, password, virtualHost, groupId, durable, consumerThreadPoolSize); }</code><technical_language>Again, logging of passwords want</technical_language>

Target:
public String toString() { return String.format("AmqpBrokerConfig [host=%s, port=%d, username=%s, password=xxx, virtualHost=%s, groupId=%s, durable=%s, consumerThreadPoolSize=%s]", host, port, username, virtualHost, groupId, durable, consumerThreadPoolSize); }
Source:
<code>public static void verifyAggregations( List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); Preconditions.checkArgument(aggFactories.size() > 0, "Must have at least one AggregatorFactory"); if (postAggs != null && !postAggs.isEmpty()) { Set<String> combinedAggNames = Sets.newHashSet( Lists.transform( aggFactories, new Function<AggregatorFactory, String>() { @Override public String apply(@Nullable AggregatorFactory input) { return input.getName(); } } ) ); for (PostAggregator postAgg : postAggs) { Set<String> dependencies = postAgg.getDependentFields(); Set<String> missing = Sets.difference(dependencies, combinedAggNames); Preconditions.checkArgument( missing.isEmpty(), <START> String.format("Missing fields [%s] for postAggregator [%s]", Joiner.on(",").join(missing), postAgg.getName()) <END> ); combinedAggNames.add(postAgg.getName()); } } }</code><technical_language>toString() Set<> List<> automatically output comma-delimited stuff, need for Joiner</technical_language>

Target:
public static void verifyAggregations( List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); Preconditions.checkArgument(aggFactories.size() > 0, "Must have at least one AggregatorFactory"); if (postAggs != null && !postAggs.isEmpty()) { Set<String> combinedAggNames = Sets.newHashSet( Lists.transform( aggFactories, new Function<AggregatorFactory, String>() { @Override public String apply(@Nullable AggregatorFactory input) { return input.getName(); } } ) ); for (PostAggregator postAgg : postAggs) { Set<String> dependencies = postAgg.getDependentFields(); Set<String> missing = Sets.difference(dependencies, combinedAggNames); Preconditions.checkArgument( missing.isEmpty(), "Missing fields [%s] for postAggregator [%s]", missing, postAgg.getName() ); combinedAggNames.add(postAgg.getName()); } } }
Source:
<code>private void loadMedia() { <START> MediaFactory mediaFactory = new MediaFactory(); <END> GetMediasUseCase getMediasUseCase = mediaFactory.getGetMediasUseCase(); getMediasUseCase.execute(new GetMediasUseCase.Callback() { @Override public void onSuccess(List<Media> medias) { mView.showMediaItems(medias); } }); }</code><technical_language>A presenter invoke factory retrieve case, case passed constructor</technical_language>

Target:
private void loadMedia() { mGetMediasUseCase.execute(new GetMediasUseCase.Callback() { @Override public void onSuccess(List<Media> medias) { mView.showMediaItems(medias); } }); }
Source:
<code>private void initializeSSLContext(SSLChannelMode preferredChannelMode) throws NoSuchAlgorithmException, KeyManagementException { switch (preferredChannelMode) { case Default: try { <START> if (!openSSLProviderRegistered) { <END> OpenSSLProvider.register(); openSSLProviderRegistered = true; } java.util.logging.Logger logger = java.util.logging.Logger.getLogger( SSL.class.getName()); logger.setLevel(Level.WARNING); ctx = SSLContext.getInstance("openssl.TLS"); ctx.init(null, null, null); logger.setLevel(Level.INFO); channelMode = SSLChannelMode.OpenSSL; } catch (LinkageError | NoSuchAlgorithmException | RuntimeException e) { LOG.debug("Failed to load OpenSSL. Falling back to the JSSE default.", e); ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; } break; case OpenSSL: if (!openSSLProviderRegistered) { OpenSSLProvider.register(); openSSLProviderRegistered = true; } java.util.logging.Logger logger = java.util.logging.Logger.getLogger( SSL.class.getName()); logger.setLevel(Level.WARNING); ctx = SSLContext.getInstance("openssl.TLS"); ctx.init(null, null, null); logger.setLevel(Level.INFO); channelMode = SSLChannelMode.OpenSSL; break; case Default_JSSE: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; break; case Default_JSSE_with_GCM: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE_with_GCM; break; default: throw new NoSuchAlgorithmException("Unknown channel mode: " + preferredChannelMode); } }</code><technical_language>move code try-catch a new method resued for case openSSL well</technical_language>

Target:
private void initializeSSLContext(SSLChannelMode preferredChannelMode) throws NoSuchAlgorithmException, KeyManagementException, IOException { LOG.debug("Initializing SSL Context to channel mode {}", preferredChannelMode); switch (preferredChannelMode) { case Default: try { bindToOpenSSLProvider(); channelMode = SSLChannelMode.OpenSSL; } catch (LinkageError | NoSuchAlgorithmException | RuntimeException e) { LOG.debug("Failed to load OpenSSL. Falling back to the JSSE default.", e); ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; } break; case OpenSSL: bindToOpenSSLProvider(); channelMode = SSLChannelMode.OpenSSL; break; case Default_JSSE: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; break; case Default_JSSE_with_GCM: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE_with_GCM; break; default: throw new IOException("Unknown channel mode: " + preferredChannelMode); } }
Source:
<code>public CompletableFuture<Void> deleteAsync(K key) { writeMetrics.numDeletes.inc(); long startNs = System.nanoTime(); Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); return rwTable.deleteAsync(key).handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to delete the record for " + key, e); } else if (!isWriteAround) { cache.delete(key); <START> writeMetrics.deleteNs.update(System.nanoTime() - startNs); <END> } return result; }); }</code><technical_language>updating timer metric if a writeAround cache. if do - metrics updated measuring time for "delete" operation right</technical_language>

Target:
public CompletableFuture<Void> deleteAsync(K key) { writeMetrics.numDeletes.inc(); long startNs = System.nanoTime(); Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); return rwTable.deleteAsync(key).handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to delete the record for " + key, e); } else if (!isWriteAround) { cache.delete(key); } writeMetrics.deleteNs.update(System.nanoTime() - startNs); return result; }); }
Source:
<code>String basicToString(int tab) { StringBuilder sb = new StringBuilder("\n"); for (int i = tab; --i >= 0;) { sb.append("\t"); } sb.append("--- Method Scope ---"); sb.append("\t"); sb.append("locals:"); for (int i = 0; i < localIndex; i++) { sb.append("\t"); <START> sb.append(locals[i].toString()); <END> } sb.append("startIndex = "); sb.append(startIndex); sb.append("isConstructorCall = "); sb.append(isConstructorCall); sb.append("initializedField = "); sb.append(initializedField); sb.append("lastVisibleFieldID = "); sb.append(lastVisibleFieldID); sb.append("referenceContext = "); sb.append(referenceContext); return sb.toString(); }</code><technical_language>toString() is required</technical_language>

Target:
String basicToString(int tab) { StringBuilder sb = new StringBuilder("\n"); for (int i = tab; --i >= 0;) { sb.append("\t"); } sb.append("--- Method Scope ---"); sb.append("\t"); sb.append("locals:"); for (int i = 0; i < localIndex; i++) { sb.append("\t"); sb.append(locals[i]); } sb.append("startIndex = "); sb.append(startIndex); sb.append("isConstructorCall = "); sb.append(isConstructorCall); sb.append("initializedField = "); sb.append(initializedField); sb.append("lastVisibleFieldID = "); sb.append(lastVisibleFieldID); sb.append("referenceContext = "); sb.append(referenceContext); return sb.toString(); }
Source:
<code>public void testChildrenOffsets() { <START> int numBuildRects = 10; <END> int degree = 8; Random random = new Random(122); int firstParentIndex = 2 * degree * ENVELOPE_SIZE; int secondParentIndex = firstParentIndex + ENVELOPE_SIZE; int grandparentIndex = 3 * degree * ENVELOPE_SIZE; List<Rectangle> buildRects = makeRectangles(random, numBuildRects); Flatbush<Rectangle> rtree = new Flatbush<>(buildRects.toArray(new Rectangle[] {}), degree); assertEquals(rtree.getHeight(), 3); assertEquals(rtree.getChildrenOffset(firstParentIndex, 1), 0); assertEquals(rtree.getChildrenOffset(secondParentIndex, 1), degree * ENVELOPE_SIZE); assertEquals(rtree.getChildrenOffset(grandparentIndex, 2), 2 * degree * ENVELOPE_SIZE); }</code><technical_language>numBuildRects -> numRectanges</technical_language>

Target:
public void testChildrenOffsets() { int numRectangles = 10; int degree = 8; Random random = new Random(122); int firstParentIndex = 2 * degree * ENVELOPE_SIZE; int secondParentIndex = firstParentIndex + ENVELOPE_SIZE; int grandparentIndex = 3 * degree * ENVELOPE_SIZE; List<Rectangle> rectangles = makeRectangles(random, numRectangles); Flatbush<Rectangle> rtree = new Flatbush<>(rectangles.toArray(new Rectangle[] {}), degree); assertEquals(rtree.getHeight(), 3); assertEquals(rtree.getChildrenOffset(firstParentIndex, 1), 0); assertEquals(rtree.getChildrenOffset(secondParentIndex, 1), degree * ENVELOPE_SIZE); assertEquals(rtree.getChildrenOffset(grandparentIndex, 2), 2 * degree * ENVELOPE_SIZE); }
Source:
<code>private void setStormHostConf() { try { String host_addr = InetAddress.getLocalHost().getHostAddress(); LOG.info("Storm master host:"+host_addr); _storm_conf.put(Config.NIMBUS_HOST, host_addr); <START> } catch (UnknownHostException ex) { <END> } }</code><technical_language>good log exception instead of ignoring it. If networking is set correctly I that</technical_language>

Target:
private void setStormHostConf() { try { String host_addr = InetAddress.getLocalHost().getHostAddress(); LOG.info("Storm master host:"+host_addr); _storm_conf.put(Config.NIMBUS_HOST, host_addr); } catch (UnknownHostException ex) { LOG.warn("Failed to get IP address of local host"); } }
Source:
<code>private void writeToFile(File file, String body) throws IOException { <START> FileOutputStream fos = new FileOutputStream(file); <END> BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8)); bw.write(body); } finally { if (bw != null) { bw.close(); } fos.close(); } }</code><technical_language>is try(FileOutputStream ....) {}</technical_language>

Target:
private static void writeToFile(File file, String body) throws IOException { FileOutputStream fos = new FileOutputStream(file); BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8)); bw.write(body); } finally { if (bw != null) { bw.close(); } fos.close(); } }
Source:
<code>public void generateCpuQuota(long elapsedSeconds) { <START> synchronized (getRoot()) { <END> if (elapsedSeconds > 0) { internalGenerateCpuQuota(elapsedSeconds); } } }</code><technical_language>here, purpose of getRoot()</technical_language>

Target:
public void generateCpuQuota(long elapsedSeconds) { synchronized (super.root) { if (elapsedSeconds > 0) { internalGenerateCpuQuota(elapsedSeconds); } } }
Source:
<code>public Credentials getHttpCredentials() { <START> return new UsernamePasswordCredentials(gerritHttpUserName, Secret.toString(gerritHttpPassword)); <END> }</code><technical_language>Similarly getGerritHttpPassword() here</technical_language>

Target:
public Credentials getHttpCredentials() { return new UsernamePasswordCredentials(gerritHttpUserName, getGerritHttpPassword()); }
Source:
<code>public JnKeysScalarEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) { super(args); this.ctx = ctx; sp1 = (SequencePointable) SequencePointable.FACTORY.createPointable(); sp2 = (SequencePointable) SequencePointable.FACTORY.createPointable(); <START> pointables = new ArrayList<>(); <END> sb = new SequenceBuilder(); abvs = new ArrayBackedValueStorage(); }</code><technical_language>reset pointables for evaluate call</technical_language>

Target:
public JnKeysScalarEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) { super(args); this.ctx = ctx; sp1 = (SequencePointable) SequencePointable.FACTORY.createPointable(); sp2 = (SequencePointable) SequencePointable.FACTORY.createPointable(); sb = new SequenceBuilder(); abvs = new ArrayBackedValueStorage(); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; <START> final ViewerCell<E> other = (ViewerCell<E>) obj; <END> if (columnIndex != other.columnIndex) return false; if (row == null) { if (other.row != null) return false; } else if (!row.equals(other.row)) return false; return true; }</code><technical_language>I get a warning for this cast Object</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") final ViewerCell<E> other = (ViewerCell<E>) obj; if (columnIndex != other.columnIndex) return false; if (row == null) { if (other.row != null) return false; } else if (!row.equals(other.row)) return false; return true; }
Source:
<code>protected void executeCommand() { VM vm = getVm(); if (vm.getVdsGroupId().equals(getParameters().getClusterId())) { setSucceeded(true); return; } List<Network> networks = getNetworkDAO().getAllForCluster(getParameters().getClusterId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getParameters().getVmId()); for (final VmNic iface : interfaces) { if (iface.getVnicProfileId() != null) { final Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId()); Network net = LinqUtils.firstOrNull(networks, new Predicate<Network>() { @Override public boolean eval(Network n) { return ObjectUtils.equals(n.getId(), network.getId()); } }); if (net == null) { iface.setVnicProfileId(null); getVmNicDao().update(iface); } } } if (vm.getDedicatedVmForVds() != null) { vm.setDedicatedVmForVds(null); dedicatedHostWasCleared = true; } vm.setCpuProfileId(null); vm.setVdsGroupId(getParameters().getClusterId()); DbFacade.getInstance().getVmStaticDao().update(vm.getStaticData()); List<AffinityGroup> allAffinityGroupsByVmId = DbFacade.getInstance().getAffinityGroupDao().getAllAffinityGroupsByVmId(vm.getId()); if (!allAffinityGroupsByVmId.isEmpty()) { StringBuilder sb = new StringBuilder(); for (AffinityGroup affinityGroup : allAffinityGroupsByVmId) { sb.append(affinityGroup.getName() + " "); } <START> log.info("Due to cluster change, removing VM from associated affinity group(s): {}", sb.toString()); <END> DbFacade.getInstance().getAffinityGroupDao().removeVmFromAffinityGroups(vm.getId()); } setSucceeded(true); }</code><technical_language>toString</technical_language>

Target:
protected void executeCommand() { VM vm = getVm(); if (vm.getVdsGroupId().equals(getParameters().getClusterId())) { setSucceeded(true); return; } List<Network> networks = getNetworkDAO().getAllForCluster(getParameters().getClusterId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getParameters().getVmId()); for (final VmNic iface : interfaces) { if (iface.getVnicProfileId() != null) { final Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId()); Network net = LinqUtils.firstOrNull(networks, new Predicate<Network>() { @Override public boolean eval(Network n) { return ObjectUtils.equals(n.getId(), network.getId()); } }); if (net == null) { iface.setVnicProfileId(null); getVmNicDao().update(iface); } } } if (vm.getDedicatedVmForVds() != null) { vm.setDedicatedVmForVds(null); dedicatedHostWasCleared = true; } vm.setCpuProfileId(null); vm.setVdsGroupId(getParameters().getClusterId()); DbFacade.getInstance().getVmStaticDao().update(vm.getStaticData()); List<AffinityGroup> allAffinityGroupsByVmId = DbFacade.getInstance().getAffinityGroupDao().getAllAffinityGroupsByVmId(vm.getId()); if (!allAffinityGroupsByVmId.isEmpty()) { StringBuilder sb = new StringBuilder(); for (AffinityGroup affinityGroup : allAffinityGroupsByVmId) { sb.append(affinityGroup.getName() + " "); } log.info("Due to cluster change, removing VM from associated affinity group(s): {}", sb); DbFacade.getInstance().getAffinityGroupDao().removeVmFromAffinityGroups(vm.getId()); } setSucceeded(true); }
Source:
<code>public void click(String title, Constants.InvokeSource source) { SuggestedEditStats stats = null; if (source == Constants.InvokeSource.EDIT_FEED_TITLE_DESC) { stats = statsCollection.addDescriptionStats; } else if (source == Constants.InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC) { stats = statsCollection.translateDescriptionStats; } <START> stats.clicks++; <END> if (!uniqueTitles.contains(title)) { uniqueTitles.add(title); final int maxItems = 100; if (uniqueTitles.size() > maxItems) { uniqueTitles.remove(0); } stats.suggestionsClicked++; } }</code><technical_language>App crash entering DescriptionEditActivity article</technical_language>

Target:
public void click(String title, Constants.InvokeSource source) { SuggestedEditStats stats; if (source == Constants.InvokeSource.EDIT_FEED_TITLE_DESC) { stats = statsCollection.addDescriptionStats; } else if (source == Constants.InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC) { stats = statsCollection.translateDescriptionStats; } else { return; } stats.clicks++; if (!uniqueTitles.contains(title)) { uniqueTitles.add(title); final int maxItems = 100; if (uniqueTitles.size() > maxItems) { uniqueTitles.remove(0); } stats.suggestionsClicked++; } }
Source:
<code>public void testPopulate() throws Exception { setupParentExpectations(); setUriInfo(setUpBasicUriExpectations()); setUpGetEntityExpectationsAllContent(1,false); resource.setParent(bricksResourceMock); control.replay(); <START> verifyModel(resource.get(), 0); <END> }</code><technical_language>want verify AdvancedDetails here</technical_language>

Target:
public void testPopulate() throws Exception { setupParentExpectations(); setUriInfo(setUpBasicUriExpectations()); setUpGetEntityExpectationsAllContent(1,false); resource.setParent(bricksResourceMock); control.replay(); verifyModelWithDetails(resource.get(), 0); }
Source:
<code><START> private void logMeasureByResource(Resource resource, Measure measure) { <END> if (LOG.isDebugEnabled()) { Measure alreadySaved = MEASURES_BY_RESOURCE.get(resource); if (alreadySaved == null) { MEASURES_BY_RESOURCE.put(resource, measure); } else { LOG.debug("Measure already saved for resource {}", measure, resource); } } }</code><technical_language>![MAJOR](<LINK_0> "logMeasureByResource" a "static" method. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private static void logMeasureByResource(Resource resource, Measure measure) { if (LOG.isDebugEnabled()) { Measure alreadySaved = MEASURES_BY_RESOURCE.get(resource); if (alreadySaved == null) { MEASURES_BY_RESOURCE.put(resource, measure); } else { LOG.debug("Measure already saved for resource {}", measure, resource); } } }
Source:
<code>public synchronized boolean trySetBytes(long bytes) { checkState(!closed, "SimpleLocalMemoryContext is already closed"); long delta = bytes - usedBytes; <START> if (parentMemoryContext.tryUpdateBytes(delta)) { <END> usedBytes += delta; return true; } return false; }</code><technical_language>bytes negative</technical_language>

Target:
public synchronized boolean trySetBytes(long bytes) { checkState(!closed, "SimpleLocalMemoryContext is already closed"); checkArgument(bytes >= 0, "bytes cannot be negative"); long delta = bytes - usedBytes; if (parentMemoryContext.tryUpdateBytes(delta)) { usedBytes = bytes; return true; } return false; }
Source:
<code>void errorSourceOnSessionLock() { when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.error(new AmqpException(false, "some error occurred.", null))); StepVerifier.create(sessionReceiver.renewSessionLock(SESSION_ID)) <START> .verifyErrorMatches(throwable -> { <END> Assertions.assertTrue(throwable instanceof ServiceBusAmqpException); final ServiceBusErrorSource actual = ((ServiceBusAmqpException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); return true; }); }</code><technical_language>verifyErrorSatisfies is correct one. other ones</technical_language>

Target:
void errorSourceOnSessionLock() { when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.error(new AmqpException(false, "some error occurred.", null))); StepVerifier.create(sessionReceiver.renewSessionLock(SESSION_ID)) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusAmqpException); final ServiceBusErrorSource actual = ((ServiceBusAmqpException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); }); }
Source:
<code>public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String branchKey = request.mandatoryParam(PARAM_BRANCH); <START> if (branchKey.isEmpty()) { <END> branchKey = null; } try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = checkFoundWithOptional(dbClient.componentDao().selectByKey(dbSession, projectKey), "Project key '%s' not found", projectKey); checkPermission(project); BranchDto branch = checkFoundWithOptional( dbClient.branchDao().selectByKey(dbSession, project.uuid(), BranchKeyType.BRANCH, branchKey), "Branch '%s' not found for project '%s'", branchKey, projectKey); if (branch.isMain()) { throw new IllegalArgumentException("Only non-main branches can be deleted"); } componentCleanerService.delete(dbSession, project); response.noContent(); } }</code><technical_language>This happen, request.mandatoryParam(PARAM_BRANCH)</technical_language>

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String branchKey = request.mandatoryParam(PARAM_BRANCH); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getRootComponentByUuidOrKey(dbSession, null, projectKey); checkPermission(project); BranchDto branch = checkFoundWithOptional( dbClient.branchDao().selectByKey(dbSession, project.uuid(), BranchKeyType.BRANCH, branchKey), "Branch '%s' not found for project '%s'", branchKey, projectKey); if (branch.isMain()) { throw new IllegalArgumentException("Only non-main branches can be deleted"); } ComponentDto branchComponent = componentFinder.getByKeyAndBranch(dbSession, projectKey, branchKey); componentCleanerService.deleteBranch(dbSession, branchComponent); response.noContent(); } }
Source:
<code>public Host getCurrentSite(final HttpServletRequest req, final User user) { try { final HttpSession session = req.getSession(); String hostId = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); <START> Host host = null; <END> if (hostId != null) { host = hostAPI.find(hostId, user, false); } return host; } catch (DotDataException|DotSecurityException e) { throw new DotRuntimeException(e); } }</code><technical_language>reduce (null != hostId)?hostAPI.find(hostId, user, false):null;</technical_language>

Target:
public Host getCurrentSite(final HttpServletRequest req, final User user) { try { final HttpSession session = req.getSession(); String hostId = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); return (null != hostId) ? hostAPI.find(hostId, user, false) : null; } catch (DotDataException|DotSecurityException e) { throw new DotRuntimeException(e); } }
Source:
<code>public ArticleMetadata get(Site site, RequestedDoiVersion id, ArticlePointer articlePointer) throws IOException { try { Map<String, Object> ingestionMetadata = (Map<String, Object>) articleApi.requestObject( articlePointer.asApiAddress().build(), Map.class); Map<String, ?> itemTable = articleService.getItemTable(articlePointer); ApiAddress relationshipsApiAddress = ApiAddress.builder("articles") .embedDoi(articlePointer.getDoi()).addToken("relationships").build(); Map<String, List<Map<String, ?>>> relationships = articleApi.requestObject(relationshipsApiAddress, Map.class); return new ArticleMetadata(this, site, id, articlePointer, ingestionMetadata, itemTable, relationships); <START> } catch (EntityNotFoundException e) { <END> throw new NotFoundException(e); } }</code><technical_language>I this catch block initial service call of java Map<String, Object> ingestionMetadata = (Map<String, Object>) articleApi.requestObject( articlePointer.asApiAddress().build(), Map.class); get a valid response that, if of subsequent calls Rhino return a 404, is wrong want error out</technical_language>

Target:
public ArticleMetadata get(Site site, RequestedDoiVersion id, ArticlePointer articlePointer) throws IOException { Map<String, Object> ingestionMetadata; try { ingestionMetadata = (Map<String, Object>) articleApi.requestObject( articlePointer.asApiAddress().build(), Map.class); } catch (EntityNotFoundException e) { throw new NotFoundException(e); } Map<String, ?> itemTable = articleService.getItemTable(articlePointer); ApiAddress relationshipsApiAddress = ApiAddress.builder("articles") .embedDoi(articlePointer.getDoi()).addToken("relationships").build(); Map<String, List<Map<String, ?>>> relationships = articleApi.requestObject(relationshipsApiAddress, Map.class); return new ArticleMetadata(this, site, id, articlePointer, ingestionMetadata, itemTable, relationships); }