auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SegmentPublishResult perform(Task task, TaskActionToolbox toolbox) throws IOException { for (DataSegment segment : segments) { if (!toolbox.getTaskLockbox().upgrade(task, segment.getInterval()).isOk()) { <START> return SegmentPublishResult.fail(); <END> } } TaskActionPreconditions.checkTaskLocks(task, toolbox.getTaskLockbox(), segments); final SegmentPublishResult retVal = toolbox.getIndexerMetadataStorageCoordinator().announceHistoricalSegments( segments, startMetadata, endMetadata ); for (DataSegment segment : segments) { toolbox.getTaskLockbox().downgrade(task, segment.getInterval()); } final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension(DruidMetrics.DATASOURCE, task.getDataSource()) .setDimension(DruidMetrics.TASK_TYPE, task.getType()); if (retVal.isSuccess()) { toolbox.getEmitter().emit(metricBuilder.build("segment/txn/success", 1)); } else { toolbox.getEmitter().emit(metricBuilder.build("segment/txn/failure", 1)); } for (DataSegment segment : retVal.getSegments()) { metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segment/added/bytes", segment.getSize())); } return retVal; }</code><technical_language>I SegmentPublishResult.fail() a static object instead of a function returns a new</technical_language>

Target:
public SegmentPublishResult perform(Task task, TaskActionToolbox toolbox) throws IOException { TaskActionPreconditions.checkLockCoversSegments(task, toolbox.getTaskLockbox(), segments); final SegmentPublishResult retVal; try { retVal = toolbox.getTaskLockbox().doInCriticalSection( task, segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()), CriticalAction.<SegmentPublishResult>builder() .onValidLocks( () -> toolbox.getIndexerMetadataStorageCoordinator().announceHistoricalSegments( segments, startMetadata, endMetadata ) ) .onInvalidLocks(SegmentPublishResult::fail) .build() ); } catch (Exception e) { throw new RuntimeException(e); } if (retVal.isSuccess()) { final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension(DruidMetrics.DATASOURCE, task.getDataSource()) .setDimension(DruidMetrics.TASK_TYPE, task.getType()); if (retVal.isSuccess()) { toolbox.getEmitter().emit(metricBuilder.build("segment/txn/success", 1)); } else { toolbox.getEmitter().emit(metricBuilder.build("segment/txn/failure", 1)); } for (DataSegment segment : retVal.getSegments()) { metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segment/added/bytes", segment.getSize())); } } return retVal; }
Source:
<code>public static void assertBuildContains(List<HudsonModelRun> builds, String name) { String allBuildNames = ""; for (HudsonModelRun build : builds) { <START> String displayName = build.getFullDisplayName().substring(18, 30); <END> allBuildNames += (displayName + ", "); if (displayName.equals(name)) { return; } } Assert.fail("Expected '" + name + "' in {" + allBuildNames + "}"); }</code><technical_language>this incredibly fragile</technical_language>

Target:
public static void assertBuildContains(List<HudsonModelRun> builds, String name) { String allBuildNames = ""; for (HudsonModelRun build : builds) { String displayName = build.getFullDisplayName().split(" ")[2]; allBuildNames += (displayName + ", "); if (displayName.contains(name)) { return; } } Assert.fail("Expected '" + name + "' in {" + allBuildNames + "}"); }
Source:
<code>private MarshalledValueByteStream serialize(Object instance) { try { MarshalledValueByteStream baos = new ExpandableMarshalledValueByteStream(this.serialisedSize); ObjectOutput out = marshaller.startObjectOutput(baos, true, this.serialisedSize); try { marshaller.objectToObjectStream(instance, out); } finally { marshaller.finishObjectOutput(out); } <START> return new ImmutableMarshalledValueByteStream(Arrays.copyOfRange(baos.getRaw(), 0, baos.size())); <END> } catch (Exception e) { throw new CacheException("Unable to marshall value " + instance, e); } }</code><technical_language>Excellent point! in cases size difference is zero close it.. check a pointless copy</technical_language>

Target:
private MarshalledValueByteStream serialize(Object instance) { try { MarshalledValueByteStream baos = new ExpandableMarshalledValueByteStream(this.serialisedSize); ObjectOutput out = marshaller.startObjectOutput(baos, true, this.serialisedSize); try { marshaller.objectToObjectStream(instance, out); } finally { marshaller.finishObjectOutput(out); } return baos; } catch (Exception e) { throw new CacheException("Unable to marshall value " + instance, e); } }
Source:
<code>public byte[] decrypt(final byte[] inputData) { try { final Cipher cipher = Cipher.getInstance(ALGORITHM, PROVIDER); cipher.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(IVBYTES)); return cipher.doFinal(inputData); } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException | InvalidAlgorithmParameterException ex) { <START> LOGGER.error("Unexpected exception during decryption", ex); <END> throw new EncrypterException("Unexpected exception during decryption!", ex); } }</code><technical_language>Replace constant. occurs more once</technical_language>

Target:
public byte[] decrypt(final byte[] inputData) { try { final Cipher cipher = Cipher.getInstance(ALGORITHM, PROVIDER); cipher.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(IVBYTES)); return cipher.doFinal(inputData); } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException | InvalidAlgorithmParameterException ex) { LOGGER.error(UNEXPECTED_EXCEPTION_DURING_DECRYPTION, ex); throw new EncrypterException("Unexpected exception during decryption!", ex); } }
Source:
<code>public GenericWeighting(DataFlagEncoder encoder, PMap hintsMap) { super(encoder); gEncoder = encoder; headingPenalty = hintsMap.getDouble(Routing.HEADING_PENALTY, Routing.DEFAULT_HEADING_PENALTY); headingPenaltyMillis = Math.round(headingPenalty * 1000); result = encoder.createResult(hintsMap); <START> double biggestSpecifiedSpeed = result.getMaxspeed(); <END> if (biggestSpecifiedSpeed > encoder.getMaxPossibleSpeed()) throw new IllegalArgumentException("Some specified speed value bigger than maximum possible speed: " + biggestSpecifiedSpeed + " > " + encoder.getMaxPossibleSpeed()); this.maxSpeed = biggestSpecifiedSpeed / SPEED_CONV; accessType = gEncoder.getAccessType("motor_vehicle"); height = hintsMap.getDouble(HEIGHT_LIMIT, 0d); weight = hintsMap.getDouble(WEIGHT_LIMIT, 0d); width = hintsMap.getDouble(WIDTH_LIMIT, 0d); }</code><technical_language>rename getMaxspeed method biggestSpecifiedSpeed</technical_language>

