auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private SecurityGroup(SecurityGroup securityGroup) { <START> this( <END> securityGroup.id, securityGroup.tenantId, securityGroup.name, securityGroup.description, securityGroup.securityGroupRules ); }</code><technical_language>Formatting is a bit odd in this</technical_language>

Target:
private SecurityGroup(SecurityGroup securityGroup) { this(securityGroup.id, securityGroup.tenantId, securityGroup.name, securityGroup.description, securityGroup.rules ); }
Source:
<code><START> protected ExpressionRewriteRuleSet(ExpressionRewriteRule rewrite) <END> { this.rewriter = rewrite; }</code><technical_language>public</technical_language>

Target:
public ExpressionRewriteRuleSet(ExpressionRewriteRule rewrite) { this.rewriter = rewrite; }
Source:
<code><START> public static <E extends Exception> void assertException( ThrowingAction<E> f, Class typeOfException ) throws <END> Exception { try { f.apply(); fail( "Expected exception of type " + typeOfException + ", but no exception was thrown" ); } catch ( Exception e ) { if ( !typeOfException.isInstance( e ) ) { fail( "Got unexpected exception " + e.getClass() + "\nExpected: " + typeOfException ); } } }</code><technical_language>copy paste of another assertException method? reused that</technical_language>

Target:
public static <E extends Exception> void assertException( ThrowingAction<E> f, Class typeOfException ) throws Exception { assertException( f, typeOfException, null ); }
Source:
<code>private void trackAATestCourseOutline() { if (!isVideoMode && environment.getConfig().getFirebaseConfig().isEnabled()) { final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(task -> { final String group = firebaseRemoteConfig.getString(Analytics.Keys.AA_EXPERIMENT); <START> if (!TextUtils.isEmpty(group) && environment.getLoginPrefs().getCurrentUserProfile() != null) { <END> final Map<String, String> values = new HashMap<>(); values.put(Analytics.Keys.EXPERIMENT, Analytics.Keys.AA_EXPERIMENT); values.put(Analytics.Keys.GROUP, group); values.put(Analytics.Keys.USER_ID, environment.getLoginPrefs().getCurrentUserProfile().id.toString()); values.put(Analytics.Keys.COURSE_ID, courseData.getCourse().getId()); environment.getAnalyticsRegistry().trackExperimentParams(Analytics.Events.MOBILE_EXPERIMENT_EVALUATED, values); } }); } }</code><technical_language>environment.getLoginPrefs().getCurrentUserProfile() store in local variable it</technical_language>

Target:
private void trackAATestCourseOutline() { if (!isVideoMode && environment.getConfig().getFirebaseConfig().isEnabled()) { final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(task -> { final String group = firebaseRemoteConfig.getString(Analytics.Keys.AA_EXPERIMENT); final ProfileModel profileModel = environment.getLoginPrefs().getCurrentUserProfile(); if (!TextUtils.isEmpty(group) && profileModel != null) { final Map<String, String> values = new HashMap<>(); values.put(Analytics.Keys.EXPERIMENT, Analytics.Keys.AA_EXPERIMENT); values.put(Analytics.Keys.GROUP, group); values.put(Analytics.Keys.USER_ID, profileModel.id.toString()); values.put(Analytics.Keys.COURSE_ID, courseData.getCourse().getId()); environment.getAnalyticsRegistry().trackExperimentParams(Analytics.Events.MOBILE_EXPERIMENT_EVALUATED, values); } }); } }
Source:
<code>private void detachOrCloseSpans(HttpServletRequest request, HttpServletResponse response, Span spanFromRequest, Throwable exception) { if (spanFromRequest != null) { addResponseTags(response, exception); if (spanFromRequest.hasSavedSpan() && requestHasAlreadyBeenHandled(request)) { reportParentSpan(spanFromRequest.getSavedSpan()); } else if (!requestHasAlreadyBeenHandled(request)) { spanFromRequest = this.tracer.close(spanFromRequest); } <START> reportParentSpan(spanFromRequest); <END> if (httpStatusSuccessful(response)) { if (log.isDebugEnabled()) { log.debug("Closing the span " + spanFromRequest + " since the response was successful"); } this.tracer.close(spanFromRequest); } else if (errorAlreadyHandled(request)) { if (log.isDebugEnabled()) { log.debug( "Won't detach the span " + spanFromRequest + " since error has already been handled"); } } else { if (log.isDebugEnabled()) { log.debug("Detaching the span " + spanFromRequest + " since the response was unsuccessful"); } this.tracer.detach(spanFromRequest); } } }</code><technical_language>nit: record report. reporting asynchronously</technical_language>

Target:
private void detachOrCloseSpans(HttpServletRequest request, HttpServletResponse response, Span spanFromRequest, Throwable exception) { if (spanFromRequest != null) { addResponseTags(response, exception); if (spanFromRequest.hasSavedSpan() && requestHasAlreadyBeenHandled(request)) { recordParentSpan(spanFromRequest.getSavedSpan()); } else if (!requestHasAlreadyBeenHandled(request)) { spanFromRequest = this.tracer.close(spanFromRequest); } recordParentSpan(spanFromRequest); if (httpStatusSuccessful(response)) { if (log.isDebugEnabled()) { log.debug("Closing the span " + spanFromRequest + " since the response was successful"); } this.tracer.close(spanFromRequest); } else if (errorAlreadyHandled(request)) { if (log.isDebugEnabled()) { log.debug( "Won't detach the span " + spanFromRequest + " since error has already been handled"); } } else { if (log.isDebugEnabled()) { log.debug("Detaching the span " + spanFromRequest + " since the response was unsuccessful"); } this.tracer.detach(spanFromRequest); } } }
Source:
<code>private String addAttribute(KafkaMetric metric) { try { MetricName metricName = metric.metricName(); <START> if (metricName.tags().containsKey(DO_NOT_REPORT_TAG)) { return null; } <END> String mBeanName = getMBeanName(prefix, metricName); if (!this.mbeans.containsKey(mBeanName)) mbeans.put(mBeanName, new KafkaMbean(mBeanName)); KafkaMbean mbean = this.mbeans.get(mBeanName); mbean.setAttribute(metricName.name(), metric); return mBeanName; } catch (JMException e) { throw new KafkaException("Error creating mbean attribute for metricName :" + metric.metricName(), e); } }</code><technical_language>I convinced this. main issue other reporters report metric. If want report a metric, I need a solution works for reporters. elaborate more need here? I of alternatives: * add a flag sensor if reported not. * rely metrics create/store sensor a local reference</technical_language>

