auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static HiveColumnStatistics createHiveColumnStatistics( ConnectorSession session, DateTimeZone timeZone, Map<ColumnStatisticType, Block> computedStatistics, Type columnType, long rowCount) { HiveColumnStatistics.Builder result = HiveColumnStatistics.builder(); <START> if (computedStatistics.containsKey(MIN) && computedStatistics.containsKey(MAX)) { <END> setMinMax(session, timeZone, columnType, computedStatistics.get(MIN), computedStatistics.get(MAX), result); } if (computedStatistics.containsKey(NUMBER_OF_DISTINCT_VALUES)) { result.setDistinctValuesCount(BIGINT.getLong(computedStatistics.get(NUMBER_OF_DISTINCT_VALUES), 0)); } if (computedStatistics.containsKey(MAX_VALUE_SIZE_IN_BYTES)) { result.setMaxColumnLength(BIGINT.getLong(computedStatistics.get(MAX_VALUE_SIZE_IN_BYTES), 0)); } if (computedStatistics.containsKey(AVERAGE_VALUE_SIZE_IN_BYTES)) { result.setAverageColumnLength(DOUBLE.getDouble(computedStatistics.get(AVERAGE_VALUE_SIZE_IN_BYTES), 0)); } if (computedStatistics.containsKey(NUMBER_OF_NON_NULL_VALUES)) { result.setNullsCount(rowCount - BIGINT.getLong(computedStatistics.get(NUMBER_OF_NON_NULL_VALUES), 0)); } if (computedStatistics.containsKey(NUMBER_OF_TRUE_VALUES) && computedStatistics.containsKey(NUMBER_OF_NON_NULL_VALUES)) { long numberOfTrue = BIGINT.getLong(computedStatistics.get(NUMBER_OF_TRUE_VALUES), 0); long numberOfNonNullValues = BIGINT.getLong(computedStatistics.get(NUMBER_OF_NON_NULL_VALUES), 0); result.setBooleanStatistics(new BooleanStatistics(OptionalLong.of(numberOfTrue), OptionalLong.of(numberOfNonNullValues - numberOfTrue))); } return result.build(); }</code><technical_language>this need neither? Sort of sense required fields, totally useless one. E.g. if min for x 10 a predicate x < 8, matches</technical_language>

Target:
private static HiveColumnStatistics createHiveColumnStatistics( ConnectorSession session, DateTimeZone timeZone, Map<ColumnStatisticType, Block> computedStatistics, Type columnType, long rowCount) { HiveColumnStatistics.Builder result = HiveColumnStatistics.builder(); verify(computedStatistics.containsKey(MIN_VALUE) == computedStatistics.containsKey(MAX_VALUE)); if (computedStatistics.containsKey(MIN_VALUE)) { setMinMax(session, timeZone, columnType, computedStatistics.get(MIN_VALUE), computedStatistics.get(MAX_VALUE), result); } if (computedStatistics.containsKey(NUMBER_OF_DISTINCT_VALUES)) { result.setDistinctValuesCount(BIGINT.getLong(computedStatistics.get(NUMBER_OF_DISTINCT_VALUES), 0)); } if (computedStatistics.containsKey(NUMBER_OF_NON_NULL_VALUES)) { result.setNullsCount(rowCount - BIGINT.getLong(computedStatistics.get(NUMBER_OF_NON_NULL_VALUES), 0)); } if (computedStatistics.containsKey(NUMBER_OF_TRUE_VALUES) && computedStatistics.containsKey(NUMBER_OF_NON_NULL_VALUES)) { long numberOfTrue = BIGINT.getLong(computedStatistics.get(NUMBER_OF_TRUE_VALUES), 0); long numberOfNonNullValues = BIGINT.getLong(computedStatistics.get(NUMBER_OF_NON_NULL_VALUES), 0); result.setBooleanStatistics(new BooleanStatistics(OptionalLong.of(numberOfTrue), OptionalLong.of(numberOfNonNullValues - numberOfTrue))); } return result.build(); }
Source:
<code>public VSizeIndexedWriter( IOPeon ioPeon, String filenameBase, int maxId ) { this.ioPeon = ioPeon; <START> this.metaFileName = StringUtils.safeFormat("%s.meta", filenameBase); <END> this.headerFileName = StringUtils.safeFormat("%s.header", filenameBase); this.valuesFileName = StringUtils.safeFormat("%s.values", filenameBase); this.maxId = maxId; }</code><technical_language>crash if bad format string</technical_language>

Target:
public VSizeIndexedWriter( IOPeon ioPeon, String filenameBase, int maxId ) { this.ioPeon = ioPeon; this.metaFileName = StringUtils.format("%s.meta", filenameBase); this.headerFileName = StringUtils.format("%s.header", filenameBase); this.valuesFileName = StringUtils.format("%s.values", filenameBase); this.maxId = maxId; }
Source:
<code>public List<RichGroup> convertGroupsToRichGroupsWithAttributes(PerunSession sess, List<Group> groups) throws InternalErrorException { List<RichGroup> richGroups = new ArrayList<>(); <START> for(Group group: groups) <END> richGroups.add(new RichGroup(group, this.getPerunBl().getAttributesManagerBl().getAttributes(sess, group))); return richGroups; }</code><technical_language>if is 1 row in "for cyclus" i prefer '{' '}' for reading</technical_language>

Target:
public List<RichGroup> convertGroupsToRichGroupsWithAttributes(PerunSession sess, List<Group> groups) throws InternalErrorException { List<RichGroup> richGroups = new ArrayList<>(); for(Group group: groups) { richGroups.add(new RichGroup(group, this.getPerunBl().getAttributesManagerBl().getAttributes(sess, group))); } return richGroups; }
Source:
<code>public String format(Object o) { Annotation anno = (Annotation) o; StringBuilder result = new StringBuilder(); result.append("@" + annotationDef.name); if (anno.fieldValues.size() == 1 && anno.fieldValues.containsKey("value")) { AnnotationFieldType fieldType = annotationDef.fieldTypes.get("value"); result.append('('); result.append(fieldType.format(anno.fieldValues.get(anno.fieldValues.get("value")))); result.append(')'); } else if (anno.fieldValues.size() > 0) { result.append('('); <START> boolean notfirst = false; <END> for (Entry<String, Object> field : anno.fieldValues.entrySet()) { if (notfirst) { result.append(", "); } else { notfirst = true; } result.append(field.getKey() + "="); AnnotationFieldType fieldType = annotationDef.fieldTypes.get(field.getKey()); result.append(fieldType.format(field.getValue())); } result.append(')'); } return result.toString(); }</code><technical_language>a positive variable is easier understand a negated one</technical_language>