Target:
public GenericWeighting(DataFlagEncoder encoder, PMap hintsMap) { super(encoder); gEncoder = encoder; headingPenalty = hintsMap.getDouble(Routing.HEADING_PENALTY, Routing.DEFAULT_HEADING_PENALTY); headingPenaltyMillis = Math.round(headingPenalty * 1000); weightingConfig = encoder.createWeightingConfig(hintsMap); double maxSpecifiedSpeed = weightingConfig.getMaxSpecifiedSpeed(); if (maxSpecifiedSpeed > encoder.getMaxPossibleSpeed()) throw new IllegalArgumentException("Some specified speed value bigger than maximum possible speed: " + maxSpecifiedSpeed + " > " + encoder.getMaxPossibleSpeed()); this.maxSpeed = maxSpecifiedSpeed / SPEED_CONV; accessType = gEncoder.getAccessType("motor_vehicle"); height = hintsMap.getDouble(HEIGHT_LIMIT, 0d); weight = hintsMap.getDouble(WEIGHT_LIMIT, 0d); width = hintsMap.getDouble(WIDTH_LIMIT, 0d); }
Source:
<code>protected Object transform( Message in, String mimeType, String transformerId, MimeTypeToTransformerMapper mapper) throws MimeTypeParseException, CatalogTransformerException { InputStream message = in.getBody(InputStream.class); if (message == null) { throw new CatalogTransformerException("Message body was null; unable to generate Metacard!"); } MimeType derivedMimeType; if (StringUtils.isEmpty(mimeType)) { derivedMimeType = new MimeType(getMimeTypeFromHeader(in, message)); <START> } else if (StringUtils.isNotBlank(transformerId)) { <END> derivedMimeType = new MimeType(mimeType + ";" + MimeTypeToTransformerMapper.ID_KEY + "=" + transformerId); } else { derivedMimeType = new MimeType(mimeType); } String metacardUpdateID = getHeaderAsStringAndRemove(in, METACARD_ID_HEADER); Metacard metacard; try { metacard = generateMetacard(derivedMimeType, mapper, message, metacardUpdateID); } catch (MetacardCreationException e) { throw new CatalogTransformerException( "Did not find an InputTransformer for MIME Type [" + mimeType + "] and " + MimeTypeToTransformerMapper.ID_KEY + " [" + transformerId + "]", e); } finally { IOUtils.closeQuietly(message); } return metacard; }</code><technical_language>reason mime type in header transformerId? curious transformerId precedence mimeType argument</technical_language>

Target:
protected Object transform( Message in, String mimeType, String transformerId, MimeTypeToTransformerMapper mapper) throws MimeTypeParseException, CatalogTransformerException { InputStream message = in.getBody(InputStream.class); if (message == null) { throw new CatalogTransformerException("Message body was null; unable to generate Metacard!"); } MimeType derivedMimeType = null; if (StringUtils.isEmpty(mimeType)) { try (TemporaryFileBackedOutputStream fileBackedOutputStream = new TemporaryFileBackedOutputStream()) { try { IOUtils.copy(message, fileBackedOutputStream); derivedMimeType = new MimeType( getMimeTypeFromHeader(in, fileBackedOutputStream.asByteSource().openStream())); } catch (IOException e) { LOGGER.debug("Failed to copy incoming inputStream message", e); } finally { message = fileBackedOutputStream.asByteSource().openStream(); } } catch (IOException e) { LOGGER.debug("Failed to create TemporaryFileBackedOuputStream", e); } } else if (StringUtils.isNotBlank(transformerId)) { derivedMimeType = new MimeType(mimeType + ";" + MimeTypeToTransformerMapper.ID_KEY + "=" + transformerId); } if (derivedMimeType == null) { derivedMimeType = new MimeType(mimeType); } String metacardUpdateID = getHeaderAsStringAndRemove(in, METACARD_ID_HEADER); Metacard metacard; try { metacard = generateMetacard(derivedMimeType, mapper, message, metacardUpdateID); } catch (MetacardCreationException e) { throw new CatalogTransformerException( "Did not find an InputTransformer for MIME Type [" + mimeType + "] and " + MimeTypeToTransformerMapper.ID_KEY + " [" + transformerId + "]", e); } finally { IOUtils.closeQuietly(message); } return metacard; }
Source:
<code><START> private void processFailureWhenClosed() { <END> this.countDown--; LOGGER.warn("Failure occurred. Decreased countDown value for circuit breaker to {}", this.countDown); if (this.countDown == 0) { this.openCircuit(); } }</code><technical_language>this method modifies countDown, is important decisions state transitions guarded a lock elsewhere, I this method synchronized. other modifications in class this method some point called holding proper lock</technical_language>

Target:
private void processFailureWhenClosed() { this.lock.lock(); try { this.countDown--; LOGGER.warn("Failure occurred. Decreased countDown value for circuit breaker to {}", this.countDown); if (this.countDown == 0) { this.openCircuit(); } } finally { this.lock.unlock(); } }
Source:
<code>public long sizeInBytes() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Reader " + m_cursorId + " has been closed"); } assertions(); long size = 0; <START> for (PBDSegment segment : m_segments.values()) { <END> final boolean wasClosed = segment.isClosed(); if (!segment.isOpenForReading(m_cursorId)) segment.openForRead(m_cursorId); size += segment.uncompressedBytesToRead(m_cursorId); if (wasClosed) { segment.close(); } } return size; } }</code><technical_language>loop range changed m_segments.tailMap(m_segmentId).values(), segment numbered m_segmentId is currently read this cursor, segments read uncompressedBytesToRead(m_cursorId) return 0 for segments</technical_language>