Target:
private String addAttribute(KafkaMetric metric) { try { MetricName metricName = metric.metricName(); String mBeanName = getMBeanName(prefix, metricName); if (!this.mbeans.containsKey(mBeanName)) mbeans.put(mBeanName, new KafkaMbean(mBeanName)); KafkaMbean mbean = this.mbeans.get(mBeanName); mbean.setAttribute(metricName.name(), metric); return mBeanName; } catch (JMException e) { throw new KafkaException("Error creating mbean attribute for metricName :" + metric.metricName(), e); } }
Source:
<code><START> private Map<String, String> getExtensionVersions() <END> { final Injector injector = Initialization.makeStartupInjector(); final ExtensionsConfig config = injector.getInstance(ExtensionsConfig.class); final List<DruidModule> druidModules = Initialization.getFromExtensions(config, DruidModule.class); Map<String, String> moduleVersions = new HashMap<>(); for (DruidModule module : druidModules) { Package pkg = module.getClass().getPackage(); moduleVersions.put(pkg.getImplementationTitle(), pkg.getImplementationVersion()); } return moduleVersions; }</code><technical_language>this method for CLI version info status servlet? code</technical_language>

Target:
private static List<ModuleVersion> getExtensionVersions() { final Injector injector = Initialization.makeStartupInjector(); final ExtensionsConfig config = injector.getInstance(ExtensionsConfig.class); final List<DruidModule> druidModules = Initialization.getFromExtensions(config, DruidModule.class); List<ModuleVersion> moduleVersions = new ArrayList<>(); for (DruidModule module : druidModules) { String artifact = module.getClass().getPackage().getImplementationTitle(); String version = module.getClass().getPackage().getImplementationVersion(); ModuleVersion moduleVersion; if (artifact != null) { moduleVersion = new ModuleVersion(module.getClass().getCanonicalName(), artifact, version); } else { moduleVersion = new ModuleVersion(module.getClass().getCanonicalName()); } moduleVersions.add(moduleVersion); } return moduleVersions; }
Source:
<code><START> private long createToken(Token token, String tokenType) { <END> try { return tokenDAO.create(token); } catch (Exception ex) { String msg = "Error linking " + tokenType + " account"; LOG.error(msg, ex); throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST); } }</code><technical_language>param a TokenType</technical_language>

Target:
private long createToken(Token token, String tokenType) { try { return tokenDAO.create(token); } catch (Exception ex) { String msg = "Error linking " + tokenType + " account"; LOG.error(msg, ex); throw new CustomWebApplicationException(msg, HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Source:
<code>public long copyStoreFiles( CatchupAddressProvider catchupAddressProvider, StoreId expectedStoreId, StoreFileStreams storeFileStreams, <START> Supplier<TerminationCondition> requestWiseTerminationCondition ) <END> throws StoreCopyFailedException { try { PrepareStoreCopyResponse prepareStoreCopyResponse = listFiles( catchupAddressProvider.primary(), expectedStoreId, storeFileStreams ); copyFilesIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); copyLuceneSnapshotIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); return prepareStoreCopyResponse.lastTransactionId(); } catch ( CatchupAddressResolutionException | CatchUpClientException e ) { throw new StoreCopyFailedException( e ); } }</code><technical_language>StoreCopyClient is created RemoteStore, is class calls this method passes a requestWiseTerminationCondition. I if this argument a field instead, this argument list is long. RemoteStore put in charge of creating StoreCopyClient</technical_language>

Target:
long copyStoreFiles( CatchupAddressProvider catchupAddressProvider, StoreId expectedStoreId, StoreFileStreams storeFileStreams, Supplier<TerminationCondition> requestWiseTerminationCondition ) throws StoreCopyFailedException { try { PrepareStoreCopyResponse prepareStoreCopyResponse = listFiles( catchupAddressProvider.primary(), expectedStoreId, storeFileStreams ); copyFilesIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); copyIndexSnapshotIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); return prepareStoreCopyResponse.lastTransactionId(); } catch ( CatchupAddressResolutionException | CatchUpClientException e ) { throw new StoreCopyFailedException( e ); } }
Source:
<code>public MarshallableEntry loadEntry(Object key) throws PersistenceException { V value = loadValue(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); long now = ctx.getTimeService().wallClockTime(); if (expiry == null || expiry.isEternal()) { return ctx.getMarshallableEntryFactory().create(key, value); } else { long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); JCacheInternalMetadata meta = new JCacheInternalMetadata(now, exp); <START> return ctx.getMarshallableEntryFactory().create(key, value, meta, now, 0); <END> } } return null; }</code><technical_language>lastUsed -1 for consistency. This JCache expiration is supposed work stores... I lean calling Expiration.getExpiry(expiryPolicy, Expiration.Operation.ACCESS) CREATION expiration ACCESS expiration is null, I checked Caffeine source code expiry.getExpiryForCreation(), good :)</technical_language>

