auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute() { if (debug != null) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(Level.DEBUG); <START> rootLogger.debug("Initialized debug logging"); <END> } MesosCluster cluster = getCluster(); if (cluster != null) { output.println("Cluster " + cluster.getClusterId() + " is already running"); return; } ClusterArchitecture clusterArchitecture = getClusterArchitecture(); startedCluster = new MesosCluster(clusterArchitecture); startedCluster.start(); startedCluster.waitForState(state -> state != null); startedCluster.printServiceUrls(output); ClusterRepository.saveClusterFile(startedCluster); }</code><technical_language>I meant LOGGER.debug("Initialized debug logging");</technical_language>

Target:
public void execute() { if (debug != null) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(Level.DEBUG); LOGGER.debug("Initialized debug logging"); } MesosCluster cluster = getCluster(); if (cluster != null) { output.println("Cluster " + cluster.getClusterId() + " is already running"); return; } ClusterArchitecture clusterArchitecture = getClusterArchitecture(); startedCluster = new MesosCluster(clusterArchitecture); startedCluster.start(); startedCluster.waitForState(state -> state != null); startedCluster.printServiceUrls(output); ClusterRepository.saveClusterFile(startedCluster); }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; <START> result = prime * result + ((this.calendarName == null) ? 0 : this.calendarName.hashCode()); <END> result = prime * result + ((this.activatePassiveCalendarTime == null) ? 0 : this.activatePassiveCalendarTime.hashCode()); result = prime * result + ((this.seasonProfileList == null) ? 0 : this.seasonProfileList.hashCode()); return result; }</code><technical_language>If calendarName null, other places in this class need null-checks. If calendarName null, null-checks in hashCode redundant, removed. for other fields</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.calendarName.hashCode(); result = prime * result + this.activatePassiveCalendarTime.hashCode(); result = prime * result + this.seasonProfileList.hashCode(); return result; }
Source:
<code>public DropwizardEmitter( DropwizardEmitterConfig config, ObjectMapper mapper, List<Emitter> alertEmitters ) { this.alertEmitters = alertEmitters; this.config = config; this.reporters = config.getReporters(); this.converter = new DropwizardConverter(mapper, config.getDimensionMapPath()); <START> this.gagues = Collections.synchronizedMap(new GaugesCache<>(config.getMaxGaugeCount())); <END> }</code><technical_language>guava Cache instead of</technical_language>

Target:
public DropwizardEmitter( DropwizardEmitterConfig config, ObjectMapper mapper, List<Emitter> alertEmitters ) { this.alertEmitters = alertEmitters; this.config = config; this.reporters = config.getReporters(); this.converter = new DropwizardConverter(mapper, config.getDimensionMapPath()); final Cache<String, Metric> metricsRegistryCache = Caffeine.newBuilder() .recordStats() .maximumSize(config.getMaxMetricsRegistrySize()) .build(); metricsRegistry = new MetricRegistry() { @Override protected ConcurrentMap<String, Metric> buildMap() { return metricsRegistryCache.asMap(); } }; }
Source:
<code>public static void waitFor(final Runnable runnable, final long timeoutMs, final int intervalMs, final Class<? extends Throwable>... additionalException) { final Class<? extends Throwable>[] leadToRetry = new Class[additionalException.length + 1]; System.arraycopy(additionalException, 0, leadToRetry, 1, additionalException.length); <START> leadToRetry[0] = AssertionError.class; <END> executeWithRetry( runnable, new RetryForSpecifiedTimeStrategy<Void>(timeoutMs) .withExceptionsThatForceRetry(leadToRetry) .withWaitBetweenEachTry(intervalMs)); }</code><technical_language>array lover :) I done easier: java final List<Class<? extends Throwable>> exs = Arrays.asList(additionalException); exs.add(AssertionError.class);</technical_language>

Target:
public static void waitFor(final Runnable runnable, final long timeoutMs, final int intervalMs, final Class<? extends Throwable>... additionalException) { final List<Class<? extends Throwable>> leadToRetry = Stream.concat(Stream.of(additionalException), Stream.of(AssertionError.class)).collect(toList()); executeWithRetry( runnable, new RetryForSpecifiedTimeStrategy<Void>(timeoutMs) .withExceptionsThatForceRetry(leadToRetry) .withWaitBetweenEachTry(intervalMs)); }
Source:
<code>public static List<String> validateClass(Class<? extends Messages> classUnderTest, File messagesDir) throws URISyntaxException, IOException { List<String> errors = new ArrayList<String>(); List<Method> messagesMethods = new ArrayList<Method>(); messagesMethods.addAll(Arrays.asList(classUnderTest.getDeclaredMethods())); <START> classUnderTest = CommonApplicationMessages.class; <END> for (File localeFile: getMessagesPropertiesFiles(messagesDir, classUnderTest)) { PropertiesFileInfo.properties = loadProperties(localeFile); PropertiesFileInfo.fileName = localeFile.getName(); compareMethodsToProperties(messagesMethods, errors, classUnderTest); } return errors; }</code><technical_language>puzzled this line, is this ensure check CommonApplicationMessages (super-interface) methods? I get public methods classUnderTest - declared classUnderTest & declared super-class / super-interface. Messages is interface, Java interface public methods, class.getMethods() API returns public methods of class (interface), including methods inherited super-class (super-interface). Also, check classUnderTest is interface actual class, class.isInterface() API</technical_language>