Target:
public long sizeInBytes() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Reader " + m_cursorId + " has been closed"); } assertions(); moveToValidSegment(); long size = 0; boolean inclusive = true; if (m_segment.isOpenForReading(m_cursorId)) { size = m_segment.getReader(m_cursorId).uncompressedBytesToRead(); inclusive = false; } for (PBDSegment currSegment : m_segments.tailMap(m_segment.segmentId(), inclusive).values()) { size += currSegment.size(); } return size; } }
Source:
<code>protected <T> void processSetting(EntityViewSetting<T, ?> setting, Object[] values) { for (JpaParameter parameter : parameters.getOptionalParameters()) { String parameterName = parameter.getParameterName(); Object parameterValue = values[parameter.getIndex()]; setting.addOptionalParameter(parameterName, parameterValue); } int entityViewSettingProcessorIndex = parameters.getEntityViewSettingProcessorIndex(); if (entityViewSettingProcessorIndex >= 0) { EntityViewSettingProcessor<T> processor = (EntityViewSettingProcessor<T>) values[entityViewSettingProcessorIndex]; <START> processor.acceptEntityViewSetting(setting); <END> } }</code><technical_language>Put a not-null check</technical_language>

Target:
protected <T> void processSetting(EntityViewSetting<T, ?> setting, Object[] values) { int entityViewSettingProcessorIndex = parameters.getEntityViewSettingProcessorIndex(); if (entityViewSettingProcessorIndex >= 0) { EntityViewSettingProcessor<T> processor = (EntityViewSettingProcessor<T>) values[entityViewSettingProcessorIndex]; if (processor != null) { setting = processor.acceptEntityViewSetting(setting); } } for (JpaParameter parameter : parameters.getOptionalParameters()) { String parameterName = parameter.getParameterName(); Object parameterValue = values[parameter.getIndex()]; setting.addOptionalParameter(parameterName, parameterValue); } }
Source:
<code><START> public ParseResult parse(String infixTagExpression) { <END> return constructExpressionFrom(tokensDerivedFrom(infixTagExpression)); }</code><technical_language>suggestion ParseResult parse(String infixTagExpression) {</technical_language>

Target:
ParseResult parse(String infixTagExpression) { return constructExpressionFrom(tokensDerivedFrom(infixTagExpression)); }
Source:
<code>public void justWorks() throws Exception { <START> FtRemote.secure(new TkFork(new FkRegex("/", "hello, world!"))).exec( <END> new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.startsWith("hello")); } } ); }</code><technical_language>@bdragan this class testing FtSecure</technical_language>

Target:
public void justWorks() throws Exception { FtSecureTest.secure(new TkFixed("hello, world")).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.startsWith("hello")); } } ); }
Source:
<code>public Set<Class<?>> findAnnotatedClasses(Class annotationClass) throws ClassNotFoundException { Set<Class<?>> annotatedClasses = new HashSet<Class<?>>(); ArrayList<String> dynamicClasses = classNames; for (String dynamicClass : dynamicClasses) { <START> Class<?> classz = getClassLoader().loadClass(dynamicClass); <END> if (classz.getAnnotation(annotationClass) != null) { annotatedClasses.add(classz); } } return annotatedClasses; }</code><technical_language>Instead of loading classes here, why. iterate compiledObjects.values()</technical_language>

Target:
public Set<Class<?>> findAnnotatedClasses(Class annotationClass) throws ClassNotFoundException { Set<Class<?>> annotatedClasses = new HashSet<Class<?>>(); ArrayList<String> dynamicClasses = classNames; for (String dynamicClass : dynamicClasses) { Class<?> classz = compiledObjects.get(dynamicClass); if (classz.getAnnotation(annotationClass) != null) { annotatedClasses.add(classz); } } return annotatedClasses; }
Source:
<code>public void initForViewByRecipientGiverQuestion(InstructorAttributes instructor, String selectedSection, String showStats, String groupByTeam) { viewType = ViewType.RECIPIENT_GIVER_QUESTION; this.instructor = instructor; this.selectedSection = selectedSection; this.showStats = showStats; this.groupByTeam = groupByTeam; if (!bundle.isComplete) { buildSectionPanelsForForAjaxLoading(sections); return; } if (bundle.responses.isEmpty()) { return; } <START> setShouldCollapsed(bundle.responses.size() > RESPONSE_LIMIT_FOR_COLLAPSING_PANEL); <END> Map<String, Map<String, List<FeedbackResponseAttributes>>> sortedResponses = bundle.getResponsesSortedByRecipient(true); buildSectionPanelsForRecipientGiverQuestion(sortedResponses); }</code><technical_language>a good idea put segments a function returning a boolean (to terminate not)? multiple times</technical_language>

Target:
public void initForViewByRecipientGiverQuestion(InstructorAttributes instructor, String selectedSection, String showStats, String groupByTeam) { viewType = ViewType.RECIPIENT_GIVER_QUESTION; this.instructor = instructor; this.selectedSection = selectedSection; this.showStats = showStats; this.groupByTeam = groupByTeam; if (!bundle.isComplete) { if (isAllSectionsSelected()) { buildSectionPanelsForForAjaxLoading(sections); } else { buildSectionPanelWithErrorMessage(); } return; } if (bundle.responses.isEmpty()) { return; } setShouldCollapsed(bundle.responses.size() > RESPONSE_LIMIT_FOR_COLLAPSING_PANEL); Map<String, Map<String, List<FeedbackResponseAttributes>>> sortedResponses = bundle.getResponsesSortedByRecipient(true); buildSectionPanelsForRecipientGiverQuestion(sortedResponses); }
Source:
<code>public void setParams(Integer lower, Integer upper) { if (lower != null) { this.lower = lower; this.hasLower = true; } if (upper != null) { this.upper = upper; this.hasUpper = true; } if (this.hasLower && this.hasUpper) { <START> if (this.lower > this.upper) { <END> throw new IllegalArgumentException( "UniformInt distribution requires that lower <= upper"); } } }</code><technical_language>combine line 103 previous condition</technical_language>