Target:
public MarshallableEntry<K,V> loadEntry(Object key) throws PersistenceException { V value = loadValue(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); if (expiry == null || expiry.isEternal()) { return ctx.<K,V>getMarshallableEntryFactory().create(key, value); } else { long now = ctx.getTimeService().wallClockTime(); long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); Metadata meta = new EmbeddedMetadata.Builder().lifespan(exp - now).build(); return ctx.<K,V>getMarshallableEntryFactory().create(key, value, meta, now, -1); } } return null; }
Source:
<code>private static Set<Class<?>> getAllAnnotatedClasses() { Set<Class<?>> metadataStoreResult = ClassScanner.getAnnotatedClasses(METADATA_STORE_ANNOTATIONS); <START> Set<Class<?>> entityResult = ClassScanner.getAnnotatedClasses(METADATA_STORE_ENTITY_ANNOTATION); <END> Set<Class<?>> includeResult = ClassScanner.getAnnotatedClasses(Include.class); entityResult.retainAll(includeResult); metadataStoreResult.addAll(entityResult); return metadataStoreResult; }</code><technical_language>Class scanning is time consuming. want scan 100% of classes times do this. In past, this caused build times roof. a new method in ClassScanner for classes need in pass</technical_language>

Target:
private static Set<Class<?>> getAllAnnotatedClasses() { Set<Class<?>> metadataStoreResult = ClassScanner.getAnnotatedClasses(METADATA_STORE_ANNOTATIONS, (clazz) -> { if (clazz.getAnnotation(Entity.class) != null) { if (clazz.getAnnotation(Include.class) != null) { return true; } return false; } return true; }); return metadataStoreResult; }
Source:
<code>public void testOperatorDropdownWhenOperatorCanBeSet() { final String operatorPlaceholder = "--- please choose ---"; registerFakeProvider(); when(translationService.format(GuidedDecisionTableErraiConstants.OperatorPage_NoOperator)).thenReturn("(no operator)"); when(presenter.getDataModelOracle()).thenReturn(oracle); when(plugin.getFactField()).thenReturn("factField"); <START> when(plugin.editingCol()).thenReturn(editingCol); <END> when(plugin.operatorPlaceholder()).thenReturn(operatorPlaceholder); when(editingCol.getOperator()).thenReturn(""); mockGetOperatorCompletionsToReturn(OperatorsOracle.STANDARD_OPERATORS); spyOperatorsDropdown(); page.operatorDropdown(widget -> { assertTrue(widget instanceof CEPOperatorsDropdown); final CEPOperatorsDropdown dropdown = (CEPOperatorsDropdown) widget; verify(dropdown.getBox()).setSelectedIndex(0); verify(dropdown.getBox()).addChangeHandler(any()); verify(dropdown).addPlaceholder(operatorPlaceholder, operatorPlaceholder); verify(dropdown).insertItem("(no operator)", "", 1); }); }</code><technical_language>java when(plugin.editingCol()).thenReturn(editingCol); is done in @Before method</technical_language>

Target:
public void testOperatorDropdownWhenOperatorCanBeSet() { final String operatorPlaceholder = "--- please choose ---"; registerFakeProvider(); when(translationService.format(GuidedDecisionTableErraiConstants.OperatorPage_NoOperator)).thenReturn("(no operator)"); when(presenter.getDataModelOracle()).thenReturn(oracle); when(plugin.getFactField()).thenReturn("factField"); when(plugin.operatorPlaceholder()).thenReturn(operatorPlaceholder); when(editingCol.getOperator()).thenReturn(""); mockGetOperatorCompletionsToReturn(OperatorsOracle.STANDARD_OPERATORS); spyOperatorsDropdown(); mockListBox(operatorPlaceholder, "", "equal to"); page.operatorDropdown(widget -> { assertTrue(widget instanceof CEPOperatorsDropdown); final CEPOperatorsDropdown dropdown = (CEPOperatorsDropdown) widget; verify(listBox).setSelectedIndex(1); verify(listBox).addChangeHandler(any()); verify(dropdown).addPlaceholder(operatorPlaceholder, operatorPlaceholder); verify(dropdown).insertItem("(no operator)", "", 1); }); }
Source:
<code>public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method method : clazz.getDeclaredMethods()) { if (methods.containsKey(method.getName())) { methods.get(method.getName()).add(method); continue; } <START> methods.put(method.getName(), new HashSet<Method>() {{add(method);}}); <END> } Class<?> parent = clazz.getSuperclass(); while (null != parent) { methods.putAll(extractMethods(clazz, parent, methods)); parent = parent.getSuperclass(); } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }</code><technical_language>Nitpick: prefer reversing logic continue: String name = method.getName(); Set<Method> methods = methodsByNames.get(name); if (methods == null) { methods = new HashSet<>(); methodsByNames.put(name, methods); } methods.add(method);</technical_language>

Target:
public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method declaredMethod : clazz.getDeclaredMethods()) { Set<Method> declaredMethods = methods.get(declaredMethod.getName()); if (declaredMethods == null) { declaredMethods = Sets.newHashSet(); methods.put(declaredMethod.getName(), declaredMethods); } declaredMethods.add(declaredMethod); } Class<?> parent = clazz.getSuperclass(); while (null != parent) { Set<Map.Entry<String, Set<Method>>> extractedMethods = extractMethods(clazz, parent, methods).entrySet(); for (Map.Entry<String, Set<Method>> extractedMethod : extractedMethods){ Set<Method> m = methods.get(extractedMethod.getKey()); if (m == null) { methods.put(extractedMethod.getKey(), extractedMethod.getValue()); } else { m.addAll(extractedMethod.getValue()); } } parent = parent.getSuperclass(); } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }
Source:
<code>public int seek(int dictId) { if (dimConversions == null) { return -1; } if (lastVal != -1) { if (dictId <= lastVal) { throw new ISE("Value dictId[%d] is less than the last value dictId[%d] I have, cannot be.", dictId, lastVal); } <START> return -1; <END> } if (currVal == -1) { currVal = dimConversions.get(); } if(currVal == dictId) { int ret = currIndex; ++currIndex; if (dimConversions.hasRemaining()) { currVal = dimConversions.get(); } else { lastVal = dictId; } return ret; } else if (currVal < dictId) { throw new ISE("Skipped currValue dictId[%d], currIndex[%d]; incoming value dictId[%d]", currVal, currIndex, dictId); } else { return -1; } }</code><technical_language>define this explicitly a constant</technical_language>