Target:
public String format(Object o) { Annotation anno = (Annotation) o; return anno.toString(); }
Source:
<code>void removeLogsDirectory() { String logsLocation = getLogsLocation(); logger.info("Removing logs " + logsLocation); while (!org.apache.commons.io.FileUtils.deleteQuietly(new File(logsLocation))) { logger.warn("Could not delete folder " + logsLocation + " retrying"); try { Thread.sleep(1000); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> } } }</code><technical_language>mistake, InterruptedException catched while</technical_language>

Target:
void removeLogsDirectory() { String logsLocation = getLogsLocation(); logger.info("Removing logs " + logsLocation); FileUtils.removeDir(new File(logsLocation)); }
Source:
<code>public int[] getAcceptableTokens() { return new int[] { TokenTypes.LAMBDA, <START> }; <END> }</code><technical_language>duplicate tokens, re-call getRequiredTokens</technical_language>

Target:
public int[] getAcceptableTokens() { return getRequiredTokens(); }
Source:
<code>public List<Annotation> getQualifiers() { return new ArrayList<Annotation>( <START> Arrays.asList(new org.jboss.arquillian.warp.servlet.AfterServlet() { <END> @Override public Class<? extends Annotation> annotationType () { return org.jboss.arquillian.warp.servlet.AfterServlet.class; } } ) ); }</code><technical_language>I return Arrays.asList(...) directly, need create wrap in ArrayList</technical_language>

Target:
public List<Annotation> getQualifiers() { return Arrays.asList((Annotation) new org.jboss.arquillian.warp.servlet.AfterServlet() { @Override public Class<? extends Annotation> annotationType () { return org.jboss.arquillian.warp.servlet.AfterServlet.class; } } ); }
Source:
<code>public void assignConsumerForSubscription(Subscription subscription) { logger.info("Creating consumer for {}", subscription.getId()); try { Consumer consumer = consumerFactory.createConsumer(subscription); logger.info("Created consumer for {}", subscription.getId()); backgroundProcess.accept(Signal.of(Signal.SignalType.START, subscription.toSubscriptionName(), consumer)); if (subscription.getState() == PENDING) { subscriptionRepository.updateSubscriptionState(subscription.getTopicName(), subscription.getName(), ACTIVE); } logger.info("Consumer for was added for execution", subscription.getId()); } catch (Exception ex) { <START> logger.warn("Failed to create consumer for subscription {}", subscription.getId(), ex); <END> } }</code><technical_language>I vote for making ERROR level message</technical_language>

Target:
public void assignConsumerForSubscription(Subscription subscription) { logger.info("Creating consumer for {}", subscription.getQualifiedName()); try { Consumer consumer = consumerFactory.createConsumer(subscription); logger.info("Created consumer for {}", subscription.getQualifiedName()); backgroundProcess.accept(Signal.of(Signal.SignalType.START, subscription.getQualifiedName(), consumer)); if (subscription.getState() == PENDING) { subscriptionRepository.updateSubscriptionState(subscription.getTopicName(), subscription.getName(), ACTIVE); } logger.info("Consumer for was added for execution", subscription.getQualifiedName()); } catch (Exception ex) { logger.error("Failed to create consumer for subscription {}", subscription.getQualifiedName(), ex); } }
Source:
<code>public void init() { logger.info("initializing CallbackHandler: {}, content: ", _uid, getContent()); if (_batchModeEnabled) { CallbackProcessor callbackProcessorRef = _batchCallbackProcessor.get(); if (callbackProcessorRef != null) { callbackProcessorRef.resetEventQueue(); } else { callbackProcessorRef = new CallbackProcessor(this); if (_batchCallbackProcessor.compareAndSet(null, callbackProcessorRef)) { <START> callbackProcessorRef.start(); <END> } else { callbackProcessorRef.shutdown(); } } } updateNotificationTime(System.nanoTime()); try { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(NotificationContext.Type.INIT); changeContext.setChangeType(_changeType); _ready = true; invoke(changeContext); } catch (Exception e) { String msg = "Exception while invoking init callback for listener:" + _listener; ZKExceptionHandler.getInstance().handle(msg, e); } }</code><technical_language>Consider operation order: 1. init() reset() is called time. 2. In init(), code reaches line 652, start yet. 3. time, in reset(), code reaches line 776, shutdown thread. cannot, thread started yet. Note, in java doc, "Interrupting a thread is alive need effect." 4. code in init() try start, thread is started. a leaked thread, eventually</technical_language>

Target:
public void init() { logger.info("initializing CallbackHandler: {}, content: ", _uid, getContent()); if (_batchModeEnabled) { CallbackProcessor callbackProcessor = _batchCallbackProcessorRef.get(); if (callbackProcessor != null) { callbackProcessor.resetEventQueue(); } else { callbackProcessor = new CallbackProcessor(this); callbackProcessor.start(); if (!_batchCallbackProcessorRef.compareAndSet(null, callbackProcessor)) { callbackProcessor.shutdown(); } } } updateNotificationTime(System.nanoTime()); try { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(NotificationContext.Type.INIT); changeContext.setChangeType(_changeType); _ready = true; invoke(changeContext); } catch (Exception e) { String msg = "Exception while invoking init callback for listener:" + _listener; ZKExceptionHandler.getInstance().handle(msg, e); } }
Source:
<code>protected void log() { <START> final Transaction transaction = TransactionSupport.suspend(); <END> try { try { auditLogDirector.log(this, getAuditLogTypeValue()); } catch (final RuntimeException ex) { log.error("Error during log command: {}. Exception {}", getClass().getName(), ex.getMessage()); log.debug("Exception", ex); } } finally { TransactionSupport.resume(transaction); } }</code><technical_language>more readable TransactionSupport.executeInNewTransaction() instead of code same</technical_language>