Target:
public static List<String> validateClass(Class<? extends Messages> classUnderTest, File messagesDir) throws URISyntaxException, IOException { List<String> errors = new ArrayList<String>(); if (classUnderTest.isInterface()) { List<Method> messagesMethods = new ArrayList<Method>(); messagesMethods.addAll(Arrays.asList(classUnderTest.getMethods())); for (File localeFile: getMessagesPropertiesFiles(messagesDir, classUnderTest)) { PropertiesFileInfo.properties = loadProperties(localeFile); PropertiesFileInfo.fileName = localeFile.getName(); compareMethodsToProperties(messagesMethods, errors, classUnderTest); } } else { errors.add("Class under test not interface: " + classUnderTest.getName()); } return errors; }
Source:
<code>public void testConditionExistingAndMissingInActivation() throws Exception { Properties sysProperties = new Properties(); sysProperties.setProperty( "myproperty", "test" ); ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); assertNotNull( builder ); DefaultModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setProcessPlugins( true ); request.setPomFile( getPom( "complexEmptyAndMissing" ) ); request.setSystemProperties( sysProperties ); <START> try { <END> builder.build( request ); } catch(Exception e) { assertTrue(e instanceof ModelBuildingException); } }</code><technical_language>I JUnit 4.12 @Rule for exceptions checking? WDYT</technical_language>

Target:
public void testConditionExistingAndMissingInActivation() throws Exception { Properties sysProperties = new Properties(); sysProperties.setProperty( "myproperty", "test" ); ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); assertNotNull( builder ); DefaultModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setProcessPlugins( true ); request.setPomFile( getPom( "complexExistsAndMissing" ) ); request.setSystemProperties( sysProperties ); builder.build( request ); }
Source:
<code>public static Collection<Persona> getPersonaByAccountIdentifierLike(String partialName) throws CentralRepoException { String queryClause = "SELECT DISTINCT accounts.id as a_id," + "p.id, p.uuid, p.name, p.comment, p.created_date, p.modified_date, p.status_id, p.examiner_id, e.login_name, e.display_name" + " FROM accounts" + " JOIN persona_accounts as pa ON pa.account_id = accounts.id" + " JOIN personas as p ON p.id = pa.persona_id" + " JOIN examiners as e ON e.id = p.examiner_id" + " WHERE LOWER(accounts.account_unique_identifier) LIKE LOWER('%" + partialName + "%')" + " AND p.status_id != " + Persona.PersonaStatus.DELETED.getStatusId() + " GROUP BY p.id"; PersonaQueryCallback queryCallback = new PersonaQueryCallback(); <START> CentralRepository.getInstance().executeSelectSQL(queryClause, queryCallback); <END> return queryCallback.getPersonas(); }</code><technical_language>Check for null. This another PR</technical_language>

Target:
public static Collection<Persona> getPersonaByAccountIdentifierLike(String partialName) throws CentralRepoException { String queryClause = "SELECT DISTINCT accounts.id as a_id," + "p.id, p.uuid, p.name, p.comment, p.created_date, p.modified_date, p.status_id, p.examiner_id, e.login_name, e.display_name" + " FROM accounts" + " JOIN persona_accounts as pa ON pa.account_id = accounts.id" + " JOIN personas as p ON p.id = pa.persona_id" + " JOIN examiners as e ON e.id = p.examiner_id" + " WHERE LOWER(accounts.account_unique_identifier) LIKE LOWER('%" + partialName + "%')" + " AND p.status_id != " + Persona.PersonaStatus.DELETED.getStatusId() + " GROUP BY p.id"; PersonaQueryCallback queryCallback = new PersonaQueryCallback(); CentralRepository cr = CentralRepository.getInstance(); if (cr != null) { cr.executeSelectSQL(queryClause, queryCallback); } return queryCallback.getPersonas(); }
Source:
<code>protected Set<String> getApplicableColos(String type, Entity entity) { try { if (DeploymentUtil.isEmbeddedMode()) { return DeploymentUtil.getDefaultColos(); } if (EntityType.getEnum(type) == EntityType.CLUSTER) { return getAllColos(); } Set<String> clusters = EntityUtil.getClustersDefined(entity); Set<String> colos = new HashSet<String>(); for (String cluster : clusters) { try{ Cluster clusterEntity = EntityUtil.getEntity(EntityType.CLUSTER, cluster); if(type.equals(EntityType.PROCESS)){ <START> EntityUtil.getEntity(EntityType.PROCESS,entity.getName()); <END> } colos.add(clusterEntity.getColo()); } catch (EntityNotRegisteredException e){ LOG.warn(e.getMessage(), e); } } if (colos.isEmpty()) { throw new EntityNotRegisteredException(entity.getName() + " (" + type + ") not found"); } return colos; } catch (FalconException e) { throw FalconWebException.newAPIException(e); } }</code><technical_language>this code achieve? I do understand this fix issue, please elaborate</technical_language>

Target:
protected Set<String> getApplicableColos(String type, Entity entity) { try { if (DeploymentUtil.isEmbeddedMode()) { return DeploymentUtil.getDefaultColos(); } if (EntityType.getEnum(type) == EntityType.CLUSTER) { return getAllColos(); } Set<String> clusters = EntityUtil.getClustersDefined(entity); Set<String> colos = new HashSet<String>(); try{ EntityType entitytype = EntityType.getEnum(type); if (entitytype == EntityType.PROCESS || entitytype == EntityType.FEED){ EntityUtil.getEntity(entitytype, entity.getName()); } for (String cluster : clusters) { Cluster clusterEntity = EntityUtil.getEntity(EntityType.CLUSTER, cluster); colos.add(clusterEntity.getColo()); } }catch (EntityNotRegisteredException e){ LOG.warn(e.getMessage(), e); } if (colos.isEmpty()) { throw new EntityNotRegisteredException(entity.getName() + " (" + type + ") not found"); } return colos; } catch (FalconException e) { throw FalconWebException.newAPIException(e); } }
Source:
<code>public static int packIp4AddressBytes(short[] bytes) throws KuraException { if ((bytes == null) || (bytes.length != 4)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); <START> } <END> int val = 0; for (int i = 0; i < 4; i++) { if ((bytes[i] < 0) || (bytes[i] > 255)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } val = val << 8; val |= bytes[i]; } return val; }</code><technical_language>well</technical_language>