Target:
public int seek(int dictId) { if (dimConversions == null) { return NOT_EXIST; } if (lastVal != NOT_INIT) { if (dictId <= lastVal) { throw new ISE("Value dictId[%d] is less than the last value dictId[%d] I have, cannot be.", dictId, lastVal ); } return NOT_EXIST; } if (currVal == NOT_INIT) { currVal = dimConversions.get(); } if (currVal == dictId) { int ret = currIndex; ++currIndex; if (dimConversions.hasRemaining()) { currVal = dimConversions.get(); } else { lastVal = dictId; } return ret; } else if (currVal < dictId) { throw new ISE("Skipped currValue dictId[%d], currIndex[%d]; incoming value dictId[%d]", currVal, currIndex, dictId ); } else { return NOT_EXIST; } }
Source:
<code>private boolean readRulesAtBase() throws IOException { <START> String path = basePath + "/.gitignore"; <END> File f = new File(path); IgnoreNode n = new IgnoreNode(f.getParentFile()); path = basePath + "/.git/info/exclude"; f = new File(path); if (f.canRead()) { n.addSecondarySource(f); } ignoreMap.put(basePath, n); return true; }</code><technical_language>Please new File(basePath, ".gitignore") Instead of string concat platform specific "/" character</technical_language>

Target:
private boolean readRulesAtBase() throws IOException { String path = basePath + "/.gitignore"; File f = new File(path); IgnoreNode n = new IgnoreNode(f.getParentFile()); path = basePath + "/.git/info/exclude"; f = new File(path); if (f.canRead()) n.addSecondarySource(f); ignoreMap.put(basePath, n); return true; }
Source:
<code>public boolean exists(String name) { <START> Preconditions.checkArgument(!Strings.isNullOrEmpty(name)); <END> return assetManager.getAsset(name, Prefab.class).isPresent(); }</code><technical_language>I argue is ok if name is empty, contract loosened a little</technical_language>

Target:
public boolean exists(String name) { if (Strings.isNullOrEmpty(name)) { return false; } return assetManager.getAsset(name, Prefab.class).isPresent(); }
Source:
<code>public void edit(HostNetworkProviderModel model) { driver.edit(model); final NeutronAgentModel neutronAgentModel = model.getNeutronAgentModel(); neutronAgentWidget.edit(neutronAgentModel); neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity()); neutronAgentModel.isPluginConfigurationAvailable().getEntityChangedEvent().addListener((ev, sender, args) -> neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity())); <START> model.getNetworkProviders().setIsChangeable(!model.getUseClusterDefaultNetworkProvider().getEntity()); <END> model.getUseClusterDefaultNetworkProvider().getEntityChangedEvent().addListener((ev, sender, args) -> model.getNetworkProviders().setIsChangeable(!model.getUseClusterDefaultNetworkProvider().getEntity())); }</code><technical_language>113-144 in model view. Please move 'HostNetworkProviderModel'</technical_language>

Target:
public void edit(HostNetworkProviderModel model) { driver.edit(model); final NeutronAgentModel neutronAgentModel = model.getNeutronAgentModel(); neutronAgentWidget.edit(neutronAgentModel); neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity()); neutronAgentModel.isPluginConfigurationAvailable().getEntityChangedEvent().addListener((ev, sender, args) -> neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity())); }
Source:
<code>public synchronized Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { return views.entrySet().stream() .filter(entry -> prefix.matches(entry.getKey())) <START> .collect(ImmutableMap.toImmutableMap( <END> Map.Entry::getKey, entry -> new ConnectorViewDefinition(entry.getKey(), Optional.empty(), entry.getValue()))); }</code><technical_language>Static import</technical_language>

Target:
public synchronized Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { return views.entrySet().stream() .filter(entry -> prefix.matches(entry.getKey())) .collect(toImmutableMap( Map.Entry::getKey, entry -> new ConnectorViewDefinition(entry.getKey(), Optional.empty(), entry.getValue()))); }
Source:
<code>public void run() { while (!Thread.interrupted()) { FSAppAttempt starvedApp; try{ starvedApp = context.getStarvedApps().take(); <START> if (Resources.none().equals(starvedApp.getStarvation())) { <END> continue; } } catch (InterruptedException e) { LOG.info("Preemption thread interrupted! Exiting."); return; } List<RMContainer> containers = identifyContainersToPreempt(starvedApp); if (containers != null) { preemptContainers(containers); } } }</code><technical_language>Feels this a Resources.isNone() call</technical_language>

Target:
public void run() { while (!Thread.interrupted()) { FSAppAttempt starvedApp; try{ starvedApp = context.getStarvedApps().take(); if (!Resources.isNone(starvedApp.getStarvation())) { List<RMContainer> containers = identifyContainersToPreempt(starvedApp); if (containers != null) { preemptContainers(containers); } } } catch (InterruptedException e) { LOG.info("Preemption thread interrupted! Exiting."); return; } } }
Source:
<code>public void initialize(RealtimeContext context) throws Exception { <START> uniqueKey = config.getKeyField(); <END> outputFieldMap = config.getOutputFieldMap(); solrClient = config.getSolrConnection(); config.verifySolrConfiguration(); }</code><technical_language>uniqueKey, consistent call keyField</technical_language>