Target:
protected void log() { final Transaction transaction = TransactionSupport.suspend(); try { auditLogDirector.log(this, getAuditLogTypeValue()); } catch (final RuntimeException ex) { log.error("Error during log command: {}. Exception {}", getClass().getName(), ex.getMessage()); log.debug("Exception", ex); } finally { TransactionSupport.resume(transaction); } }
Source:
<code>public List<WorkflowAction> findAvailableDefaultActionsByContentType(ContentType contentType, User user) throws DotDataException, DotSecurityException { DotPreconditions.isTrue(this.permissionAPI. doesUserHavePermission(contentType, PermissionAPI.PERMISSION_READ, user, true), () -> "User " + user + " cannot read content type " + contentType.name(), DotSecurityException.class); List<WorkflowScheme> schemes = findSchemesForContentType(contentType); if (!hasValidLicense()) { final WorkflowScheme systemWorkflow = schemes.stream() .filter(WorkflowScheme::isSystemWorkflowScheme).findFirst() .orElse(workFlowFactory.findSystemWorkflow()); <START> schemes = new ImmutableList.Builder<WorkflowScheme>().add(systemWorkflow).build(); <END> } return findAvailableDefaultActionsBySchemes(schemes, APILocator.getUserAPI().getSystemUser()); }</code><technical_language>I a bit more efficient if do if (!hasValidLicense()) { //When License, allow system workflow return new ImmutableList.Builder<WorkflowScheme>().add(workFlowFactory.findSystemWorkflow()).build(); } final List<WorkflowScheme> schemes = findSchemesForContentType(contentType); ...</technical_language>

Target:
public List<WorkflowAction> findAvailableDefaultActionsByContentType(ContentType contentType, User user) throws DotDataException, DotSecurityException { DotPreconditions.isTrue(this.permissionAPI. doesUserHavePermission(contentType, PermissionAPI.PERMISSION_READ, user, true), () -> "User " + user + " cannot read content type " + contentType.name(), DotSecurityException.class); List<WorkflowScheme> schemes = findSchemesForContentType(contentType); if (!hasValidLicense()) { final WorkflowScheme systemWorkflow = schemes.stream() .filter(WorkflowScheme::isSystem).findFirst() .orElse(workFlowFactory.findSystemWorkflow()); schemes = new ImmutableList.Builder<WorkflowScheme>().add(systemWorkflow).build(); } return findAvailableDefaultActionsBySchemes(schemes, APILocator.getUserAPI().getSystemUser()); }
Source:
<code>public void review(final CertifiedProductSearchDetails listing) { for (CertificationResult cert : listing.getCertificationResults()) { if (cert.isSuccess()) { <START> if (cert.getTestToolsUsed() != null && cert.getTestToolsUsed().size() > 0) { <END> Iterator<CertificationResultTestTool> testToolIter = cert.getTestToolsUsed().iterator(); while (testToolIter.hasNext()) { CertificationResultTestTool testTool = testToolIter.next(); if (!StringUtils.isEmpty(testTool.getTestToolName())) { if (StringUtils.isEmpty(testTool.getTestToolVersion())) { if (listing.getIcs() != null && listing.getIcs().getInherits() != null && listing.getIcs().getInherits().booleanValue()) { listing.getWarningMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getTestToolName(), cert.getNumber())); } else { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getTestToolName(), cert.getNumber())); } } } } } } } }</code><technical_language>this previous line combined? reduce nesting</technical_language>

Target:
public void review(final CertifiedProductSearchDetails listing) { for (CertificationResult cert : listing.getCertificationResults()) { if (cert.isSuccess() && cert.getTestToolsUsed() != null && cert.getTestToolsUsed().size() > 0) { for (CertificationResultTestTool testTool : cert.getTestToolsUsed()) { if (!StringUtils.isEmpty(testTool.getTestToolName()) && StringUtils.isEmpty(testTool.getTestToolVersion())) { if (listing.getIcs() != null && listing.getIcs().getInherits() != null && listing.getIcs().getInherits().booleanValue()) { listing.getWarningMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getTestToolName(), cert.getNumber())); } else { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getTestToolName(), cert.getNumber())); } } } } } }
Source:
<code>private boolean handleMethodInvocation(Instruction instruction) { boolean isStatic = instruction.opcode == Opcodes.INVOKESTATIC; int arity = isStatic ? instruction.arity() : (instruction.arity() + 1); ProgramState.Pop pop = programState.unstackValue(arity); Preconditions.checkState(pop.values.size() == arity, "Arguments mismatch for INVOKE"); SymbolicValue returnSV = constraintManager.createSymbolicValue(instruction); if (isStatic) { String signature = instruction.fieldOrMethod.completeSignature(); MethodBehavior methodInvokedBehavior = behaviorCache.get(signature); if (methodInvokedBehavior != null && methodInvokedBehavior.isComplete()) { methodInvokedBehavior .happyPathYields() .forEach(yield -> yield.statesAfterInvocation(Lists.reverse(pop.values), Collections.emptyList(), pop.state, () -> returnSV).forEach(ps -> { checkerDispatcher.methodYield = yield; checkerDispatcher.addTransition(ps); <START> checkerDispatcher.methodYield = null; <END> })); methodInvokedBehavior .exceptionalPathYields() .forEach(yield -> yield.statesAfterInvocation( Lists.reverse(pop.values), Collections.emptyList(), pop.state, () -> constraintManager.createExceptionalSymbolicValue(yield.exceptionType())).forEach(ps -> { ps.storeExitValue(); enqueue(new ProgramPoint(exitBlock), ps); })); return true; } } if (instruction.hasReturnValue()) { programState = pop.state; } else { programState = pop.state.stackValue(returnSV); } return false; }</code><technical_language>matter of taste style I tend prefer : programState = pop.state; if(!instruction.hasReturnValue()) { programState = programeState.stackValue(returnSV); } branch..</technical_language>