Target:
public void setParams(Integer lower, Integer upper) { if (lower != null) { this.lower = lower; this.hasLower = true; } if (upper != null) { this.upper = upper; this.hasUpper = true; } if (this.hasLower && this.hasUpper) { if (this.lower > this.upper) { throw new IllegalArgumentException( "UniformInt distribution requires that lower <= upper"); } this.prob = 1.0 / (this.upper - this.lower + 1); this.logProb = Math.log(this.prob); } }
Source:
<code>private static Map<String, String> parseAttrs(List<String> attributes) throws BadRequestException, ForbiddenException { if (attributes == null) { <START> return new HashMap<>(); <END> } final Map<String, String> res = Maps.newHashMapWithExpectedSize(attributes.size()); for (String attribute : attributes) { final int colonIdx = attribute.indexOf(':'); if (colonIdx == -1) { throw new BadRequestException( "Attribute '" + attribute + "' is not valid, " + "it should contain name and value separated with colon. " + "For example: attributeName:attributeValue"); } String name = attribute.substring(0, colonIdx); String value = attribute.substring(colonIdx + 1); if (name.isEmpty()) throw new BadRequestException( "Attribute '" + attribute + "' is not valid, " + "Empty attribute name is not allowed. "); if (name.startsWith("codenvy")) throw new ForbiddenException( "Attribute '" + attribute + "' is not allowed. 'codenvy' prefix is reserved. "); res.put(name, value); } return res; }</code><technical_language>this change</technical_language>

Target:
private static Map<String, String> parseAttrs(List<String> attributes) throws BadRequestException, ForbiddenException { if (attributes == null) { return Maps.newHashMapWithExpectedSize(1); } final Map<String, String> res = Maps.newHashMapWithExpectedSize(attributes.size()); for (String attribute : attributes) { final int colonIdx = attribute.indexOf(':'); if (colonIdx == -1) { throw new BadRequestException( "Attribute '" + attribute + "' is not valid, " + "it should contain name and value separated with colon. " + "For example: attributeName:attributeValue"); } String name = attribute.substring(0, colonIdx); String value = attribute.substring(colonIdx + 1); if (name.isEmpty()) throw new BadRequestException( "Attribute '" + attribute + "' is not valid, " + "Empty attribute name is not allowed. "); if (name.startsWith("codenvy")) throw new ForbiddenException( "Attribute '" + attribute + "' is not allowed. 'codenvy' prefix is reserved. "); res.put(name, value); } return res; }
Source:
<code>SearchIndexAsyncClient(String endpoint, String indexName, SearchServiceVersion apiVersion, HttpPipeline httpPipeline) { SearchServiceUrlParts parts = SearchServiceUrlParser.parseServiceUrlParts(endpoint); <START> if (StringUtils.isBlank(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("Invalid indexName")); } if (apiVersion == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Invalid apiVersion")); } if (httpPipeline == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Invalid httpPipeline")); } <END> this.endpoint = endpoint; this.indexName = indexName; this.apiVersion = apiVersion; this.httpPipeline = httpPipeline; restClient = new SearchIndexRestClientBuilder() .searchServiceName(parts.serviceName) .indexName(indexName) .searchDnsSuffix(parts.dnsSuffix) .apiVersion(apiVersion.getVersion()) .pipeline(httpPipeline) .serializer(SERIALIZER) .build(); }</code><technical_language>checks in client builder instead of constructor</technical_language>

Target:
SearchIndexAsyncClient(String endpoint, String indexName, SearchServiceVersion apiVersion, HttpPipeline httpPipeline) { SearchServiceUrlParts parts = SearchServiceUrlParser.parseServiceUrlParts(endpoint); if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new NullPointerException("Invalid indexName")); } if (apiVersion == null) { throw logger.logExceptionAsError(new NullPointerException("Invalid apiVersion")); } if (httpPipeline == null) { throw logger.logExceptionAsError(new NullPointerException("Invalid httpPipeline")); } this.endpoint = endpoint; this.indexName = indexName; this.apiVersion = apiVersion; this.httpPipeline = httpPipeline; restClient = new SearchIndexRestClientBuilder() .searchServiceName(parts.serviceName) .indexName(indexName) .searchDnsSuffix(parts.dnsSuffix) .apiVersion(apiVersion.getVersion()) .pipeline(httpPipeline) .serializer(SERIALIZER) .build(); }
Source:
<code>public <T> Maybe<Class<T>> tryResolveClass(String bundleUrl, String type) { try { <START> Class<T> clazz = (Class<T>) Osgis.getBundle(framework, bundleUrl).get().loadClass(type); <END> return Maybe.of(clazz); } catch (Exception e) { Exceptions.propagateIfFatal(e); return Maybe.absent(e); } }</code><technical_language>loadClass(type) throw ClassNotFoundException if found. catch generic Exception? e.g. if bundle name invalid fine throw exception returning Maybe.absent()</technical_language>

Target:
public <T> Maybe<Class<T>> tryResolveClass(String bundleUrl, String type) { try { Maybe<Bundle> bundle = Osgis.getBundle(framework, bundleUrl); if (bundle.isPresent()) { Class<T> clazz = (Class<T>) bundle.get().loadClass(type); return Maybe.of(clazz); } else { return Maybe.absent("No bundle found in " + framework + " at URL: " + bundleUrl); } } catch (ClassNotFoundException e) { return Maybe.absent(e); } }
Source:
<code>public void testWithParameterAuthorizationUrl(String host, String redirectUrl, String opHost, String redirectUrls, String postLogoutRedirectUrl, String logoutUrl, String paramRedirectUrl) throws IOException { ClientInterface client = Tester.newClient(host); final RegisterSiteResponse site = RegisterSiteTest.registerWithMultipleRedirectUrls(client, opHost, redirectUrl, postLogoutRedirectUrl, logoutUrl, redirectUrls); final GetAuthorizationUrlParams commandParams = new GetAuthorizationUrlParams(); commandParams.setOxdId(site.getOxdId()); commandParams.setAuthorizationRedirectUri(paramRedirectUrl); final GetAuthorizationUrlResponse resp = client.getAuthorizationUrl(Tester.getAuthorization(), commandParams); assertNotNull(resp); <START> notEmpty(resp.getAuthorizationUrl()); <END> }</code><technical_language>check paramRedirectUrl is contained resp.getAuthorizationUrl()</technical_language>