Target:
public void initialize(RealtimeContext context) throws Exception { keyField = config.getKeyField(); solrClient = config.getSolrConnection(); outputFieldMap = config.createOutputFieldMap(); metrics = context.getMetrics(); config.testSolrConnection(); }
Source:
<code>public String revisionId(Path path) { RepositoryBuilder builder = getVerifiedRepositoryBuilder(path); try { return builder.build().exactRef("HEAD").getObjectId().getName(); } catch (IOException e) { <START> throw MessageException.of("I/O error while getting revision ID for path: " + path, e); <END> } }</code><technical_language>error technical. a MessageException</technical_language>

Target:
public String revisionId(Path path) { RepositoryBuilder builder = getVerifiedRepositoryBuilder(path); try { return builder.build().exactRef("HEAD").getObjectId().getName(); } catch (IOException e) { throw new IllegalStateException("I/O error while getting revision ID for path: " + path, e); } }
Source:
<code>void add(Context context, Request currentRequest, WorkspaceItem source, String path, Object value) throws Exception { String[] split = path.split("/"); Item item = source.getItem(); <START> List<Bundle> bundle = itemService.getBundles(item, Constants.CONTENT_BUNDLE_NAME);; <END> for(Bundle bb : bundle) { int idx = 0; for(Bitstream b : bb.getBitstreams()) { if(idx==Integer.parseInt(split[0])) { addValue(context, b, split[2], evaluateObject((LateObjectEvaluator)value)); } idx++; } } }</code><technical_language>a double semicolon this line (And a others in other classes, want do a search & replace here)</technical_language>

Target:
void add(Context context, Request currentRequest, WorkspaceItem source, String path, Object value) throws Exception { String[] split = getAbsolutePath(path).split("/"); Item item = source.getItem(); List<Bundle> bundle = itemService.getBundles(item, Constants.CONTENT_BUNDLE_NAME);; for(Bundle bb : bundle) { int idx = 0; for(Bitstream b : bb.getBitstreams()) { if(idx==Integer.parseInt(split[1])) { if (split.length == 4) { List<MetadataValueRest> list = evaluateArrayObject((LateObjectEvaluator) value); replaceValue(context, b, split[3], list); } else { MetadataValueRest object = evaluateSingleObject((LateObjectEvaluator) value); List<MetadataValue> metadataByMetadataString = bitstreamService.getMetadataByMetadataString(b, split[3]); Assert.notEmpty(metadataByMetadataString); if (split.length > 4) { String controlChar = split[4]; switch (controlChar) { case "-": addValue(context, b, split[3], object, -1); break; default: int index = Integer.parseInt(controlChar); if (index > metadataByMetadataString.size()) { throw new IllegalArgumentException( "The specified index MUST NOT be greater than the number of elements in the array"); } addValue(context, b, split[3], object, index); break; } } } } idx++; } } }
Source:
<code>private boolean notRedirect(HttpServletRequest req) { <START> String refererValue = req.getHeader("Referer"); <END> return (refererValue != null && (refererValue.contains( "host_id=" ) || refererValue.contains( "fromAngular=true" ) || refererValue.contains( "dotAdmin" ) || refererValue.contains( "p_p_id=site-browser"))); }</code><technical_language>This a global constant (such Constants interface)</technical_language>

Target:
private boolean notRedirect(HttpServletRequest req) { String refererValue = req.getHeader(Constants.REFERER_URL_HTTP_HEADER); return (refererValue != null && (refererValue.contains( "host_id=" ) || refererValue.contains( "fromAngular=true" ) || refererValue.contains(PortletURLUtil.URL_ADMIN_PREFIX ) || refererValue.contains( "p_p_id=" + PortletID.SITE_BROWSER ))); }
Source:
<code>public void schedulePasswordReminderJob() { <START> CronSchedulableJob job = new CronSchedulableJob(new MotechEvent(PASSWORD_EXPIRATION_CHECK_EVENT), "0 * * * * ? *"); <END> schedulerService.safeScheduleJob(job); }</code><technical_language>This runs minute</technical_language>

Target:
public void schedulePasswordReminderJob() { CronSchedulableJob job = new CronSchedulableJob(new MotechEvent(PASSWORD_EXPIRATION_CHECK_EVENT), "0 0 0 * * ? *"); schedulerService.safeScheduleJob(job); }
Source:
<code>public static byte[] getBytesNoPaddingfromList(List<Integer> list, int maxValue) { <START> int numBytes = getNumBytesForMax(maxValue); <END> final ByteBuffer buffer = ByteBuffer.allocate((list.size() * numBytes)); int i = 0; for (Integer val : list) { if (val < 0) { throw new IAE("integer values must be positive, got[%d], i[%d]", val, i); } if (val > maxValue) { throw new IAE("val[%d] > maxValue[%d], please don't lie about maxValue. i[%d]", val, maxValue, i); } byte[] intAsBytes = Ints.toByteArray(val); buffer.put(intAsBytes, intAsBytes.length - numBytes, numBytes); ++i; } buffer.position(0); return buffer.array(); }</code><technical_language>refactor reduce copy-paste fromList</technical_language>

Target:
public static byte[] getBytesNoPaddingfromList(List<Integer> list, int maxValue) { int numBytes = getNumBytesForMax(maxValue); final ByteBuffer buffer = ByteBuffer.allocate((list.size() * numBytes)); writeToBuffer(buffer, list, numBytes, maxValue); return buffer.array(); }
Source:
<code>public void detectsSplitPpv1Message() { <START> EmbeddedChannel channel = new EmbeddedChannel(); <END> channel.pipeline().addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler( true)); ByteBuf buf1 = Unpooled.wrappedBuffer( "PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf1); ByteBuf buf2 = Unpooled.wrappedBuffer( "192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf2); Object msg = channel.readInbound(); assertTrue(msg instanceof HAProxyMessage); assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.class)); }</code><technical_language>forgot release this object</technical_language>