Target:
private boolean handleMethodInvocation(Instruction instruction) { boolean isStatic = instruction.opcode == Opcodes.INVOKESTATIC; int arity = isStatic ? instruction.arity() : (instruction.arity() + 1); ProgramState.Pop pop = programState.unstackValue(arity); Preconditions.checkState(pop.values.size() == arity, "Arguments mismatch for INVOKE"); SymbolicValue returnSV = constraintManager.createSymbolicValue(instruction); if (isStatic) { String signature = instruction.fieldOrMethod.completeSignature(); MethodBehavior methodInvokedBehavior = behaviorCache.get(signature); if (methodInvokedBehavior != null && methodInvokedBehavior.isComplete()) { methodInvokedBehavior .happyPathYields() .forEach(yield -> yield.statesAfterInvocation(Lists.reverse(pop.values), Collections.emptyList(), pop.state, () -> returnSV).forEach(ps -> { checkerDispatcher.methodYield = yield; checkerDispatcher.addTransition(ps); checkerDispatcher.methodYield = null; })); methodInvokedBehavior .exceptionalPathYields() .forEach(yield -> yield.statesAfterInvocation( Lists.reverse(pop.values), Collections.emptyList(), pop.state, () -> constraintManager.createExceptionalSymbolicValue(yield.exceptionType())).forEach(ps -> { ps.storeExitValue(); enqueue(new ProgramPoint(exitBlock), ps); })); return true; } } programState = pop.state; if (instruction.hasReturnValue()) { programState = programState.stackValue(returnSV); } return false; }
Source:
<code>public static <RT> ErrorHandler<RT> get(Logger logger) { <START> return new WarningErrorHandler<RT>(logger); <END> }</code><technical_language>I this is error: return instance of ExceptionLogHandler, of WarningErrorHandler</technical_language>

Target:
public static <RT> ErrorHandler<RT> get(Logger logger) { return new ExceptionLogHandler<RT>(logger); }
Source:
<code>public static void testComparator() { final LogEntry logEntry1 = new LogEntry(100, LogType.FOUND_IT, "logEntry1 is older than logEntry2"); final LogEntry logEntry2 = new LogEntry(200, LogType.FOUND_IT, "logEntry2 is more recent than logEntry1"); final List<LogEntry> logList = new ArrayList<>(2); logList.add(logEntry1); logList.add(logEntry2); Collections.sort(logList, LogEntry.DESCENDING_DATE_COMPARATOR); <START> assertThat(logList).hasSize(2); <END> assertThat(logList.get(0)).isEqualTo(logEntry2); assertThat(logList.get(1)).isEqualTo(logEntry1); }</code><technical_language>written assertThat(logList).containsExactly(logEntry2, logEntry1). 3 previous checks once. :) I admit I more advanced assertions myself..</technical_language>

Target:
public static void testComparator() { final LogEntry logEntry1 = new LogEntry(100, LogType.FOUND_IT, "logEntry1 is older than logEntry2"); final LogEntry logEntry2 = new LogEntry(200, LogType.FOUND_IT, "logEntry2 is more recent than logEntry1"); final List<LogEntry> logList = new ArrayList<>(2); logList.add(logEntry1); logList.add(logEntry2); Collections.sort(logList, LogEntry.DESCENDING_DATE_COMPARATOR); assertThat(logList).containsExactly(logEntry2, logEntry1); }
Source:
<code>public void testfromSerialized() { TestProperties props = (TestProperties) new TestProperties("test") { @Override public boolean postDeserialize(int version, boolean persistent) { date.setTaggedValue("foo", "bar" + version); return false; } }; props.init(); String s = props.toSerialized(); <START> assertNotEquals("bar", props.date.getTaggedValue("foo")); <END> TestProperties desProp = Properties.Helper.fromSerialized(s, TestProperties.class).object; assertEquals("bar0", desProp.date.getTaggedValue("foo")); }</code><technical_language>do a negative check for "bar0" check deserialization</technical_language>

Target:
public void testfromSerialized() { TestProperties props = (TestProperties) new TestProperties("test") { @Override public boolean postDeserialize(int version, PostDeserializeSetup setup, boolean persistent) { date.setTaggedValue("foo", "bar" + version); return super.postDeserialize(version, setup, persistent); } }; props.init(); String s = props.toSerialized(); assertNull(props.date.getTaggedValue("foo")); TestProperties desProp = Properties.Helper.fromSerializedPersistent(s, TestProperties.class).object; assertEquals("bar0", desProp.date.getTaggedValue("foo")); }
Source:
<code>public void onBecomeStandbyFromLeader(Message message, NotificationContext context) { <START> logger.info("++Becoming STANDBY from LEADER"); <END> }</code><technical_language>Is a convention ++</technical_language>

Target:
public void onBecomeStandbyFromLeader(Message message, NotificationContext context) { logger.info("Becoming STANDBY from LEADER"); }
Source:
<code>public String getUrlForWiki(String wikiName, String language, boolean addWWW, EnvType envType) { final String wikiaName = getWikiaGlobalName(wikiName); String www = ""; if (addWWW) { www = "www."; } String host; HttpUrl.Builder urlBuilder = new HttpUrl.Builder(); switch (envType) { case DEV: { String devBoxOwner = this.env.split("-")[1]; host = String.join(".", www + wikiaName, devBoxOwner, envType.getWikiaDomain()); break; } case PROD: { host = String.join(".", www + wikiaName, envType.getWikiaDomain()); break; } case STAGING: { host = String.join(".", www + wikiaName, envType.getWikiaDomain()); break; } case SANDBOX: { host = String.join(".", www + wikiaName, this.env, envType.getWikiaDomain()); break; } default: throw new WebDriverException("Unknown environment type"); } urlBuilder.scheme(getUrlProtocol()).host(host); if (language != null && !("en").equals(language)) { <START> urlBuilder.addPathSegments(language); <END> } return urlBuilder.build().toString(); }</code><technical_language>need option run language format (as a subdomain)</technical_language>