Target:
public static int packIp4AddressBytes(short[] bytes) { if ((bytes == null) || (bytes.length != 4)) { throw new IllegalArgumentException("bytes is null or invalid"); } int val = 0; for (int i = 0; i < 4; i++) { if ((bytes[i] < 0) || (bytes[i] > 255)) { throw new IllegalArgumentException( "bytes is invalid; value is out of range: " + Integer.toString(bytes[i])); } val = val << 8; val |= bytes[i]; } return val; }
Source:
<code>CachedConnection reserveAny(final ThriftTransportKey key) { <START> return executeWithinLock(key, () -> getOrCreateCachedConnections(key).reserveAny()); <END> }</code><technical_language>locks acquired contention. executeWithinLock acquires a lock. call getOrCreateCachedConnections() acquire another lock ConcurrentHashMap. multiple locks executeWithinLock overlap a single lock ConcurrentHashMap unnecessarily block threads. I this avoided accessing concurrent hash map of executeWithinLock. I this is safe long keys removed concurrent hash map (which case currently, case this change). I this code written follows, acquire locks independently. java CachedConnection reserveAny(final ThriftTransportKey key) { // avoid aquiring concurrent hash map lock executeWithinLock var cachedConns = getOrCreateCachedConnections(key); return executeWithinLock(key, () -> cachedConns.reserveAny()); }</technical_language>

Target:
CachedConnection reserveAny(final ThriftTransportKey key) { var connections = getOrCreateCachedConnections(key); return executeWithinLock(key, connections::reserveAny); }
Source:
<code>@Override public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); <START> monthView.setDividerColor(dividerColor); <END> monthView.setDayTextColor(dayTextColorResId); monthView.setTitleTextColor(titleTextColor); monthView.setHeaderTextColor(headerTextColor); if (dayBackgroundResId != 0) { monthView.setDayBackground(dayBackgroundResId); } } monthView.init(months.get(position), cells.get(position), displayOnly); return monthView; }</code><technical_language>worth moving this stuff MonthView.create</technical_language>

Target:
@Override public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today, dividerColor, dayBackgroundResId, dayTextColorResId, titleTextColor, headerTextColor); } monthView.init(months.get(position), cells.get(position), displayOnly); return monthView; }
Source:
<code>private Object doMput(Message<?> requestMessage) { File file = null; Object payload = requestMessage.getPayload(); if (payload instanceof File) { file = (File) payload; } else if (payload instanceof String) { file = new File((String) payload); } else if (!(payload instanceof Collection)) { throw new IllegalArgumentException( "Only File or String payloads (or Collection of File/String) allowed for 'mput', received: " + payload.getClass()); } if ((payload instanceof Collection)) { return ((Collection<?>) payload).stream() .map(p -> doMput(getMessageBuilderFactory().withPayload(p) .copyHeaders(requestMessage.getHeaders()) <START> .build())) <END> .collect(Collectors.toList()); } else if (!file.isDirectory()) { return doPut(requestMessage); } else { File localDir = file; return this.remoteFileTemplate.invoke(t -> mPut(requestMessage, t.getSession(), localDir)); } }</code><technical_language>do a MutableMessage? Doens't need worry new id timestamp headers..</technical_language>

Target:
private Object doMput(Message<?> requestMessage) { File file = null; Object payload = requestMessage.getPayload(); if (payload instanceof File) { file = (File) payload; } else if (payload instanceof String) { file = new File((String) payload); } else if (!(payload instanceof Collection)) { throw new IllegalArgumentException( "Only File or String payloads (or Collection of File/String) allowed for 'mput', received: " + payload.getClass()); } if ((payload instanceof Collection)) { return ((Collection<?>) payload).stream() .map(p -> doMput(new MutableMessage<>(p, requestMessage.getHeaders()))) .collect(Collectors.toList()); } else if (!file.isDirectory()) { return doPut(requestMessage); } else { File localDir = file; return this.remoteFileTemplate.invoke(t -> mPut(requestMessage, t.getSession(), localDir)); } }
Source:
<code>private void apply(File file) throws Exception { String data; try (InputStream input = new FileInputStream(file)) { data = IOUtils.toString(input, StandardCharsets.UTF_8.name()); LOGGER.debug("Installing file [{}]. Contents:\n{}", file.getAbsolutePath(), data); } if (StringUtils.isEmpty(data)) { LOGGER.debug("File is empty [{}]. Nothing to install.", file.getAbsolutePath()); return; } Outer outer; try { outer = GSON.fromJson(data, Outer.class); } catch (ClassCastException e) { throw new IllegalArgumentException("Cannot parse json [" + file.getAbsolutePath() + "]", e); } final String filename = file.getName(); final Changeset changeset = new Changeset(); <START> changesetsByFile.put(filename, changeset); <END> handleSection(changeset, "Attribute Types", outer.attributeTypes, this::parseAttributeTypes); handleSection( changeset, METACARD_TYPES_PROPERTY, outer.metacardTypes, this::parseMetacardTypes); handleSection(changeset, VALIDATORS_PROPERTY, outer.validators, this::parseValidators); handleSection(changeset, DEFAULTS_PROPERTY, outer.defaults, this::parseDefaults); handleSection(changeset, INJECTIONS_PROPERTY, outer.inject, this::parseInjections); handleSection( changeset, METACARD_VALIDATORS_PROPERTY, outer.metacardvalidators, this::registerMetacardValidators); }</code><technical_language>forced read streams in a string Boon of a bug. advantage of Gson read it</technical_language>