Target:
public void detectsSplitPpv1Message() { EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(true)); ByteBuf buf1 = Unpooled.wrappedBuffer( "PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf1); ByteBuf buf2 = Unpooled.wrappedBuffer( "192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf2); Object msg = channel.readInbound(); assertTrue(msg instanceof HAProxyMessage); buf1.release(); buf2.release(); ((HAProxyMessage) msg).release(); assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.class)); }
Source:
<code>protected Fragment getFragment(int position) { final IssueMilestoneListFragment f = IssueMilestoneListFragment.newInstance(mRepoOwner, mRepoName, position == 1); <START> if (position != 1) { <END> mOpenFragment = f; } return f; }</code><technical_language>if (position == 0) expresses this is about</technical_language>

Target:
protected Fragment getFragment(int position) { final IssueMilestoneListFragment f = IssueMilestoneListFragment.newInstance(mRepoOwner, mRepoName, position == 1); if (position == 0) { mOpenFragment = f; } return f; }
Source:
<code>public void configure(SpringProcessEngineConfiguration processEngineConfiguration){ <START> processEngineConfiguration.setActivityBehaviorFactory(new DefaultActivityBehaviorFactoryMapping(processExtensionService,processVariablesInitiator)); <END> }</code><technical_language>Do integration test checking is set properly</technical_language>

Target:
public void configure(SpringProcessEngineConfiguration processEngineConfiguration){ processEngineConfiguration.setActivityBehaviorFactory(new MappingAwareActivityBehaviorFactory(variablesMappingProvider, processVariablesInitiator)); }
Source:
<code>private void deleteChannel (ChannelInfoItem selectedItem) { <START> ExtractorHelper.getChannelInfo(selectedItem.getServiceId(), selectedItem.getUrl(), true) <END> .subscribeOn(Schedulers.io()) .observeOn(Schedulers.newThread()) .subscribe((@NonNull ChannelInfo result) -> { List<SubscriptionEntity> toDelete = subscriptionService.subscriptionTable() .getSubscription(result.getServiceId(), result.getUrl()) .blockingFirst(); subscriptionService.subscriptionTable().delete(toDelete); }); }</code><technical_language>subscribe, a disposable created run code in a thread is killed fragment is, is a good idea create a CompositeDisposable fragment level put disposables in there. fragment is destroyed (i.e. onStop()), need clean dispose items in dispoable</technical_language>

Target:
private void deleteChannel (ChannelInfoItem selectedItem) { subscriptionService.subscriptionTable() .getSubscription(selectedItem.getServiceId(), selectedItem.getUrl()) .toObservable() .observeOn(Schedulers.io()) .subscribe(getDeleteObserver()); Toast.makeText(activity, getString(R.string.channel_unsubscribed), Toast.LENGTH_SHORT).show(); }
Source:
<code>protected <T> Transform<Throwable, T> handleVersionConflict( Provider<T> emptyProvider, Runnable reportWriteDroppedByDuplicate ) { return throwable -> { <START> if (throwable.getMessage().contains("version conflict")) { <END> reportWriteDroppedByDuplicate.run(); return emptyProvider.get(); } throw new RuntimeException(throwable); }; }</code><technical_language>exceptions want deal with, a list of exceptions act on, string matching? I if text change some point, this break</technical_language>

Target:
protected <T> Transform<Throwable, T> handleVersionConflict( Provider<T> emptyProvider, Runnable reportWriteDroppedByDuplicate ) { return throwable -> { if (ExceptionUtils.getRootCause(throwable) instanceof VersionConflictEngineException || throwable.getMessage().contains("version_conflict_engine_exception")) { reportWriteDroppedByDuplicate.run(); return emptyProvider.get(); } throw new RuntimeException(throwable); }; }
Source:
<code>public int getItemCount() { <START> if (mNavigationItems != null) { <END> return mNavigationItems.size(); } else { return mServerName.size(); } }</code><technical_language>This better. return mNavigationItems!=null?mNavigationItems.size():mServerName.size(); is cases null list</technical_language>

Target:
public int getItemCount() { return mNavigationItems != null ? mNavigationItems.size() : mServerName.size(); }
Source:
<code>private static String getAltFromHgvs(String hgvs, Type type) { <START> if (!type.equals(Type.DELETION)) <END> return getPattern("(?<=[a-z+>])[ATCG]+$", hgvs); String alt = getPattern("(?<=[a-z+>])[ATCG]*$", hgvs); if (alt.equals(null)) return ""; String ans = ""; while (ans.length() < alt.length()) ans += "X"; return ans; }</code><technical_language>suggestion if (!type.equals(Type.DELETION)) { ... }</technical_language>

Target:
private static String getAltFromHgvs(String hgvs, Type type) { if (!type.equals(Type.DELETION)) { return getPattern("(?<=[a-z+>])[ATCG]+$", hgvs); } String alt = getPattern("(?<=[a-z+>])[ATCG]*$", hgvs); if (alt.equals(null)) { return ""; } String ans = ""; while (ans.length() < alt.length()) { ans += "X"; } return ans; }
Source:
<code>public long save(Study study) throws IOException { if (study.getId() == StudyImpl.UNSAVED_ID) { study.setLastModifier(authorizationManager.getCurrentUser()); <START> return studyStore.save(study); <END> } else { Study original = studyStore.get(study.getId()); authorizationManager.throwIfNotWritable(original); original.setAccession(study.getAccession()); original.setAlias(study.getAlias()); original.setDescription(study.getDescription()); original.setLastModifier(authorizationManager.getCurrentUser()); original.setStudyType(studyStore.getType(original.getStudyType().getId())); return studyStore.save(original); } }</code><technical_language>need add Hibernate-managed StudyType saving</technical_language>