Target:
public String getUrlForWiki(String wikiName, String language, boolean addWWW, EnvType envType) { final String wikiaName = getWikiaGlobalName(wikiName); if (language == null || wikiName == null) throw new NullPointerException("Wikia name and language are required"); HttpUrl.Builder urlBuilder = new HttpUrl.Builder(); String www = addWWW ? "www." : ""; String host = getFormattedWikiHost(www, wikiaName, envType, language); if (!("en").equals(language) && forceLanguageInPath) { urlBuilder.addEncodedPathSegments(language); } return urlBuilder.scheme(getUrlProtocol()).host(host).build().toString().replaceFirst("/$",""); }
Source:
<code>public void actionPerformed(ActionEvent e) { eventLogger.log(this); final Map<String, String> parameters = e.getParameters(); if (parameters != null && !parameters.isEmpty()) { final ProjectConfigDto dataObject = dtoFactory.createDto(ProjectConfigDto.class); if (parameters.containsKey("projectName")) { dataObject.setName(parameters.get("projectName")); } if (parameters.containsKey("projectType")) { dataObject.setType(parameters.get("projectType")); } else { <START> dataObject.setType("blank"); <END> } wizard.show(dataObject, CREATE); } else { wizard.show(); } }</code><technical_language>org.eclipse.che.api.project.shared.Constants#BLANK_ID instead of hardcoded string</technical_language>

Target:
public void actionPerformed(ActionEvent e) { eventLogger.log(this); final Map<String, String> parameters = e.getParameters(); if (parameters != null && !parameters.isEmpty()) { final ProjectConfigDto dataObject = dtoFactory.createDto(ProjectConfigDto.class); if (parameters.containsKey("projectName")) { dataObject.setName(parameters.get("projectName")); } if (parameters.containsKey("projectType")) { dataObject.setType(parameters.get("projectType")); } else { dataObject.setType(BLANK_ID); } wizard.show(dataObject, CREATE); } else { wizard.show(); } }
Source:
<code>public void init(FilterConfig filterConfig) throws ServletException { controller = new Controller(); <START> Framework.getRuntime().getComponentManager().addListener(new ComponentManager.LifeCycleHandler() { <END> @Override public void beforeStop(ComponentManager mgr, boolean isStandby) { controller.onStandby(); } @Override public void afterStart(ComponentManager mgr, boolean isResume) { controller.onResumed(); } }); }</code><technical_language>install()</technical_language>

Target:
public void init(FilterConfig filterConfig) throws ServletException { controller = new Controller(); new ComponentManager.LifeCycleHandler() { @Override public void beforeStop(ComponentManager mgr, boolean isStandby) { controller.onStandby(); } @Override public void afterStart(ComponentManager mgr, boolean isResume) { controller.onResumed(); } }.install(); }
Source:
<code>public GaussianDistribution asGaussian() { <START> GaussianDistribution gaussian = new GaussianDistribution(this.mean,this.sigma,this.alpha,this.beta,GaussianDistribution.DistributionModel.from_value(this.model_type)); <END> return gaussian; }</code><technical_language>return line final</technical_language>

Target:
public GaussianDistribution asGaussian() { return new GaussianDistribution(this.mean,this.sigma,this.alpha,this.beta,this.kappa,this.modelType); }
Source:
<code>public static ValueAttributesInfo fromMap(Map<String, String> attributes, Optional<ObjectMapper> mapper) { <START> return mapper.orElseGet(() -> new ObjectMapper()).convertValue(attributes, ValueAttributesInfo.class); <END> }</code><technical_language>suggestion return mapper.orElseGet(ObjectMapper::new).convertValue(attributes, ValueAttributesInfo.class);</technical_language>

Target:
public static ValueAttributesInfo fromMap(Map<String, String> attributes, Optional<ObjectMapper> mapper) { return mapper.orElseGet(ObjectMapper::new).convertValue(attributes, ValueAttributesInfo.class); }
Source:
<code>public static String asEqualsPattern(String string) { <START> return StringUtils.isNotEmpty(string) ? String.format("%s", string) : ""; <END> }</code><technical_language>return StringUtils.defaultString(string);</technical_language>

Target:
public static String asEqualsPattern(String string) { return StringUtils.defaultString(string); }
Source:
<code>public CreateResponse create(CreateRequest createRequest) throws IngestException, SourceUnavailableException { <START> INGEST_LOGGER.info("Resource ingest has started."); <END> CreateResponse createResponse = doCreate(createRequest); createResponse = doPostIngest(createResponse); INGEST_LOGGER.info("Resource ingest has completed."); return createResponse; }</code><technical_language>useful this generic? Resource ingest started for '{}'</technical_language>

Target:
public CreateResponse create(CreateRequest createRequest) throws IngestException, SourceUnavailableException { CreateResponse createResponse = doCreate(createRequest); createResponse = doPostIngest(createResponse); return createResponse; }
Source:
<code>private void addOutliers() throws IOException { <START> Configuration conf = new Configuration(); <END> for (Entry<Object, Object> pair : props.entrySet()) { String key = (String) pair.getKey(); conf.set(key, (String) pair.getValue()); } for (Properties jobProps : planner.getOutlierProperties()) { this.executorService.submit(new OutlierCollectorRunner(jobProps, FileSystem.get(conf))); } }</code><technical_language>If CamusSweeper extends Configured, get a Configuration getConf()</technical_language>