Target:
public void testWithParameterAuthorizationUrl(String host, String redirectUrl, String opHost, String redirectUrls, String postLogoutRedirectUrl, String logoutUrl, String paramRedirectUrl) throws IOException { ClientInterface client = Tester.newClient(host); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrl, postLogoutRedirectUrl, logoutUrl, StringUtils.isNotBlank(redirectUrls) ? Lists.newArrayList(redirectUrls.split(" ")) : null); final GetAuthorizationUrlParams commandParams = new GetAuthorizationUrlParams(); commandParams.setOxdId(site.getOxdId()); commandParams.setAuthorizationRedirectUri(paramRedirectUrl); final GetAuthorizationUrlResponse resp = client.getAuthorizationUrl(Tester.getAuthorization(), commandParams); assertNotNull(resp); notEmpty(resp.getAuthorizationUrl()); assertTrue(resp.getAuthorizationUrl().contains(paramRedirectUrl)); }
Source:
<code>private boolean hasAnyRolePermission(final WorkflowAction wa,final Iterable<Role> roles) throws DotDataException{ <START> for(Role role:roles){ <END> if (permissionAPI.doesRoleHavePermission(wa, PermissionAPI.PERMISSION_USE, role)) { return true; } } return false; }</code><technical_language>set final</technical_language>

Target:
private boolean hasAnyRolePermission(final WorkflowAction wa,final Iterable<Role> roles) throws DotDataException{ for(final Role role:roles){ if (permissionAPI.doesRoleHavePermission(wa, PermissionAPI.PERMISSION_USE, role)) { return true; } } return false; }
Source:
<code><START> public void testWebGetCallMeter() { <END> sleep20Millis(); long currMeterNum = dr.getMeter("Web-Get-Call-Meter"); WebMetrics.INSTANCE.markWebGetCall(); sleep20Millis(); Assert.assertEquals(dr.getMeter("Web-Get-Call-Meter"), currMeterNum + 1); WebMetrics.INSTANCE.markWebGetCall(); WebMetrics.INSTANCE.markWebGetCall(); sleep20Millis(); Assert.assertEquals(dr.getMeter("Web-Get-Call-Meter"), currMeterNum + 3); }</code><technical_language>Consider consolidating tests parameterized tests</technical_language>

Target:
public void testWebGetCallMeter() { MetricsTestUtility.testMeter("Web-Get-Call-Meter", dr, WebMetrics.INSTANCE::markWebGetCall); }
Source:
<code>public String removeEvent(@PathVariable("id") long id, RedirectAttributes redirectAttributes) { Event event = eventRepository.findOne(id); if (event != null) { eventRepository.delete(event); redirectAttributes.addFlashAttribute("message", "Event '" + event.getTitle() + "' deleted!"); } else { <START> redirectAttributes.addFlashAttribute("message", "That event does not exist."); <END> } return "redirect:/events/"; }</code><technical_language>This throw error instead</technical_language>

Target:
public String removeEvent(@PathVariable("id") long id, RedirectAttributes redirectAttributes) throws EventNotFoundException { Event event = eventRepository.findOne(id); if (event != null) { eventRepository.delete(event); redirectAttributes.addFlashAttribute("message", "Event '" + event.getTitle() + "' deleted!"); return "redirect:/events/"; } else { throw new EventNotFoundException("This event does not exist"); } }
Source:
<code><START> public static HostInfo buildFromEndpoint(final String endPoint) { <END> final String host = getHost(endPoint); final Integer port = getPort(endPoint); if (host == null || port == null) { throw new ConfigException( String.format("Error parsing host address %s. Expected format host:port.", endPoint) ); } return new HostInfo(host, port); }</code><technical_language>migrated unit test</technical_language>

Target:
public static HostInfo buildFromEndpoint(final String endPoint) { if (endPoint == null || endPoint.trim().isEmpty()) { return null; } final String host = getHost(endPoint); final Integer port = getPort(endPoint); if (host == null || port == null) { throw new ConfigException( String.format("Error parsing host address %s. Expected format host:port.", endPoint) ); } return new HostInfo(host, port); }
Source:
<code>public Stream<Object> extractAllEntitiesStream(Solution_ solution) { <START> List<Stream<Object>> streamList = new ArrayList<>( entityMemberAccessorMap.size() + entityCollectionMemberAccessorMap.size()); for (MemberAccessor memberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(memberAccessor, solution); if (entity != null) { streamList.add(Stream.of(entity)); } } for (MemberAccessor memberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollectionOrArray(memberAccessor, solution, false); streamList.add(entityCollection.stream()); } return streamList.stream().flatMap(Function.identity()); <END> }</code><technical_language>I do Stream.concat(). allow get rid of List</technical_language>

Target:
public Stream<Object> extractAllEntitiesStream(Solution_ solution) { Stream<Object> stream = Stream.empty(); for (MemberAccessor memberAccessor : entityMemberAccessorMap.values()) { Object entity = extractMemberObject(memberAccessor, solution); if (entity != null) { stream = Stream.concat(stream, Stream.of(entity)); } } for (MemberAccessor memberAccessor : entityCollectionMemberAccessorMap.values()) { Collection<Object> entityCollection = extractMemberCollectionOrArray(memberAccessor, solution, false); stream = Stream.concat(stream, entityCollection.stream()); } return stream; }
Source:
<code>public void clear() { <START> authzManager.checkPermission(CachePermission.WRITE); <END> delegate.clear(); }</code><technical_language>this bulk instead</technical_language>