Target:
private void apply(File file) throws Exception { String data; try (InputStream input = new FileInputStream(file)) { data = IOUtils.toString(input, StandardCharsets.UTF_8.name()); LOGGER.debug("Installing file [{}]. Contents:\n{}", file.getAbsolutePath(), data); } if (StringUtils.isEmpty(data)) { LOGGER.debug("File is empty [{}]. Nothing to install.", file.getAbsolutePath()); return; } Outer outer = GSON.fromJson(data, Outer.class); final String filename = file.getName(); final Changeset changeset = new Changeset(); changesetsByFile.put(filename, changeset); handleSection(changeset, "Attribute Types", outer.attributeTypes, this::parseAttributeTypes); handleSection( changeset, METACARD_TYPES_PROPERTY, outer.metacardTypes, this::parseMetacardTypes); handleSection(changeset, VALIDATORS_PROPERTY, outer.validators, this::parseValidators); handleSection(changeset, DEFAULTS_PROPERTY, outer.defaults, this::parseDefaults); handleSection(changeset, INJECTIONS_PROPERTY, outer.inject, this::parseInjections); handleSection( changeset, METACARD_VALIDATORS_PROPERTY, outer.metacardvalidators, this::registerMetacardValidators); }
Source:
<code>private boolean matchesParameterAndReturnTypes(Method method, List<Type> resolvedTypes, Type returnType) { checkState(method.getParameterCount() >= resolvedTypes.size(), "method %s has not enough arguments: %s (should have at least %s)", method.getName(), method.getParameterCount(), resolvedTypes.size()); Class<?>[] methodParameterJavaTypes = method.getParameterTypes(); for (int i = 0, methodParameterIndex = 0; i < resolvedTypes.size(); i++) { NullConvention nullConvention = argumentProperties.get(i).getNullConvention(); Class<?> type = getNullAwareContainerType(resolvedTypes.get(i).getJavaType(), nullConvention == USE_BOXED_TYPE); if (!methodParameterJavaTypes[methodParameterIndex].equals(type)) { return false; } <START> methodParameterIndex += (nullConvention == USE_NULL_FLAG || nullConvention == BLOCK_POSITION) ? 2 : 1; <END> } return method.getReturnType().equals(getNullAwareContainerType(returnType.getJavaType(), nullableResult)); }</code><technical_language>following: NullConvention enum java public enum NullConvention { RETURN_NULL_ON_NULL(1), USE_BOXED_TYPE(1), USE_NULL_FLAG(2), BLOCK_POSITION(2), /**/; private final int parameterCount; NullConvention(int methodParameterCount) { this.parameterCount = methodParameterCount; } public int getParameterCount() { return parameterCount; } } do java methodParameterIndex += nullConvention.getParameterCount();</technical_language>

Target:
private boolean matchesParameterAndReturnTypes(Method method, List<Type> resolvedTypes, Type returnType) { checkState(method.getParameterCount() >= resolvedTypes.size(), "method %s has not enough arguments: %s (should have at least %s)", method.getName(), method.getParameterCount(), resolvedTypes.size()); Class<?>[] methodParameterJavaTypes = method.getParameterTypes(); for (int i = 0, methodParameterIndex = 0; i < resolvedTypes.size(); i++) { NullConvention nullConvention = argumentProperties.get(i).getNullConvention(); Class<?> type = getNullAwareContainerType(resolvedTypes.get(i).getJavaType(), nullConvention == USE_BOXED_TYPE); if (!methodParameterJavaTypes[methodParameterIndex].equals(type)) { return false; } methodParameterIndex += nullConvention.getParameterCount(); } return method.getReturnType().equals(getNullAwareContainerType(returnType.getJavaType(), nullableResult)); }
Source:
<code><START> UnnnecessaryLoadingTest.CountingStore getCacheStore(Cache cache) { <END> return (UnnnecessaryLoadingTest.CountingStore) TestingUtil.getFirstLoader(cache); }</code><technical_language>'n' in "Unnnecessary"</technical_language>