Target:
private void addOutliers() throws IOException { createExecutorService(); List<Future<?>> futures = new ArrayList<Future<?>>(); for (Properties jobProps : planner.getOutlierProperties()) { futures.add(this.executorService.submit(new OutlierCollectorRunner(jobProps, FileSystem.get(getConf())))); } this.executorService.shutdown(); for (Future<?> future : futures) { try { future.get(); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
Source:
<code>private void assertResultSerializable(Result result) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); <START> ObjectOutputStream objectoutputstream = new ObjectOutputStream(byteArrayOutputStream); <END> objectoutputstream.writeObject(result); objectoutputstream.flush(); byte[] bytes = byteArrayOutputStream.toByteArray(); ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); Result fromStream = (Result) objectInputStream.readObject(); assertSerializedCorrectly(result, fromStream); InputStream resource = getClass().getResourceAsStream(getName()); assertNotNull("Could not read resource " + getName(), resource); objectInputStream = new ObjectInputStream(resource); fromStream = (Result) objectInputStream.readObject(); assertSerializedCorrectly(new ResultWithFixedRunTime(result), fromStream); }</code><technical_language>Please rename objectoutputstream camelcase naming</technical_language>

Target:
private void assertResultSerializable(Result result) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(result); objectOutputStream.flush(); byte[] bytes = byteArrayOutputStream.toByteArray(); ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); Result fromStream = (Result) objectInputStream.readObject(); assertSerializedCorrectly(result, fromStream); InputStream resource = getClass().getResourceAsStream(getName()); assertNotNull("Could not read resource " + getName(), resource); objectInputStream = new ObjectInputStream(resource); fromStream = (Result) objectInputStream.readObject(); assertSerializedCorrectly(new ResultWithFixedRunTime(result), fromStream); }
Source:
<code>private Pool getDevPool(Consumer consumer, String sku) { PoolFilterBuilder poolFilters = new PoolFilterBuilder(); <START> poolFilters.addAttributeFilter(Pool.REQUIRES_CONSUMER_ATTRIBUTE, consumer.getUuid()); <END> Page<List<Pool>> poolsPage = poolManager.listAvailableEntitlementPools(consumer, null, consumer.getOwner(), null, null, true, true, poolFilters, null); if (poolsPage != null && poolsPage.getPageData() != null && poolsPage.getPageData().size() == 1) { return poolsPage.getPageData().get(0); } else { return null; } }</code><technical_language>filter dev pool type in case consumer specific restriction again</technical_language>

Target:
private Pool getDevPool(Consumer consumer, String sku) { PoolFilterBuilder poolFilters = new PoolFilterBuilder(); poolFilters.addAttributeFilter(Pool.REQUIRES_CONSUMER_ATTRIBUTE, consumer.getUuid()); poolFilters.addAttributeFilter(Pool.DEVELOPMENT_POOL_ATTRIBUTE, "true"); Page<List<Pool>> poolsPage = poolManager.listAvailableEntitlementPools(consumer, null, consumer.getOwner(), null, null, true, true, poolFilters, null); if (poolsPage != null && poolsPage.getPageData() != null && poolsPage.getPageData().size() == 1) { return poolsPage.getPageData().get(0); } else { return null; } }
Source:
<code>public void can_compare_after_writes() { interval = IntervalPersisterTest.createRandomInterval(); interval.close(); persister.save(interval); WatchDogItem savedItem = new ArrayList<>(persister.readItems()) .get(0); assertTrue(savedItem instanceof IntervalBase); IntervalBase savedInterval = (IntervalBase) savedItem; assertEquals(interval.getType(), savedInterval.getType()); assertEquals(interval.getStart(), savedInterval.getStart()); assertEquals(interval.getEnd(), savedInterval.getEnd()); assertEquals(interval.getDuration(), savedInterval.getDuration()); assertEquals(interval.isClosed(), savedInterval.isClosed()); <START> assertEquals(savedInterval.getType(), savedInterval.getType()); <END> assertEquals(savedInterval.getStart(), savedInterval.getStart()); assertEquals(savedInterval.getEnd(), savedInterval.getEnd()); assertEquals(interval.getDuration(), savedInterval.getDuration()); assertEquals(interval.isClosed(), savedInterval.isClosed()); }</code><technical_language>This assert fail</technical_language>

Target:
public void can_compare_after_writes() { IntervalBase interval = IntervalPersisterTest.createRandomInterval(); interval.close(); persister.save(interval); WatchDogItem savedItem = new ArrayList<>(persister.readItems()) .get(0); assertTrue(savedItem instanceof IntervalBase); IntervalBase savedInterval = (IntervalBase) savedItem; assertEquals(interval.getType(), savedInterval.getType()); assertEquals(interval.getStart(), savedInterval.getStart()); assertEquals(interval.getEnd(), savedInterval.getEnd()); assertEquals(interval.getDuration(), savedInterval.getDuration()); assertEquals(interval.isClosed(), savedInterval.isClosed()); }
Source:
<code>public static OnmsTopologyVertex create(String id, String label, String address, String iconKey) { <START> return new OnmsTopologyVertex(Objects.requireNonNull(id, "id is null, cannot create vertex"), label, address, <END> iconKey); }</code><technical_language>put Objects.requireNonNull(...) beginning of method? This easier read</technical_language>

Target:
public static OnmsTopologyVertex create(String id, String label, String address, String iconKey) { Objects.requireNonNull(id, "id is null, cannot create vertex"); return new OnmsTopologyVertex(id, label, address, iconKey); }
Source:
<code>private void firePropertyChange(final PropertyChangeEvent event) { Object[] allListeners = listeners.getListeners(); for <START> (Object allListener : <END> allListeners) { final IPropertyChangeListener listener = (IPropertyChangeListener) allListener; SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { listener.propertyChange(event); } @Override public void handleException(Throwable exception) { } }); } }</code><technical_language>listener</technical_language>