Target:
public void clear() { authzManager.checkPermission(AuthorizationPermission.BULK_WRITE); delegate.clear(); }
Source:
<code><START> private boolean originalConstraintMatches(TableScanNode node) <END> { Map<String, SymbolReference> assignments = node.getOutputSymbols().stream() .collect(toMap(Symbol::getName, Symbol::toSymbolReference)); SymbolAliases symbolAliases = SymbolAliases.builder().putAll(assignments).build(); ExpressionVerifier verifier = new ExpressionVerifier(symbolAliases); return expectedOriginalConstraint .map(expected -> verifier.process(node.getOriginalConstraint(), expected)) .orElse(true); }</code><technical_language>put this method method</technical_language>

Target:
private boolean originalConstraintMatches(TableScanNode node) { return expectedOriginalConstraint .map(expected -> { Map<String, SymbolReference> assignments = node.getOutputSymbols().stream() .collect(toMap(Symbol::getName, Symbol::toSymbolReference)); SymbolAliases symbolAliases = SymbolAliases.builder().putAll(assignments).build(); ExpressionVerifier verifier = new ExpressionVerifier(symbolAliases); return verifier.process(node.getOriginalConstraint(), expected); }) .orElse(true); }
Source:
<code>public boolean logoutCurrentUser(String sessionID) throws IOException { if(sessionID == null || sessionID.isEmpty()) throw new IOException("invalid input of session ID"); final String url = URL_AUTH + "/" + URL_LOGOUT; Map<String, String> response = request(url, null, sessionID, HTTP_METHOD_POST); String responseCode = response.get(RESPONSE_CODE); int result = checkResponseCode(response.get(RESPONSE_CODE), "logout"); <START> if(result != 0) <END> throw new IOException("logout with session id failed "); return (result == 0); }</code><technical_language>if throw exception function return false true</technical_language>

Target:
public boolean logoutCurrentUser(String sessionID) throws IOException, IllegalArgumentException { if(sessionID == null || sessionID.isEmpty()) throw new IllegalArgumentException("invalid input of session ID"); final String url = URL_AUTH + "/" + URL_LOGOUT; Map<String, String> response = request(url, null, sessionID, HTTP_METHOD_POST); String responseCode = response.get(RESPONSE_CODE); int result = checkResponseCode(response.get(RESPONSE_CODE), "logout"); return (result == 0); }
Source:
<code>protected boolean isUserAuthorizedToRunAction() { if (isInternalExecution()) { if (log.isDebugEnabled()) { log.debugFormat("Permission check skipped for internal action {0}.", getActionType()); } return true; } if (!MultiLevelAdministrationHandler.isMultilevelAdministrationOn()) { if (log.isDebugEnabled()) { log.debugFormat("Permission check for action {0} skipped because multilevel administration is disabled.", getActionType()); } return true; } if (getCurrentUser() == null) { addCanDoActionMessage(VdcBllMessages.USER_IS_NOT_LOGGED_IN); return false; } final List<PermissionSubject> permSubjects = getPermissionCheckSubjects(); if (permSubjects == null || permSubjects.isEmpty()) { if (log.isDebugEnabled()) { log.debugFormat("The set of objects to check is null or empty for action {0}.", getActionType()); } <START> addCanDoActionMessage(VdcBllMessages.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); <END> return false; } if (isQuotaDependant()) { addQuotaPermissionSubject(permSubjects); } if (log.isDebugEnabled()) { StringBuilder builder = getPermissionSubjectsAsStringBuilder(permSubjects); log.debugFormat("Checking whether user {0} has permission on {1}", getCurrentUser().getId(), builder.toString()); } return checkPermissions(permSubjects); }</code><technical_language>suggest move here, print info, this is case in operation failed permissions, helpful there</technical_language>

Target:
protected boolean isUserAuthorizedToRunAction() { if (isInternalExecution()) { if (log.isDebugEnabled()) { log.debugFormat("Permission check skipped for internal action {0}.", getActionType()); } return true; } if (!MultiLevelAdministrationHandler.isMultilevelAdministrationOn()) { if (log.isDebugEnabled()) { log.debugFormat("Permission check for action {0} skipped because multilevel administration is disabled.", getActionType()); } return true; } if (getCurrentUser() == null) { addCanDoActionMessage(VdcBllMessages.USER_IS_NOT_LOGGED_IN); return false; } final List<PermissionSubject> permSubjects = getPermissionCheckSubjects(); if (permSubjects == null || permSubjects.isEmpty()) { if (log.isDebugEnabled()) { log.debugFormat("The set of objects to check is null or empty for action {0}.", getActionType()); } addCanDoActionMessage(VdcBllMessages.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); StringBuilder builder = getPermissionSubjectsAsStringBuilder(permSubjects); log.infoFormat("Checking whether user {0} or one of the groups he is member of, have the following permissions: {1}", getCurrentUser().getId(), builder.toString()); return false; } if (isQuotaDependant()) { addQuotaPermissionSubject(permSubjects); } return checkPermissions(permSubjects); }
Source:
<code><START> private static void fetchExecutorMetrics(long now, MBeanServer mbs, List<Metric> metrics) <END> throws JMException { final ObjectName executorName = new ObjectName("Catalina:type=Executor,*"); final Set<ObjectName> names = mbs.queryNames(executorName, null); if (names == null) { return; } for (ObjectName name : names) { AttributeList list = mbs.getAttributes(name, EXECUTOR_ATTRS); for (Attribute a : list.asList()) { metrics.add(toGauge(now, name, a)); } } }</code><technical_language>issue executor is values for default ThreadPool mbean bogus (-1 for values). nice if cleaner. report ThreadPool stats if a custom executor is used. I executorName Connector mbean is for a connector. Another area some confusion in is some of naming is switch a custom executor. normalize a bit general names same? For example, currentThreadCount activeCount</technical_language>