Target:
public long save(Study study) throws IOException { if (study.getId() == StudyImpl.UNSAVED_ID) { study.setLastModifier(authorizationManager.getCurrentUser()); study.setStudyType(studyStore.getType(study.getStudyType().getId())); study.setProject(projectStore.get(study.getProject().getId())); study.setName(LimsUtils.generateTemporaryName()); long id = studyStore.save(study); try { study.setName(namingScheme.generateNameFor(study)); LimsUtils.validateNameOrThrow(study, namingScheme); studyStore.save(study); } catch (MisoNamingException e) { throw new IOException(e); } return id; } else { Study original = studyStore.get(study.getId()); authorizationManager.throwIfNotWritable(original); original.setAccession(study.getAccession()); original.setAlias(study.getAlias()); original.setDescription(study.getDescription()); original.setLastModifier(authorizationManager.getCurrentUser()); original.setStudyType(studyStore.getType(study.getStudyType().getId())); return studyStore.save(original); } }
Source:
<code>public void testRepairAfterIncompleteCompaction() throws Exception { PartitionId partitionId = new MockPartitionId(testPartition, MockClusterMap.DEFAULT_PARTITION_CLASS); BlobId blobId = new BlobId(BLOB_ID_V6, BlobIdType.NATIVE, dataCenterId, accountId, containerId, partitionId, false, BlobDataType.DATACHUNK); InputStream inputStream = getBlobInputStream(blobSize); long now = System.currentTimeMillis(); CloudBlobMetadata cloudBlobMetadata = new CloudBlobMetadata(blobId, now, -1, blobSize, CloudBlobMetadata.EncryptionOrigin.NONE); uploadBlobWithRetry(blobId, blobSize, cloudBlobMetadata, inputStream); long deletionTime = now - TimeUnit.DAYS.toMillis(7); assertTrue("Expected delete to return true", azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator)); azureDest.getAzureBlobDataAccessor().purgeBlobs(Collections.singletonList(cloudBlobMetadata)); try { assertFalse("Expected delete to return false", azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator)); } catch (CloudStorageException cex) { <START> assertEquals("Unexpected error code", HttpConstants.StatusCodes.NOTFOUND, cex.getStatusCode()); <END> } assertNull("Expected record to be purged from Cosmos", azureDest.getCosmosDataAccessor().getMetadataOrNull(blobId)); }</code><technical_language>This sense, expect method return false throw exception</technical_language>

Target:
public void testRepairAfterIncompleteCompaction() throws Exception { PartitionId partitionId = new MockPartitionId(testPartition, MockClusterMap.DEFAULT_PARTITION_CLASS); BlobId blobId = new BlobId(BLOB_ID_V6, BlobIdType.NATIVE, dataCenterId, accountId, containerId, partitionId, false, BlobDataType.DATACHUNK); InputStream inputStream = getBlobInputStream(blobSize); long now = System.currentTimeMillis(); CloudBlobMetadata cloudBlobMetadata = new CloudBlobMetadata(blobId, now, -1, blobSize, CloudBlobMetadata.EncryptionOrigin.NONE); uploadBlobWithRetry(blobId, blobSize, cloudBlobMetadata, inputStream); long deletionTime = now - TimeUnit.DAYS.toMillis(7); assertTrue("Expected delete to return true", azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator)); azureDest.getAzureBlobDataAccessor().purgeBlobs(Collections.singletonList(cloudBlobMetadata)); try { azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator); } catch (CloudStorageException cex) { assertEquals("Unexpected error code", HttpConstants.StatusCodes.NOTFOUND, cex.getStatusCode()); } assertNull("Expected record to be purged from Cosmos", azureDest.getCosmosDataAccessor().getMetadataOrNull(blobId)); }
Source:
<code>private void updateGuideStarAdders() { <START> final boolean onlyAutoGroup = getContextTargetEnv().getGroups().size() == 1; <END> final boolean enabled = onlyAutoGroup || selectionIsManualGroup() || selectionIsManualTarget(); _guideStarAdders.forEach((gp, comp) -> comp.setEnabled(enabled)); }</code><technical_language>This is true a bit indirect maybe. a getAutomaticGroup in GuideEnvironment, add a getManualGroups</technical_language>

Target:
private void updateGuideStarAdders() { final boolean onlyAutoGroup = getContextTargetEnv().getGuideEnvironment().manualGroups().isEmpty(); final boolean enabled = onlyAutoGroup || selectionIsManualGroup() || selectionIsManualTarget(); _guideStarAdders.forEach((gp, comp) -> comp.setEnabled(enabled)); }
Source:
<code><START> void setupDefaultHandlers() { <END> domElementContainer.addDomHandler(new ScrollHandler() { @Override public void onScroll(final ScrollEvent scrollEvent) { domElementContainer.getElement().setScrollTop(0); domElementContainer.getElement().setScrollLeft(0); } }, ScrollEvent.getType()); addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(final AttachEvent event) { if (event.isAttached()) { onResize(); } } }); addMouseDownHandler((e) -> setFocus(true)); }</code><technical_language>@manstis @danielezonca @karreiro I Guillerme is a "default" supporter. learn mistakes, though, I remember "AbstractPopover" implemented, I discussed hour try convince "protected" modifiers - un-heard. I do re-use in scesim rewrite re-usable. is extremely hard foresee needs of a specific component, kie-common codebase is full of widget absolutely un-reusable for reason. If a developer "broke" a functionality overriding a method, is his/her responsability - this is of modifier applied. In specific case, is that, sooner later, need override "default handlers" for some reason - need a widget rewrite. A good code is is easy extend/reuse, works in specific situation firstly used. So, "pragmatic" stop shooting feet :) :) :)</technical_language>