Target:
private void firePropertyChange(final PropertyChangeEvent event) { Object[] allListeners = listeners.getListeners(); for (Object l : allListeners) { final IPropertyChangeListener listener = (IPropertyChangeListener)l; SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { listener.propertyChange(event); } @Override public void handleException(Throwable exception) { } }); } }
Source:
<code>public boolean fetch() throws IOException { if (currentOffset >= lastOffset) { return false; } long tempTime = System.currentTimeMillis(); TopicAndPartition topicAndPartition = new TopicAndPartition(kafkaRequest.getTopic(), kafkaRequest.getPartition()); log.debug("\nAsking for offset : " + (currentOffset)); PartitionFetchInfo partitionFetchInfo = new PartitionFetchInfo(currentOffset, fetchBufferSize); HashMap<TopicAndPartition, PartitionFetchInfo> fetchInfo = new HashMap<TopicAndPartition, PartitionFetchInfo>(); fetchInfo.put(topicAndPartition, partitionFetchInfo); FetchRequest fetchRequest = new FetchRequest(CamusJob.getKafkaFetchRequestCorrelationId(context), CamusJob.getKafkaClientName(context), CamusJob.getKafkaFetchRequestMaxWait(context), CamusJob.getKafkaFetchRequestMinBytes(context), fetchInfo); FetchResponse fetchResponse = null; try { fetchResponse = simpleConsumer.fetch(fetchRequest); if (fetchResponse.hasError()) { <START> throw new RuntimeException(); <END> } return processFetchResponse(fetchResponse, tempTime); } catch (Exception e) { log.info("Exception generated during fetch for topic " + kafkaRequest.getTopic() + ". Will refresh topic metadata and retry."); return refreshTopicMetadataAndRetryFetch(fetchRequest, tempTime); } }</code><technical_language>exception some error messages</technical_language>

Target:
public boolean fetch() throws IOException { if (currentOffset >= lastOffset) { return false; } long tempTime = System.currentTimeMillis(); TopicAndPartition topicAndPartition = new TopicAndPartition(kafkaRequest.getTopic(), kafkaRequest.getPartition()); log.debug("\nAsking for offset : " + (currentOffset)); PartitionFetchInfo partitionFetchInfo = new PartitionFetchInfo(currentOffset, fetchBufferSize); HashMap<TopicAndPartition, PartitionFetchInfo> fetchInfo = new HashMap<TopicAndPartition, PartitionFetchInfo>(); fetchInfo.put(topicAndPartition, partitionFetchInfo); FetchRequest fetchRequest = new FetchRequest(CamusJob.getKafkaFetchRequestCorrelationId(context), CamusJob.getKafkaClientName(context), CamusJob.getKafkaFetchRequestMaxWait(context), CamusJob.getKafkaFetchRequestMinBytes(context), fetchInfo); FetchResponse fetchResponse = null; try { fetchResponse = simpleConsumer.fetch(fetchRequest); if (fetchResponse.hasError()) { String message = "Error Code generated : " + fetchResponse.errorCode(kafkaRequest.getTopic(), kafkaRequest.getPartition()) + "\n"; throw new RuntimeException(message); } return processFetchResponse(fetchResponse, tempTime); } catch (Exception e) { log.info("Exception generated during fetch for topic " + kafkaRequest.getTopic() + ": " + e.getMessage() + ". Will refresh topic metadata and retry."); return refreshTopicMetadataAndRetryFetch(fetchRequest, tempTime); } }
Source:
<code>protected ProcessBuilder createProcessBuilder(String homeDirectory) { ProcessBuilder pb = new ProcessBuilder(homeDirectory + "/bin/storm","logviewer"); <START> File log = new File(homeDirectory + "/logs/logviewer-startup.log"); <END> pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(log)); return pb; }</code><technical_language>Is some Path.join() instead? more idiomatic</technical_language>

Target:
protected ProcessBuilder createProcessBuilder(String homeDirectory) { ProcessBuilder pb = new ProcessBuilder(Paths.get(homeDirectory, "/bin/storm").toString(), "logviewer"); File log = Paths.get(homeDirectory, "/logs/logviewer-startup.log").toFile(); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(log)); return pb; }
Source:
<code><START> static KubernetesClient createClient(KubernetesCloud cloud) throws Exception { <END> String displayName = cloud.getDisplayName(); final Client c = clients.getIfPresent(displayName); if (c == null) { KubernetesClient client = new KubernetesFactoryAdapter(cloud.getServerUrl(), cloud.getNamespace(), cloud.getServerCertificate(), cloud.getCredentialsId(), cloud.isSkipTlsVerify(), cloud.getConnectTimeout(), cloud.getReadTimeout(), cloud.getMaxRequestsPerHost()).createClient(); clients.put(displayName, new Client(getValidity(cloud), client)); LOGGER.log(Level.INFO, "Created new Kubernetes client: {0} {1}", new Object[] { displayName, client }); return client; } return c.getClient(); }</code><technical_language>specialised exceptions, I guess this throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, IOException, CertificateEncodingException, KubernetesAuthException</technical_language>

Target:
static KubernetesClient createClient(KubernetesCloud cloud) throws KubernetesAuthException, IOException { String displayName = cloud.getDisplayName(); final Client c = clients.getIfPresent(displayName); if (c == null) { KubernetesClient client = new KubernetesFactoryAdapter(cloud.getServerUrl(), cloud.getNamespace(), cloud.getServerCertificate(), cloud.getCredentialsId(), cloud.isSkipTlsVerify(), cloud.getConnectTimeout(), cloud.getReadTimeout(), cloud.getMaxRequestsPerHost()).createClient(); clients.put(displayName, new Client(getValidity(cloud), client)); LOGGER.log(Level.INFO, "Created new Kubernetes client: {0} {1}", new Object[] { displayName, client }); return client; } return c.getClient(); }
Source:
<code>default void onBeforeClass(ITestClass testClass) { <START> throw new UnsupportedOperationException("Method is not implemented"); <END> }</code><technical_language>this problems actual consumers? If a user decides build a listener implements IClassListener provides implementation for onAfterClass() exceptions for onBeforeClass. IMO throwing exceptions in default methods. please this removed in this listener interface</technical_language>

Target:
default void onBeforeClass(ITestClass testClass) { }
Source:
<code>public Observable<ResultsPage<Entity>> searchCollection( final CollectionSearch search ) { final ApplicationScope applicationScope = search.getApplicationScope(); final String collectionName = search.getCollectionName(); final Optional<String> query = search.getQuery(); final IdBuilder pipelineBuilder = pipelineBuilderFactory.create( applicationScope ) .withCursor( search.getCursor() ) .withLimit( search.getLimit() ) .keepStaleEntries(search.getKeepStaleEntries()) <START> .query(search.getQuery()) <END> .fromId( search.getCollectionOwnerId() ); final EntityBuilder results; if ( !query.isPresent()) { results = pipelineBuilder.traverseCollection( collectionName ).loadEntities(); } else { results = pipelineBuilder.searchCollection( collectionName, query.get(),search).loadEntities(); } return results.build(); }</code><technical_language>query(query)</technical_language>