Target:
UnnecessaryLoadingTest.CountingStore getCacheStore(Cache cache) { return (UnnecessaryLoadingTest.CountingStore) TestingUtil.getFirstLoader(cache); }
Source:
<code>public VaultRawSecret obtainSecret(String vaultSecretId) { Path secretPath = vaultPath.resolve(Paths.get(vaultSecretId)); if (!Files.exists(secretPath)) { return DefaultVaultRawSecret.empty(); } <START> try(InputStream is = Files.newInputStream(secretPath)) { <END> byte[] buf = new byte[is.available()]; is.read(buf); return DefaultVaultRawSecret.forByteArray(buf); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>RandomAccessFile instead for mmap access</technical_language>

Target:
public VaultRawSecret obtainSecret(String vaultSecretId) { Path secretPath = resolveSecretPath(vaultSecretId); if (!Files.exists(secretPath)) { return DefaultVaultRawSecret.forBuffer(Optional.empty()); } try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(secretPath, EnumSet.of(StandardOpenOption.READ))) { MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); return DefaultVaultRawSecret.forBuffer(Optional.of(mappedByteBuffer)); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public void saveLibraries(final Collection<Library> libraries) throws IOException { log.info("Migrating libraries..."); <START> Date now = new Date(); <END> User user = serviceManager.getAuthorizationManager().getCurrentUser(); for (Library library : libraries) { library.inheritPermissions(library.getSample()); valueTypeLookup.resolveAll(library); library.setLastModifier(user); library.setLastUpdated(now); library.getLibraryAdditionalInfo().setCreatedBy(user); library.getLibraryAdditionalInfo().setCreationDate(now); library.getLibraryAdditionalInfo().setUpdatedBy(user); library.getLibraryAdditionalInfo().setLastUpdated(now); if (replaceChangeLogs) { Collection<ChangeLog> changes = library.getChangeLog(); library.setId(serviceManager.getLibraryDao().save(library)); saveLibraryChangeLog(library, changes); } else { library.setId(serviceManager.getLibraryDao().save(library)); } log.debug("Saved library " + library.getAlias()); } log.info(libraries.size() + " libraries migrated."); }</code><technical_language>this set for migration</technical_language>

Target:
public void saveLibraries(final Collection<Library> libraries) throws IOException { log.info("Migrating libraries..."); User user = serviceManager.getAuthorizationManager().getCurrentUser(); for (Library library : libraries) { library.inheritPermissions(library.getSample()); valueTypeLookup.resolveAll(library); library.setLastModifier(user); library.setLastUpdated(timeStamp); library.getLibraryAdditionalInfo().setCreatedBy(user); library.getLibraryAdditionalInfo().setCreationDate(timeStamp); library.getLibraryAdditionalInfo().setUpdatedBy(user); library.getLibraryAdditionalInfo().setLastUpdated(timeStamp); if (replaceChangeLogs) { Collection<ChangeLog> changes = library.getChangeLog(); library.setId(serviceManager.getLibraryDao().save(library)); saveLibraryChangeLog(library, changes); } else { library.setId(serviceManager.getLibraryDao().save(library)); } log.debug("Saved library " + library.getAlias()); } log.info(libraries.size() + " libraries migrated."); }
Source:
<code>public Optional<Integer> getVal(ItemStack container) { <START> return Optional.of(container.getMaxDamage() - container.getItemDamage()); <END> }</code><technical_language>checking if ItemStack.isDamageable()</technical_language>

Target:
public Optional<Integer> getVal(ItemStack container) { if(container.getItem().isDamageable()) { return Optional.of(container.getMaxDamage() - container.getItemDamage()); } return Optional.empty(); }
Source:
<code>Aggregator[] getValueAggregators(TopNQuery query, BaseLongColumnValueSelector selector, Cursor cursor) { long key = selector.getLong(); <START> Aggregator[] aggs = aggregatesStore.get(key); <END> if (aggs == null) { aggs = BaseTopNAlgorithm.makeAggregators(cursor, query.getAggregatorSpecs()); aggregatesStore.put(key, aggs); } return aggs; }</code><technical_language>computeIfAbsent() computes hash time</technical_language>

Target:
Aggregator[] getValueAggregators(TopNQuery query, BaseLongColumnValueSelector selector, Cursor cursor) { long key = selector.getLong(); return aggregatesStore.computeIfAbsent( key, k -> BaseTopNAlgorithm.makeAggregators(cursor, query.getAggregatorSpecs()) ); }
Source:
<code>protected String getText() { if (missingFile.length() > 0) { return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_0, missingFile); } else { if (context == null) return super.getText(); String contextDescription; ICSourceNotFoundDescription description = context.getAdapter(ICSourceNotFoundDescription.class); if (description != <START> null) { <END> contextDescription = description.getDescription(); } else contextDescription = context.toString(); if (description.isAdress()) return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_8, contextDescription); return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_3, contextDescription); } }</code><technical_language>formatting</technical_language>

Target:
protected String getText() { if (missingFile.length() > 0) { return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_0, missingFile); } else { if (context == null) return super.getText(); String contextDescription; ICSourceNotFoundDescription description = context.getAdapter(ICSourceNotFoundDescription.class); if (description != null) contextDescription = description.getDescription(); else contextDescription = context.toString(); if (description.isAddress()) return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_8, contextDescription); return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_3, contextDescription); } }
Source:
<code><START> public void testOpenWithDownBroker() throws Exception { <END> String sinkstr = "{\n" + " \"type\": \"kafka\",\n" + " \"client.id\": \"kafkasink\",\n" + " \"bootstrap.servers\": \"localhost:7101\",\n" + " \"kafka.etc\": {\n" + " \"acks\": \"1\"\n" + " }\n" + "}"; KafkaSink sink = jsonMapper.readValue(sinkstr, new TypeReference<Sink>(){}); sink.open(); Assert.assertTrue(sink.isOpened()); sink.close(); }</code><technical_language>Test method name is 'testOpenWithDownBroker' shutting kafka broker? call kafkaServer.after() shutdown explicitly</technical_language>

Target:
public void testOpenWithDownBroker() throws Exception { String sinkstr = "{\n" + " \"type\": \"kafka\",\n" + " \"client.id\": \"kafkasink\",\n" + " \"bootstrap.servers\": \"localhost:1\",\n" + " \"kafka.etc\": {\n" + " \"acks\": \"1\"\n" + " }\n" + "}"; KafkaSink sink = jsonMapper.readValue(sinkstr, new TypeReference<Sink>(){}); sink.open(); Assert.assertTrue(sink.isOpened()); sink.close(); }
Source:
<code>public void reschedule_commands_from_storage_in_parallel_on_build_if_thread_spawning_allowed() { final String mainThreadName = Thread.currentThread().getName(); final StringBuilder threadNameUponScheduling = new StringBuilder(0); final CommandScheduler scheduler = threadAwareScheduler(threadNameUponScheduling); storeSingleCommandForRescheduling(); final CommandBus commandBus = CommandBus.newBuilder() .setCommandStore(commandStore) .setCommandScheduler(scheduler) .setThreadSpawnAllowed(true) .setAutoReschedule(true) .build(); assertNotNull(commandBus); try { <START> Thread.sleep(150); <END> } catch (InterruptedException e) { throw new IllegalStateException(e); } final ArgumentCaptor<Command> commandCaptor = ArgumentCaptor.forClass(Command.class); verify(scheduler, times(1)).schedule(commandCaptor.capture()); final String actualThreadName = threadNameUponScheduling.toString(); assertNotNull(actualThreadName); assertNotEquals(mainThreadName, actualThreadName); }</code><technical_language>is changed</technical_language>