Target:
protected void setupDefaultHandlers() { domElementContainer.addDomHandler(new ScrollHandler() { @Override public void onScroll(final ScrollEvent scrollEvent) { domElementContainer.getElement().setScrollTop(0); domElementContainer.getElement().setScrollLeft(0); } }, ScrollEvent.getType()); addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(final AttachEvent event) { if (event.isAttached()) { onResize(); } } }); addMouseDownHandler((e) -> setFocus(true)); }
Source:
<code>public static void assertThenRelease(final Response actual, final Matcher<Response> matcher) { try { MatcherAssert.assertThat(actual, matcher); } finally { <START> if(actual != null) <END> { actual.release(); } } }</code><technical_language>RequestFacade.releaseResponse() simplify this code</technical_language>

Target:
public static void assertThenRelease(final Response actual, final Matcher<Response> matcher) { try { MatcherAssert.assertThat(actual, matcher); } finally { RequestFacade.releaseResponse(actual); } }
Source:
<code>public ITmfStateProvider getNewInstance() { <START> return new KernelMemoryStateProvider(this.getTrace(), this.fLayout); <END> }</code><technical_language>remove this</technical_language>

Target:
public ITmfStateProvider getNewInstance() { return new KernelMemoryStateProvider(getTrace(), fLayout); }
Source:
<code>private Language saveOrUpdateLanguage(final String languageId, final LanguageForm form) { final Language newLanguage = new Language(); if (StringUtils.isSet(languageId)) { try { final Language origLanguage = this.languageAPI.getLanguage(languageId); BeanUtils.copyProperties(newLanguage, origLanguage); } catch (Exception e) { Logger.debug(this.getClass(), () -> "Unable to find language with id:" + languageId); <START> throw new DoesNotExistException(e.getMessage(), e); <END> } } newLanguage.setLanguageCode(form.getLanguageCode()); newLanguage.setLanguage(form.getLanguage()); newLanguage.setCountryCode(form.getCountryCode()); newLanguage.setCountry(form.getCountry()); this.languageAPI.saveLanguage(newLanguage); return newLanguage; }</code><technical_language>Perhaps, exception name is accurate</technical_language>

Target:
private Language saveOrUpdateLanguage(final String languageId, final LanguageForm form) { final Language newLanguage = new Language(); if (StringUtils.isSet(languageId)) { final Language origLanguage = this.languageAPI.getLanguage(languageId); Sneaky.sneaked(()->BeanUtils.copyProperties(newLanguage, origLanguage)); } newLanguage.setLanguageCode(form.getLanguageCode()); newLanguage.setLanguage(form.getLanguage()); newLanguage.setCountryCode(form.getCountryCode()); newLanguage.setCountry(form.getCountry()); this.languageAPI.saveLanguage(newLanguage); return newLanguage; }
Source:
<code>public void testAssumptionFailure( Failure failure ) { <START> this.reporter.testAssumptionFailure( SimpleReportEntry.ignored( getClassName( failure.getDescription() ) , <END> failure.getDescription().getDisplayName() , failure.getMessage() ) ); failureFlag.set( Boolean.TRUE ); }</code><technical_language>@jimma please introduce a new constructor public SimpleReportEntry( String source, String name, String message ) call instead of SimpleReportEntry.ignored? call constructor in SimpleReportEntry.ignored well? Thx</technical_language>

Target:
public void testAssumptionFailure( Failure failure ) { reporter.testAssumptionFailure( new SimpleReportEntry( getClassName( failure.getDescription() ) , failure.getDescription().getDisplayName() , failure.getMessage() ) ); failureFlag.set( true ); }
Source:
<code>public static String getGetFeatureInfoUrlForProxy(String url, String projection, String bbox, String width, String height, String x, String y, String layerName) { <START> String wmsUrl = url+"?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&SRS="+projection <END> +"&BBOX="+bbox +"&WIDTH="+width +"&HEIGHT="+height +"&QUERY_LAYERS="+layerName +"&X="+Math.round(Float.parseFloat(x)) +"&Y="+Math.round(Float.parseFloat(y)) +"&LAYERS="+layerName +"&FEATURECOUNT=1" +"&INFO_FORMAT=application/json" +"&EXCEPTIONS=application/vnd.ogc.se_xml" +"&BUFFER=0"; return wmsUrl; }</code><technical_language>Check IOHelper.constructUrl() for properly concatenating parameters a base url</technical_language>

Target:
public static String getGetFeatureInfoUrlForProxy(String url, String projection, String bbox, String width, String height, String x, String y, String layerName) { Map<String, String> urlParams = new HashMap<String, String>(); urlParams.put("SERVICE", "WMS"); urlParams.put("VERSION", "1.1.1"); urlParams.put("REQUEST", "GetFeatureInfo"); urlParams.put("SRS", projection); urlParams.put("BBOX", bbox); urlParams.put("WIDTH", width); urlParams.put("HEIGHT", height); urlParams.put("QUERY_LAYERS", layerName); urlParams.put("X", Long.toString(Math.round(Float.parseFloat(x)))); urlParams.put("Y", Long.toString(Math.round(Float.parseFloat(y)))); urlParams.put("LAYERS", layerName); urlParams.put("FEATURECOUNT", "1"); urlParams.put("INFO_FORMAT", "application/json"); urlParams.put("EXCEPTIONS", "application/vnd.ogc.se_xml"); urlParams.put("BUFFER", "0"); return IOHelper.constructUrl(url, urlParams); }
Source:
<code>public static Trace getAndClearTrace() { Trace trace = currentTrace.get(); <START> currentTrace.remove(); <END> return trace; }</code><technical_language>\+ unset MDC</technical_language>

Target:
public static Trace getAndClearTrace() { Trace trace = currentTrace.get(); currentTrace.remove(); MDC.remove(Tracers.TRACE_ID_KEY); return trace; }