Target:
public Observable<ResultsPage<Entity>> searchCollection( final CollectionSearch search ) { final ApplicationScope applicationScope = search.getApplicationScope(); final String collectionName = search.getCollectionName(); final Optional<String> query = search.getQuery(); final IdBuilder pipelineBuilder = pipelineBuilderFactory.create( applicationScope ) .withCursor( search.getCursor() ) .withLimit( search.getLimit() ) .keepStaleEntries(search.getKeepStaleEntries()) .query(query) .fromId( search.getCollectionOwnerId() ); final EntityBuilder results; if ( !query.isPresent()) { results = pipelineBuilder.traverseCollection( collectionName ).loadEntities(); } else { results = pipelineBuilder.searchCollection( collectionName, query.get(),search).loadEntities(); } return results.build(); }
Source:
<code>public void replacePopulations(List<T> main, List<T> temp){ for(int i=0; i<populationSize; i++){ T mainIndividual = main.get(i); T tempIndividual = temp.get(i); for (FitnessFunction<T> fitnessFunction : fitnessFunctions) { fitnessFunction.getFitness(mainIndividual); notifyEvaluation(mainIndividual); fitnessFunction.getFitness(tempIndividual); notifyEvaluation(tempIndividual); } <START> if(keepOffspring(mainIndividual, tempIndividual)){ <END> if (!(isTooLong(tempIndividual) || tempIndividual.size() == 0)){ main.set(i, tempIndividual); } } } }</code><technical_language>isBetterOrEqual method GeneticAlgorithm class</technical_language>

Target:
public void replacePopulations(List<T> main, List<T> temp){ assert main.size() == temp.size(); for(int i=0; i<Properties.POPULATION; i++){ T mainIndividual = main.get(i); T tempIndividual = temp.get(i); for (FitnessFunction<T> fitnessFunction : fitnessFunctions) { fitnessFunction.getFitness(mainIndividual); notifyEvaluation(mainIndividual); fitnessFunction.getFitness(tempIndividual); notifyEvaluation(tempIndividual); } if(isBetterOrEqual(mainIndividual, tempIndividual)){ if (!(isTooLong(tempIndividual) || tempIndividual.size() == 0)){ main.set(i, tempIndividual); } } } }
Source:
<code>protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = new DateTime(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); if (beginValidTime != null && endValidTime != null) { if (isConditionsDefaultValueEnabled()) { beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); } <START> if(beginValidTime.isBefore(endValidTime)) { <END> return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); } } return null; }</code><technical_language>Do need error out if beginValidTime.isBefore(endValidTime) met</technical_language>

Target:
protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = new DateTime(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); if (beginValidTime != null && endValidTime != null) { if (isConditionsDefaultValueEnabled() || beginValidTime.isAfter(endValidTime)) { beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); } return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); } return null; }
Source:
<code>public void testReadResolve() throws IOException { User user = User.get("User"); MyViewsProperty property = new MyViewsProperty(AllView.DEFAULT_VIEW_NAME); property.setUser(user); user.addProperty(property); property.readResolve(); <START> assertNotNull("Property should contain " + AllView.DEFAULT_VIEW_NAME + " default.", property.getView(AllView.DEFAULT_VIEW_NAME)); <END> }</code><technical_language>default</technical_language>

Target:
public void testReadResolve() throws IOException { User user = User.get("User"); MyViewsProperty property = new MyViewsProperty(AllView.DEFAULT_VIEW_NAME); property.setUser(user); user.addProperty(property); property.readResolve(); assertNotNull("Property should contain " + AllView.DEFAULT_VIEW_NAME + " by default.", property.getView(AllView.DEFAULT_VIEW_NAME)); }
Source:
<code><START> public String getResolvedAddress(String hostname) { <END> if (_resolvedAddress.isPresent()) return _resolvedAddress.get(); ProcessTaskWrapper<Integer> task = SshEffectorTasks.ssh("ping -c 1 -t 1 "+hostname).machine(getMachine()) .summary("checking resolution of "+hostname).allowingNonZeroExitCode().newTask(); DynamicTasks.queueIfPossible(task).orSubmitAndBlock(getEntity()).asTask().blockUntilEnded(); if (task.asTask().isError()) { log.warn("ping could not be run, at "+getEntity()+" / "+getMachine()+": "+Tasks.getError(task.asTask())); return ""; } if (task.getExitCode()==null || task.getExitCode()!=0) { if (task.getExitCode()!=null && task.getExitCode()<10) return (_resolvedAddress = Maybe.of((String)null)).get(); log.warn("ping not run as expected, at "+getEntity()+" / "+getMachine()+" (code "+task.getExitCode()+"):\n"+task.getStdout().trim()+" --- "+task.getStderr().trim()); return (_resolvedAddress = Maybe.of("")).get(); } String out = task.getStdout(); try { String line1 = Strings.getFirstLine(out); String ip = Strings.getFragmentBetween(line1, "(", ")"); if (Strings.isNonBlank(ip)) return (_resolvedAddress = Maybe.of(ip)).get(); } catch (Exception e) { } if (out.contains("127.0.0.1")) return (_resolvedAddress = Maybe.of("127.0.0.1")).get(); return (_resolvedAddress = Maybe.of("")).get(); }</code><technical_language>This generic can/should move some utility class (and write integration test for it)? Happy deferred, in this PR</technical_language>

Target:
public String getResolvedAddress(String hostname) { if (resolvedAddressCache.isPresent()) return resolvedAddressCache.get(); return (resolvedAddressCache = Maybe.of(BrooklynAccessUtils.getResolvedAddress(getEntity(), getMachine(), hostname))).get(); }