Target:
private static void fetchExecutorMetrics(long now, MBeanServer mbs, List<Metric> metrics) throws JMException { final ObjectName executorName = new ObjectName("Catalina:type=Executor,*"); final Set<ObjectName> names = mbs.queryNames(executorName, null); if (names == null) { return; } for (ObjectName name : names) { AttributeList list = mbs.getAttributes(name, EXECUTOR_ATTRS); for (Attribute a : list.asList()) { addMetric(metrics, a.getName().equals("completedTaskCount") ? toCounter(now, name, a) : toGauge(now, name, a)); } } }
Source:
<code>public String sendQrCode() throws SocketException { people = userFacade.findByEmail(this.uname); HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext. getCurrentInstance().getExternalContext().getRequest(); try { if (people != null && authController.checkPasswordAndStatus(people, passwd, httpServletRequest)) { String random = SecurityUtils.getRandomPassword(passwordLength); usersController.updateSecret(people.getUid(), random); String message = UserAccountsEmailMessages.buildTempResetMessage(random); email.sendEmail(people.getEmail(), RecipientType.TO,UserAccountsEmailMessages.ACCOUNT_PASSWORD_RESET, message); am.registerAccountChange(people, AccountsAuditActions.RECOVERY.name(), AccountsAuditActions.SUCCESS.name(), "Reset QR code.", people, httpServletRequest); return "validate_code"; } else { <START> MessagesController.addSecurityErrorMessage(AccountStatusErrorMessages.INCCORCT_CREDENTIALS); <END> if (people != null) { am.registerAccountChange(people, AccountsAuditActions.RECOVERY.name(), AccountsAuditActions.FAILED.name(), "", people, httpServletRequest); } return ""; } } catch (MessagingException ex) { am.registerAccountChange(people, AccountsAuditActions.RECOVERY.name(), AccountsAuditActions.FAILED.name(), "", people, httpServletRequest); } catch (AppException ex) { Logger.getLogger(RecoverySelector.class.getName()).log(Level.SEVERE, null, ex); } MessagesController.addSecurityErrorMessage(AccountStatusErrorMessages.INTERNAL_ERROR); return ""; }</code><technical_language>@ErmiasG Small typo in constant</technical_language>

Target:
public String sendQrCode() throws SocketException { people = userFacade.findByEmail(this.uname); HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext. getCurrentInstance().getExternalContext().getRequest(); try { if (people != null && authController.checkPasswordAndStatus(people, passwd, httpServletRequest)) { String random = SecurityUtils.getRandomPassword(passwordLength); usersController.updateSecret(people.getUid(), random); String message = UserAccountsEmailMessages.buildTempResetMessage(random); email.sendEmail(people.getEmail(), RecipientType.TO,UserAccountsEmailMessages.ACCOUNT_PASSWORD_RESET, message); am.registerAccountChange(people, AccountsAuditActions.RECOVERY.name(), AccountsAuditActions.SUCCESS.name(), "Reset QR code.", people, httpServletRequest); return "validate_code"; } else { MessagesController.addSecurityErrorMessage(AccountStatusErrorMessages.INCORRECT_CREDENTIALS); if (people != null) { am.registerAccountChange(people, AccountsAuditActions.RECOVERY.name(), AccountsAuditActions.FAILED.name(), "", people, httpServletRequest); } return ""; } } catch (MessagingException ex) { am.registerAccountChange(people, AccountsAuditActions.RECOVERY.name(), AccountsAuditActions.FAILED.name(), "", people, httpServletRequest); } catch (AppException ex) { Logger.getLogger(RecoverySelector.class.getName()).log(Level.SEVERE, null, ex); } MessagesController.addSecurityErrorMessage(AccountStatusErrorMessages.INTERNAL_ERROR); return ""; }
Source:
<code>public final String getStatusCounts() { <START> String buckets = new String(); <END> for (Map.Entry<Status, AtomicInteger> entry : returncodes.entrySet()) { buckets += ", Return(" + entry.getKey().getName() + ")=" + entry.getValue().get(); } return buckets; }</code><technical_language>a StringAppender</technical_language>

Target:
public final String getStatusCounts() { StringBuilder buckets = new StringBuilder(); for (Map.Entry<Status, AtomicInteger> entry : returncodes.entrySet()) { buckets.append(", Return(" + entry.getKey().getName() + ")=" + entry.getValue().get()); } return buckets.toString(); }
Source:
<code>public void merge(ProjectInfo projectInfo) { getLibraries().putAll(projectInfo.getLibraries()); <START> getTargets().putAll(projectInfo.getTargets()); <END> if (getPythonSetup() == null && projectInfo.getPythonSetup() != null) { python_setup = projectInfo.getPythonSetup(); } }</code><technical_language>prefer instance variables get indicator is modifying class. getLibraries() getTargets() return a frozen collection. legacy issue again</technical_language>

Target:
public void merge(ProjectInfo projectInfo) { libraries.putAll(projectInfo.getLibraries()); targets.putAll(projectInfo.getTargets()); if (python_setup == null && projectInfo.getPythonSetup() != null) { python_setup = projectInfo.getPythonSetup(); } }
Source:
<code>public F.Promise<Result> show(final String languageTag) { final UserContext userContext = userContext(languageTag); final F.Promise<Cart> cartPromise = getOrCreateCart(userContext, session()); return cartPromise.map(cart -> { final CheckoutConfirmationPageContent content = new CheckoutConfirmationPageContent(cart, userContext, productDataConfig, i18nResolver(), reverseRouter()); <START> final SunrisePageData pageData = pageData(userContext, content, ctx()); <END> return ok(templateService().renderToHtml("checkout-confirmation", pageData, userContext.locales())); }); }</code><technical_language>if get error message Http.Context is reason this kind of changes, especially in Play 2.5</technical_language>