Target:
public void reschedule_commands_from_storage_in_parallel_on_build_if_thread_spawning_allowed() { final String mainThreadName = Thread.currentThread().getName(); final StringBuilder threadNameUponScheduling = new StringBuilder(0); final CountDownLatch latch = new CountDownLatch(1); final CommandScheduler scheduler = threadAwareScheduler(threadNameUponScheduling, latch); storeSingleCommandForRescheduling(); final CommandBus commandBus = CommandBus.newBuilder() .setCommandStore(commandStore) .setCommandScheduler(scheduler) .setThreadSpawnAllowed(true) .setAutoReschedule(true) .build(); assertNotNull(commandBus); try { latch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } final ArgumentCaptor<Command> commandCaptor = ArgumentCaptor.forClass(Command.class); verify(scheduler, times(1)).schedule(commandCaptor.capture()); final String actualThreadName = threadNameUponScheduling.toString(); assertNotNull(actualThreadName); assertNotEquals(mainThreadName, actualThreadName); }
Source:
<code>public String getMode() { if (!isEnabled()) { return DISABLED_MODE; <START> } else if (opened) { <END> return ACTIVE_MODE; } return DEFAULT_MODE; }</code><technical_language>removed bit is important! needs if dropdown is focusedWidget (in other words, if is current selection tabbing) in order highlight widget yellow - returning ACTIVE_MODE does. find another workaround avoid TabbingManager, need some if tabbed</technical_language>

Target:
public String getMode() { if (!isEnabled()) { return DISABLED_MODE; } else if (opened || this.equals(TabbingManager.focusedWidget)) { return ACTIVE_MODE; } return DEFAULT_MODE; }
Source:
<code>public static <T> T first(Class<T>type){ <START> return findById(type, 1); <END> }</code><technical_language>object in database necessarily id of 1. I a implementation do a find order ascending id limit query a single item</technical_language>

Target:
public static <T> T first(Class<T>type){ List<T> list = findWithQuery(type, "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ROWID ASC LIMIT 1" ); if (list.isEmpty()) return null; return list.get(0); }
Source:
<code>private boolean makeGitHubTeamVisible(Channel channel, User sender, String team) { boolean result = false; if (!isSenderAuthorized(channel, sender)) { insufficientPermissionError(channel); return false; } OutputChannel out = channel.send(); try { GitHub github = GitHub.connect(); GHOrganization o = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION); final GHTeam ghTeam = o.getTeamByName(team); if (ghTeam == null) { out.message("No team for " + team); return false; } ghTeam.setPrivacy(GHTeam.Privacy.CLOSED); <START> String successMsg = "Made GitHub team " + team + " visible"; <END> out.message(successMsg); result = true; } catch (IOException e) { out.message("Failed to make GitHub team " + team + " visible: " + e.getMessage()); e.printStackTrace(); } return result; }</code><technical_language>reason a separate declaration? conform other out.message calls below</technical_language>

Target:
private boolean makeGitHubTeamVisible(Channel channel, User sender, String team) { boolean result = false; if (!isSenderAuthorized(channel, sender)) { insufficientPermissionError(channel); return false; } OutputChannel out = channel.send(); try { GitHub github = GitHub.connect(); GHOrganization o = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION); final GHTeam ghTeam = o.getTeamByName(team); if (ghTeam == null) { out.message("No team for " + team); return false; } ghTeam.setPrivacy(GHTeam.Privacy.CLOSED); out.message("Made GitHub team " + team + " visible"); result = true; } catch (IOException e) { out.message("Failed to make GitHub team " + team + " visible: " + e.getMessage()); e.printStackTrace(); } return result; }
Source:
<code>private <E extends Enum<E>> Class<E> determineEnumClass(ExtensionContext context) { Class enumClass = enumSource.value(); <START> if (enumClass.equals(NullEnum.class)) { <END> Method method = context.getRequiredTestMethod(); Class<?>[] parameterTypes = method.getParameterTypes(); Preconditions.condition(parameterTypes.length > 0, () -> "At least one parameter is required on test method: " + method.toGenericString()); Preconditions.condition(Enum.class.isAssignableFrom(parameterTypes[0]), () -> "First parameter must reference an Enum type (alternatively, use the annotation's 'value' parameter to specify the type explicitly): " + method.toGenericString()); enumClass = parameterTypes[0]; } return enumClass; }</code><technical_language>== suffice -- right</technical_language>

Target:
private <E extends Enum<E>> Class<E> determineEnumClass(ExtensionContext context) { Class enumClass = enumSource.value(); if (enumClass.equals(NullEnum.class)) { Method method = context.getRequiredTestMethod(); Class<?>[] parameterTypes = method.getParameterTypes(); Preconditions.condition(parameterTypes.length > 0, () -> "Test method must declare at least one parameter: " + method.toGenericString()); Preconditions.condition(Enum.class.isAssignableFrom(parameterTypes[0]), () -> "First parameter must reference an Enum type (alternatively, use the annotation's 'value' attribute to specify the type explicitly): " + method.toGenericString()); enumClass = parameterTypes[0]; } return enumClass; }
Source:
<code>public void testDateFormat4ms() { testAssumeColumnDetails_Dates( Arrays.asList( "02/29/20 00:00:00" ), "MM/dd/yy HH:mm:ss" ); <START> } <END></code><technical_language>if date is 02/10/12 00:00:00 ? Generally, of behavior changed ? of test cases changed output change ? Do run changes ? If not, failures expected ? outputing format changes another</technical_language>

Target:
public void testDateFormat4ms() { testAssumeColumnDetails_Dates( asList( "11/10/15 11:57:33" ), "MM/dd/yy HH:mm:ss" ); }
Source:
<code>public synchronized Observable<T> attach(Observer<T> observer) { if (observer == null) { throw new DeveloperError("You cannot attach a null observer"); } <START> if (observers.contains(observer)) { <END> return this; } observers.add(observer); return this; }</code><technical_language>Better: if observer add it, return this anyway</technical_language>

Target:
public synchronized Observable<T> attach(Observer<T> observer) { if (observer == null) { throw new DeveloperError("You cannot attach a null observer"); } if (!observers.contains(observer)) { observers.add(observer); } return this; }
Source:
<code>public Navigation(ComponentContainer container) { super(container.$form()); <START> activity = container.$context(); <END> apiKey = ""; startLocation = new GeoPoint(0, 0); endLocation = new GeoPoint(0, 0); method = TransportMethod.DEFAULT; }</code><technical_language>protected field form in AndroidNonvisibleComponent is Activity, need store a separate field in this class</technical_language>

Target:
public Navigation(ComponentContainer container) { super(container.$form()); apiKey = ""; startLocation = new GeoPoint(0.0, 0.0); endLocation = new GeoPoint(0.0, 0.0); method = TransportMethod.DEFAULT; }
Source:
<code>public PageBlobAsyncClient asPageBlobAsyncClient() { return new SpecializedBlobClientBuilder() <START> .blobAsyncClient(this) <END> .buildPageBlobAsyncClient(); }</code><technical_language>this passed argument is iffy me. find a cyclic dependency graph. prefer pass in relevant arguments create specialised client (ie. connection string, proxy, transport type, etc. etc.)</technical_language>

Target:
public PageBlobAsyncClient asPageBlobAsyncClient() { return prepareBuilder().buildPageBlobAsyncClient(); }
Source:
<code>public User setUserActivationKey(User user) { String token = RandomStringUtils.randomAlphanumeric(20); long time = System.currentTimeMillis() + getValidTime(); String hashedKey = Security.encodeString(token); String activationKey = hashedKey+":"+time; LoginCredential credentials = dao.getLoginCredential(user); credentials.setActivationKey(activationKey); dao.setUserActivationKey(credentials); <START> String link = Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GP_HOST_URL) + token; <END> String msg = "Hi " + user.getUsername() + ", \n It looks like you like to change your password, click on the following link to do so.\n" + link + " please disregard this email if you didn't innitiate the password reset process The openmrs Team"; Message mail = new Message(); mail.setId(20); mail.setRecipients(user.getEmail()); mail.setSender(Context.getAdministrationService().getGlobalProperty("mail.from")); mail.setContentType(Context.getAdministrationService().getGlobalProperty("mail.default_content_type")); mail.setSubject("Password Reset Request"); mail.setContent(msg); mail.setSentDate(new Date()); try { Context.getMessageService().sendMessage(mail); } catch (MessageException e) { } return user; }</code><technical_language>this is correct, URL a placeholder replace token, appending</technical_language>

Target:
public User setUserActivationKey(User user) throws MessageException { String token = RandomStringUtils.randomAlphanumeric(20); long time = System.currentTimeMillis() + getValidTime(); String hashedKey = Security.encodeString(token); String activationKey = hashedKey + ":" + time; LoginCredential credentials = dao.getLoginCredential(user); credentials.setActivationKey(activationKey); dao.setUserActivationKey(credentials); MessageSourceService messages = Context.getMessageSourceService(); AdministrationService adminService = Context.getAdministrationService(); String link = adminService.getGlobalProperty(OpenmrsConstants.GP_HOST_URL) .replace("{activationKey}", token); String msg = messages.getMessage("mail.passwordreset.content").replace("{name}", user.getUsername()) .replace("{link}", link) .replace("{time}", String.valueOf(getValidTime() / 60000)); Context.getMessageService().sendMessage(user.getEmail(), adminService.getGlobalProperty("mail.from"), messages.getMessage("mail.passwordreset.subject"), msg); return user; }
Source:
<code>public void testNegativeBlockTime() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 20; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); ByteBuffer buffer = pool.allocate(size, 0); pool.deallocate(buffer); try { buffer = pool.allocate(size, -maxBlockTimeInMs); <START> } catch (IllegalArgumentException e) { <END> } pool.deallocate(buffer); assertEquals(size, pool.capacity()); }</code><technical_language>do catch IllegalArgumentException? expecting one</technical_language>

Target:
public void testNegativeBlockTime() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 20; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); ByteBuffer buffer = pool.allocate(size, 0); pool.deallocate(buffer); try { pool.allocate(size, -maxBlockTimeInMs); fail("IllegalArgumentException should have been thrown when timeToBlockInMs is negative."); } catch (IllegalArgumentException e) { } try { pool.allocate((int) capacity + 1, maxBlockTimeInMs); fail( "IllegalArgumentException should have been thrown when requested buffer size is larger than the buffer pool's capacity."); } catch (IllegalArgumentException e) { } assertEquals(size, pool.capacity()); }
Source:
<code>public TypedValue<?> apply(TypedValue<?> t) { if (runningExtremes == null) { this.runningExtremes = new RunningExtremes(this.options.getWindowSize()); } <START> final double value = ((Number) t.getValue()).doubleValue(); <END> return TypedValues.newDoubleValue(this.runningExtremes.updateAndGetMax(value)); }</code><technical_language>prefer checking DataType returning NaN double if input is numeric. This is prevent log flooding if input is numeric</technical_language>

Target:
public TypedValue<?> apply(TypedValue<?> t) { if (runningExtremum == null) { this.runningExtremum = new RunningExtremum<>(this.options.getWindowSize()); } final double value = ((Number) t.getValue()).doubleValue(); this.runningExtremum.add(value); return TypedValues.newDoubleValue(this.runningExtremum.max()); }
Source:
<code>public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("accountExpirationTime"); <START> attr.setDisplayName("Accoun expiration."); <END> attr.setType(Integer.class.getName()); attr.setDescription("Account expiration."); return attr; }</code><technical_language>"Account" instead of "Accoun"</technical_language>

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("accountExpirationTime"); attr.setDisplayName("Account expiration."); attr.setType(Integer.class.getName()); attr.setDescription("Account expiration."); return attr; }
Source:
<code>private Optional<LogFile> createLogFile(Path path) { <START> Optional<LogFileName> logFileName = LogFileName.parseHistoryLogFileName(masterLogFile.getFileName().toString(), path.getFileName().toString()); <END> if (!logFileName.isPresent()) { return Optional.empty(); } BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException e) { return Optional.empty(); } return Optional.of(new LogFile(path, logFileName.get(), fileAttributes.size())); }</code><technical_language>Static import</technical_language>