Target:
public CompletionStage<Result> show(final String languageTag) { final UserContext userContext = userContext(languageTag); return getOrCreateCart(userContext, session()) .thenApplyAsync(cart -> renderCheckoutConfirmationPage(cart, userContext), HttpExecution.defaultContext()); }
Source:
<code>public void onPlayerConsumePotion(PlayerItemConsumeEvent event) { if (event.getItem().getType() == Material.POTION) { Collection<PotionEffect> fx = Potion.fromItemStack(event.getItem()).getEffects(); for (PotionEffect effect : fx) { <START> if (effect.getType() == PotionEffectType.INVISIBILITY && !TFM_AdminList.isSuperAdmin(event.getPlayer())) <END> { event.getPlayer().sendMessage(ChatColor.RED + "Invisibility is not allowed."); event.setCancelled(true); } } } }</code><technical_language>is avoid nested if statements</technical_language>

Target:
public void onPlayerConsumePotion(PlayerItemConsumeEvent event) { Collection<PotionEffect> fx = Potion.fromItemStack(event.getItem()).getEffects(); for (PotionEffect effect : fx) { if (effect.getType() == PotionEffectType.INVISIBILITY && !TFM_AdminList.isSuperAdmin(event.getPlayer()) && && event.getItem().getType() == Material.POTION) { event.getPlayer().sendMessage(ChatColor.RED + "Invisibility is not allowed."); event.setCancelled(true); } } }
Source:
<code>public JsonLdConfiguration(GeoServerDataDirectory dd) { this.dd = dd; templateCache = CacheBuilder.newBuilder() .maximumSize(10) <START> .initialCapacity(1) <END> .expireAfterAccess(120, TimeUnit.MINUTES) .build( new CacheLoader<CacheKey, JsonLdTemplate>() { @Override public JsonLdTemplate load(CacheKey key) { Resource resource = dd.get(key.getResource(), key.getPath()); JsonLdTemplate template = new JsonLdTemplate(resource); return template; } }); }</code><technical_language>default a bit small... 100 configurable System variable? Ideally nice runtime configurable, for example matching number of cached feature types in "global settings", guessing some complications, possibly rebuilding cache. thinking out loud mind, asking for this change implemented</technical_language>

Target:
public JsonLdConfiguration(GeoServerDataDirectory dd) { this.dd = dd; templateCache = CacheBuilder.newBuilder() .maximumSize(100) .initialCapacity(1) .expireAfterAccess(120, TimeUnit.MINUTES) .build( new CacheLoader<CacheKey, JsonLdTemplate>() { @Override public JsonLdTemplate load(CacheKey key) { Resource resource = dd.get(key.getResource(), key.getPath()); JsonLdTemplate template = new JsonLdTemplate(resource); return template; } }); }
Source:
<code>public void fileStatusArraySortingWithEventDumpDirComparator() { FileStatus[] dirList = new FileStatus[30]; for (int i = 0; i < 30; i+=2){ dirList[i] = new FileStatus(5, true, 1, 64, 100, <START> new Path("hdfs://tmp/"+Integer.toString(i+1))); <END> } for (int i = 1; i < 30; i+=2){ dirList[i] = new FileStatus(5, true, 1, 64, 100, new Path("hdfs://tmp/"+Integer.toString(i-1))); } Arrays.sort(dirList, new EventDumpDirComparator()); for (int i = 0; i < 30; i++){ assertTrue(dirList[i].getPath().getName().equalsIgnoreCase(Integer.toString(i))); } }</code><technical_language>Need license too</technical_language>

Target:
public void fileStatusArraySortingWithEventDumpDirComparator() { int size = 30; FileStatus[] dirList = new FileStatus[size]; for (int i = 0; i < size; i++){ dirList[i] = new FileStatus(5, true, 1, 64, 100, new Path("hdfs://tmp/"+Integer.toString(size-i))); } Arrays.sort(dirList, new EventDumpDirComparator()); for (int i = 0; i < 30; i++){ assertTrue(dirList[i].getPath().getName().equalsIgnoreCase(Integer.toString(i+1))); } }
Source:
<code>protected void doSend(String destination, Message<?> message) { try { <START> if (message.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION) instanceof CorrelationData) { <END> this.rabbitTemplate.send(destination, createMessage(message), message.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION, CorrelationData.class)); } else { this.rabbitTemplate.send(destination, createMessage(message)); } } catch (RuntimeException ex) { throw convertAmqpException(ex); } }</code><technical_language>perform this get() once</technical_language>

Target:
protected void doSend(String destination, Message<?> message) { try { Object correlation = message.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION); if (correlation instanceof CorrelationData) { this.rabbitTemplate.send(destination, createMessage(message), (CorrelationData) correlation); } else { this.rabbitTemplate.send(destination, createMessage(message)); } } catch (RuntimeException ex) { throw convertAmqpException(ex); } }
Source:
<code>void intBoxingAndUnboxing(int int1, Integer integer1, String string, Double double1) { new Integer(int1).intValue(); new Integer(1 + 2).intValue(); Integer.valueOf(int1).intValue(); Integer.valueOf(1 + 2).intValue(); processInt(string, new Integer(int1)); new Integer(int1).toString(); integer1.intValue(); Integer.valueOf(integer1); Integer.valueOf(double1); <START> int int2 = new Integer(1); END> int2 = new Integer(1); int2 = new Integer(string); Integer integer2 = new Integer(1); integer2 = new Integer(1); int2 = new Unknown(); int2 = unknownMethod(1); }</code><technical_language>I add case Long.valueOf (to justify generalization in code)</technical_language>

Target:
void intBoxingAndUnboxing(int int1, Integer integer1, String string, Double double1) { new Integer(int1).intValue(); new Integer(1 + 2).intValue(); Integer.valueOf(int1).intValue(); Integer.valueOf(1 + 2).intValue(); processInt(string, new Integer(int1)); new Integer(int1).toString(); integer1.intValue(); Integer.valueOf(integer1); Double.valueOf(double1); Integer.valueOf(double1); Long.valueOf(integer1); int int2 = new Integer(1); int2 = new Integer(1); int2 = new Integer(string); Integer integer2 = new Integer(1); integer2 = new Integer(1); int2 = new Unknown(); int2 = unknownMethod(1); }