Target:
private Optional<LogFile> createLogFile(Path path) { Optional<LogFileName> logFileName = parseHistoryLogFileName(masterLogFile.getFileName().toString(), path.getFileName().toString()); if (!logFileName.isPresent()) { return Optional.empty(); } BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException e) { return Optional.empty(); } return Optional.of(new LogFile(path, logFileName.get(), fileAttributes.size())); }
Source:
<code>private void addComplaintData(final SurveillanceReportWorkbookWrapper workbook, final Row row, final Complaint complaint) { addDataCell(workbook, row, COL_COMPLAINT_DATE, dateFormatter.format(complaint.getReceivedDate())); addDataCell(workbook, row, COL_ACB_COMPLAINT_ID, complaint.getAcbComplaintId()); addDataCell(workbook, row, COL_ONC_COMPLAINT_ID, complaint.getOncComplaintId()); addDataCell(workbook, row, COL_SUMMARY, complaint.getSummary()); addDataCell(workbook, row, COL_ACTIONS_RESPONSE, complaint.getActions()); addDataCell(workbook, row, COL_COMPLAINANT_TYPE, complaint.getComplainantType() != null ? complaint.getComplainantType().getName() : ""); addDataCell(workbook, row, COL_COMPLAINANT_TYPE_OTHER, complaint.getComplainantTypeOther()); addDataCell(workbook, row, COL_COMPLAINANT_CONTACTED, complaint.isComplainantContacted() ? "Yes" : "No"); addDataCell(workbook, row, COL_DEVELOPER_CONTACTED, complaint.isDeveloperContacted() ? "Yes" : "No"); addDataCell(workbook, row, COL_ATL_CONTACTED, complaint.isOncAtlContacted() ? "Yes" : "No"); <START> addDataCell(workbook, row, COL_COMPLAINT_STATUS, complaint.getClosedDate() == null ? "Open" : "Closed"); <END> addDataCell(workbook, row, COL_FLAGGED_FOR_ONC, complaint.isFlagForOncReview() ? "Yes" : "No"); }</code><technical_language>"Open" "Closed" strings constants pull enum</technical_language>

Target:
private void addComplaintData(final SurveillanceReportWorkbookWrapper workbook, final Row row, final Complaint complaint) { addDataCell(workbook, row, COL_COMPLAINT_DATE, dateFormatter.format(complaint.getReceivedDate())); addDataCell(workbook, row, COL_ACB_COMPLAINT_ID, complaint.getAcbComplaintId()); addDataCell(workbook, row, COL_ONC_COMPLAINT_ID, complaint.getOncComplaintId()); addDataCell(workbook, row, COL_SUMMARY, complaint.getSummary()); addDataCell(workbook, row, COL_ACTIONS_RESPONSE, complaint.getActions()); addDataCell(workbook, row, COL_COMPLAINANT_TYPE, complaint.getComplainantType() != null ? complaint.getComplainantType().getName() : ""); addDataCell(workbook, row, COL_COMPLAINANT_TYPE_OTHER, complaint.getComplainantTypeOther()); addDataCell(workbook, row, COL_COMPLAINANT_CONTACTED, complaint.isComplainantContacted() ? BOOLEAN_YES : BOOLEAN_NO); addDataCell(workbook, row, COL_DEVELOPER_CONTACTED, complaint.isDeveloperContacted() ? BOOLEAN_YES : BOOLEAN_NO); addDataCell(workbook, row, COL_ATL_CONTACTED, complaint.isOncAtlContacted() ? BOOLEAN_YES : BOOLEAN_NO); addDataCell(workbook, row, COL_COMPLAINT_STATUS, complaint.getClosedDate() == null ? Complaint.COMPLAINT_OPEN : Complaint.COMPLAINT_CLOSED); addDataCell(workbook, row, COL_FLAGGED_FOR_ONC, complaint.isFlagForOncReview() ? BOOLEAN_YES : BOOLEAN_NO); }
Source:
<code>public Optional<Response> handle(HandlerInput handlerInput, IntentRequest intentRequest) { <START> final List<Restaurant> restaurants = SkillUtils.getRestaurantsByMeal(Meal.COFFEE, SkillData.CITY_INFORMATION.getRestaurants()); <END> final Restaurant restaurant = restaurants.get(SkillUtils.getRandomIndexInRange(restaurants.size(), 0)); final ResourceBundle messages = SkillUtils.getMessages(handlerInput); final Map<String, Object> sessionAttributes = handlerInput.getAttributesManager().getSessionAttributes(); sessionAttributes.put("restaurant", restaurant.getName()); final String speechOutput = String.format(messages.getString("COFFEE_SPEECH"), restaurant.getName()); return handlerInput.getResponseBuilder() .withSpeech(speechOutput) .withReprompt(speechOutput) .build(); }</code><technical_language>A lot of this logic reused for handler. Is a generify save some code duplication</technical_language>

Target:
public Optional<Response> handle(HandlerInput handlerInput, IntentRequest intentRequest) { return SkillUtils.getRestaurantDataAsResponse(handlerInput, true, Meal.COFFEE, "Messages", "COFFEE_SPEECH", SkillData.CITY_INFORMATION.getRestaurants()); }