auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public byte[] getCacheKey() { int size = 1; List<byte[]> columns = Lists.newArrayListWithExpectedSize(this.columns.size()); for (String column : this.columns) { final byte[] bytes = StringUtils.toUtf8(column); columns.add(bytes); size += bytes.length + 1; } final ByteBuffer bytes = ByteBuffer.allocate(size).put(LIST_CACHE_PREFIX); for (byte[] column : columns) { bytes.put(column); <START> bytes.put((byte) 0); <END> } return bytes.array(); }</code><technical_language>Other places bytes render byte array invalid UTF8. I 0xFF</technical_language>

Target:
public byte[] getCacheKey() { int size = 1; List<byte[]> columns = Lists.newArrayListWithExpectedSize(this.columns.size()); for (String column : this.columns) { final byte[] bytes = StringUtils.toUtf8(column); columns.add(bytes); size += bytes.length + 1; } final ByteBuffer bytes = ByteBuffer.allocate(size).put(LIST_CACHE_PREFIX); for (byte[] column : columns) { bytes.put(column); bytes.put((byte) 0xff); } return bytes.array(); }
Source:
<code>public Map<DateTime, TimeZoneHistory> timeZoneHistoryList(@Scope({OAuthScope.ADMINISTRATION_READ}) final AccessToken accessToken) { <START> return timeZoneHistoryDAODynamoDB.getAllTimeZones(19670); <END> }</code><technical_language>@pims: explain this number, a static constant</technical_language>

Target:
public Map<DateTime, TimeZoneHistory> timeZoneHistoryList(@Scope({OAuthScope.ADMINISTRATION_READ}) final AccessToken accessToken) { return timeZoneHistoryDAODynamoDB.getAllTimeZones(accessToken.accountId); }
Source:
<code>public static Iterable<Model> parseYaml(Iterable<IFile> files) { if (files == null || Iterables.isEmpty(files)) { return Lists.newArrayList(); } final SwaggerSchema schema = Activator.getDefault().getSchema(); final ObjectMapper mapper = createMapper(); final List<Model> modelSet = Lists.newArrayList(); for (IFile file : files) { Model model = new Model(schema, file.getFullPath()); try { mapper.reader() .withAttribute(ATTRIBUTE_MODEL, model) .withAttribute(ATTRIBUTE_PARENT, null) .withAttribute(ATTRIBUTE_POINTER, JsonPointer.compile("")) .withType(AbstractNode.class) <START> .readValue(file.getLocationURI().toURL()); <END> } catch (IllegalArgumentException | IOException e) { e.printStackTrace(); } modelSet.add(model); } return modelSet; }</code><technical_language>ObjectReader construct is identical created inparseYaml(SwaggerSchema schema, String text). reuse code</technical_language>

Target:
public static Iterable<Model> parseYaml(Iterable<IFile> files) { if (files == null || Iterables.isEmpty(files)) { return Lists.newArrayList(); } final SwaggerSchema schema = Activator.getDefault().getSchema(); final List<Model> models = Lists.newArrayList(); for (IFile file : files) { Model model = new Model(schema, file.getFullPath()); try { reader(model).readValue(file.getLocationURI().toURL()); } catch (IllegalArgumentException | IOException e) { e.printStackTrace(); continue; } models.add(model); } return models; }
Source:
<code>public void init() { <START> registry = ModelRegistryService.getInstance(null); <END> graph = mock(ModelGraph.class); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); }</code><technical_language>a constant instead of null code easier read this place pls</technical_language>

Target:
public void init() { registry = ModelRegistryService.getInstance(context); graph = mock(ModelGraph.class); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); }
Source:
<code><START> @Override public List findElements(String by, String using) { <END> return super.findElements(by, using); }</code><technical_language>@SrinivasanTarget forgot change this string java @Override public List<T> findElements(String by, String using)</technical_language>

Target:
@Override public List<T> findElements(String by, String using) { return super.findElements(by, using); }
Source:
<code>private TreeSet<Entry<String, File>> jarsFirstSortedPluginsSet( Map<String, File> activePlugins) { TreeSet<Entry<String, File>> sortedPlugins = Sets.newTreeSet(new Comparator<Entry<String, File>>() { @Override public int compare(Entry<String, File> entry1, Entry<String, File> entry2) { String file1 = entry1.getValue().getName(); String file2 = entry2.getValue().getName(); int cmp = file1.compareTo(file2); if (file1.endsWith(".jar")) { return (file2.endsWith(".jar") ? cmp : -1); } else { return (file2.endsWith(".jar") ? +1 : cmp); } } }); <START> Iterator<Entry<String, File>> it = activePlugins.entrySet().iterator(); while (it.hasNext()) { Entry<String,File> entry = it.next(); sortedPlugins.add( new AbstractMap.SimpleImmutableEntry<String, File>( entry.getKey(), entry.getValue())); } <END> return sortedPlugins; }</code><technical_language>Yes, this work creates a new entry. extract a method called "addAllEntries()" more readable? method = :-)</technical_language>

Target:
private TreeSet<Entry<String, File>> jarsFirstSortedPluginsSet( Map<String, File> activePlugins) { TreeSet<Entry<String, File>> sortedPlugins = Sets.newTreeSet(new Comparator<Entry<String, File>>() { @Override public int compare(Entry<String, File> entry1, Entry<String, File> entry2) { String file1 = entry1.getValue().getName(); String file2 = entry2.getValue().getName(); int cmp = file1.compareTo(file2); if (file1.endsWith(".jar")) { return (file2.endsWith(".jar") ? cmp : -1); } else { return (file2.endsWith(".jar") ? +1 : cmp); } } }); addAllEntries(activePlugins, sortedPlugins); return sortedPlugins; }
Source:
<code>static Map<String, String> collectQuery(List<NameValuePair> args) { <START> val result = new HashMap<String, String>(); <END> for (val pair : args) { result.put(pair.getName().toLowerCase(), pair.getValue()); } return result; }</code><technical_language>ImmutableMap.Builder or: java import static Collectors.toImmutableMap; ... args.stream().[stuff].collect(toImmutableMap)</technical_language>

Target:
static Map<String, String> collectQuery(List<NameValuePair> args) { val result = new ImmutableMap.Builder<String, String>(); for (val pair : args) { result.put(pair.getName().toLowerCase(), pair.getValue()); } return result.build(); }
Source:
<code>private String asReference(String repoLocation, String path, String projectName, String tagName) { StringBuffer buffer = new StringBuffer(); buffer.append("scm:git:"); buffer.append(repoLocation); if (path != null) { Path projectPath = new Path(path); buffer.append(";path=\""); buffer.append(projectPath.toString()); buffer.append('"'); if (!projectPath.lastSegment().equals(projectName)) { buffer.append(";project=\""); buffer.append(projectName); buffer.append('"'); } } <START> if (tagName != null && !tagName.equals("HEAD")) { END> buffer.append(";tag="); buffer.append(tagName); } return buffer.toString(); }</code><technical_language>This if copied CVS one. HEAD sense in a Git checkout anyway? idea (behind CVS) write out 'default' for needed e.g. default HEAD. Git default 'master' instead</technical_language>

Target:
private String asReference(String repoLocation, String path, String projectName, String tagName) { final StringBuffer buffer = new StringBuffer(); buffer.append("scm:git:"); buffer.append(repoLocation); if (path != null) { final Path projectPath = new Path(path); buffer.append(";path=\""); buffer.append(projectPath.toString()); buffer.append('"'); if (!projectPath.lastSegment().equals(projectName)) { buffer.append(";project=\""); buffer.append(projectName); buffer.append('"'); } } if (tagName != null && !tagName.equals("master")) { buffer.append(";tag="); buffer.append(tagName); } return buffer.toString(); }
Source:
<code>public static boolean checkAndRequestPermissions(final Activity activity, final Type type) { final Set<Type> types = new HashSet<>(); types.add(type); <START> return checkAndRequestPermissions(activity, types); <END> }</code><technical_language>return checkAndRequestPermissions(activity, EnumSet.of(type));</technical_language>

Target:
public static boolean checkAndRequestPermissions(final Activity activity, final Type type) { return checkAndRequestPermissions(activity, EnumSet.of(type)); }
Source:
<code>public static QueryContext context(Session ses) { <START> return (QueryContext)ses.getVariable("IGNITE_QUERY_CONTEXT").getObject(); <END> }</code><technical_language>QCTX_VARIABLE_NAME</technical_language>

Target:
public static QueryContext context(Session ses) { return (QueryContext)ses.getVariable(QCTX_VARIABLE_NAME).getObject(); }
Source:
<code>public void testSanitizeForJs() { <START> <END> String unsanitized = "\\ \" ' #"; String expected = "\\\\ \\&quot; \\&#39; \\#"; String sanitized = Sanitizer.sanitizeForJs(unsanitized); assertEquals(null, Sanitizer.sanitizeForJs(null)); assertEquals(expected, sanitized); }</code><technical_language>Unnecessary blank lines a method - remove slightly shorter</technical_language>

Target:
public void testSanitizeForJs() { sanitizeJs_receivesNull_returnsNull(); sanitizeJs_receivesUnsanitized_returnsSanitized(); }
Source:
<code>private static RowGroupStatistics buildActualRowGroupStatistics(int rowGroupIndex, Map<StreamId, List<RowGroupIndex>> actualRowGroupStatistics) { return new RowGroupStatistics( BOTH, actualRowGroupStatistics.entrySet() .stream() <START> .collect(Collectors.toMap((entry) -> entry.getKey().getColumn(), (entry) -> entry.getValue().get(rowGroupIndex).getColumnStatistics()))); <END> }</code><technical_language>nit: write entry -> ..</technical_language>

Target:
private static RowGroupStatistics buildActualRowGroupStatistics(int rowGroupIndex, Map<StreamId, List<RowGroupIndex>> actualRowGroupStatistics) { return new RowGroupStatistics( BOTH, actualRowGroupStatistics.entrySet() .stream() .collect(Collectors.toMap(entry -> entry.getKey().getColumn(), entry -> entry.getValue().get(rowGroupIndex).getColumnStatistics()))); }
Source:
<code>public Object handle(UnitOfWork<? extends CommandMessage<?>> unitOfWork, InterceptorChain interceptorChain) throws Exception { return InterceptorChainParameterResolverFactory.callWithInterceptorChain(interceptorChain, () -> { if (!delegate.canHandle(unitOfWork.getMessage())) { return interceptorChain.proceed(); } return delegate.handle(unitOfWork.getMessage(), target); <START> <END> }); }</code><technical_language>replace this for: java !delegate.canHandle(unitOfWork.getMessage()) ? interceptorChain.proceed() : delegate.handle(unitOfWork.getMessage(), target)</technical_language>

Target:
public Object handle(UnitOfWork<? extends CommandMessage<?>> unitOfWork, InterceptorChain interceptorChain) throws Exception { return InterceptorChainParameterResolverFactory.callWithInterceptorChain( interceptorChain, () -> delegate.canHandle(unitOfWork.getMessage()) ? delegate.handle(unitOfWork.getMessage(), target) : interceptorChain.proceed()); }
Source:
<code>public void shouldGetConflictExceptionFor_markChargeAsCaptureApproved_whenNoChargeExists() { String extChargeId = addChargeAndCardDetails(EXPIRED, ServicePaymentReference.of("ref"), ZonedDateTime.now().minusMinutes(90)); final String expectedErrorMessage = format("Operation for charge conflicting, %s, attempt to perform delayed capture on charge not in AWAITING CAPTURE REQUEST state.", extChargeId); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId) .postMarkChargeAsCaptureApproved() .statusCode(CONFLICT.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains(expectedErrorMessage)) <START> .body("error_identifier", Matchers.is(ErrorIdentifier.GENERIC.toString())); <END> }</code><technical_language>this</technical_language>

Target:
public void shouldGetConflictExceptionFor_markChargeAsCaptureApproved_whenNoChargeExists() { String extChargeId = addChargeAndCardDetails(EXPIRED, ServicePaymentReference.of("ref"), ZonedDateTime.now().minusMinutes(90)); final String expectedErrorMessage = format("Operation for charge conflicting, %s, attempt to perform delayed capture on charge not in AWAITING CAPTURE REQUEST state.", extChargeId); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId) .postMarkChargeAsCaptureApproved() .statusCode(CONFLICT.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains(expectedErrorMessage)) .body("error_identifier", is(ErrorIdentifier.GENERIC.toString())); }
Source:
<code>private static Map<String, PartitionStatistics> getPartitionsStatistics(SemiTransactionalHiveMetastore metastore, SchemaTableName table, List<HivePartition> hivePartitions) { if (hivePartitions.isEmpty()) { return ImmutableMap.of(); } boolean unpartitioned = hivePartitions.stream().anyMatch(partition -> partition.getPartitionId().equals(UNPARTITIONED_ID)); if (unpartitioned) { checkArgument(hivePartitions.size() == 1, "expected only one hive partition"); } <START> if (unpartitioned) { <END> return ImmutableMap.of(UNPARTITIONED_ID, metastore.getTableStatistics(table.getSchemaName(), table.getTableName())); } else { Set<String> partitionNames = hivePartitions.stream() .map(HivePartition::getPartitionId) .collect(toImmutableSet()); return metastore.getPartitionStatistics(table.getSchemaName(), table.getTableName(), partitionNames); } }</code><technical_language>perhaps, combine if statements</technical_language>

Target:
private static Map<String, PartitionStatistics> getPartitionsStatistics(SemiTransactionalHiveMetastore metastore, SchemaTableName table, List<HivePartition> hivePartitions) { if (hivePartitions.isEmpty()) { return ImmutableMap.of(); } boolean unpartitioned = hivePartitions.stream().anyMatch(partition -> partition.getPartitionId().equals(UNPARTITIONED_ID)); if (unpartitioned) { checkArgument(hivePartitions.size() == 1, "expected only one hive partition"); return ImmutableMap.of(UNPARTITIONED_ID, metastore.getTableStatistics(table.getSchemaName(), table.getTableName())); } Set<String> partitionNames = hivePartitions.stream() .map(HivePartition::getPartitionId) .collect(toImmutableSet()); return metastore.getPartitionStatistics(table.getSchemaName(), table.getTableName(), partitionNames); }
Source:
<code>public CatalogProtos.FragmentProto getProto() { JdbcFragmentProto.Builder builder = JdbcFragmentProto.newBuilder(); builder.setInputSourceId(this.inputSourceId); builder.setUri(this.uri); if(hostNames != null) { List inputList = new ArrayList<>(); inputList.addAll(Arrays.asList(hostNames)); <START> builder.addAllHosts(inputList); <END> } CatalogProtos.FragmentProto.Builder fragmentBuilder = CatalogProtos.FragmentProto.newBuilder(); fragmentBuilder.setId(this.inputSourceId); fragmentBuilder.setDataFormat("JDBC"); fragmentBuilder.setContents(builder.buildPartial().toByteString()); return fragmentBuilder.build(); }</code><technical_language>rewritten Arrays.asList()</technical_language>

Target:
public CatalogProtos.FragmentProto getProto() { JdbcFragmentProto.Builder builder = JdbcFragmentProto.newBuilder(); builder.setInputSourceId(this.inputSourceId); builder.setUri(this.uri); if(hostNames != null) { builder.addAllHosts(Arrays.asList(hostNames)); } CatalogProtos.FragmentProto.Builder fragmentBuilder = CatalogProtos.FragmentProto.newBuilder(); fragmentBuilder.setId(this.inputSourceId); fragmentBuilder.setDataFormat("JDBC"); fragmentBuilder.setContents(builder.buildPartial().toByteString()); return fragmentBuilder.build(); }
Source:
<code>public Object clone() throws CloneNotSupportedException { <START> return super.clone(); END> }</code><technical_language>Please change this implementation throw CloneNotSupportedException. This implementation result in sharing references List field items in list clones. A deep copy approach superclass work, worth effort. Thanks</technical_language>

Target:
public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone is not supported for the RunIngestModulesAction"); }
Source:
<code>private void compareWorkAndCreditNameVisibility(Work work) { Visibility workVisibility = work.getVisibility(); for (Contributor contributor : work.getWorkContributors().getContributor()) { if (contributor.getCreditName() != null && contributor.getCreditName().getVisibility() != null && contributor.getCreditName().getVisibility().isMoreRestrictiveThan(workVisibility)) { <START> LOGGER.warn("Client posting work with visibility ({}) less restrictive than its contributor credit name ({})", <END> new Object[] { work.getWorkTitle().getTitle(), workVisibility.toString(), contributor.getCreditName().getContent(), contributor.getCreditName().getVisibility().toString() }); } } }</code><technical_language>lets put this in error log, notice</technical_language>

Target:
private void compareWorkAndCreditNameVisibility(Work work) { Visibility workVisibility = work.getVisibility(); for (Contributor contributor : work.getWorkContributors().getContributor()) { if (contributor.getCreditName() != null && contributor.getCreditName().getVisibility() != null && contributor.getCreditName().getVisibility().isMoreRestrictiveThan(workVisibility)) { LOGGER.error("Client posting work with visibility ({}) less restrictive than its contributor credit name ({})", new Object[] { work.getWorkTitle().getTitle(), workVisibility.toString(), contributor.getCreditName().getContent(), contributor.getCreditName().getVisibility().toString() }); } } }
Source:
<code>public static synchronized boolean reload() { LOGGER.info("Configuration is being reloaded"); InputStream stream; <START> Long default_max_age; <END> String default_url; try { PROPERTIES.clear(); stream = new FileInputStream(PATH); PROPERTIES.load(stream); stream.close(); default_url = PROPERTIES.getProperty(ACTION_URL_PROP); if (!Utils.isValidURL(default_url)) { LOGGER.error("Invalid configuration value in " + PATH + " file " + ACTION_URL_PROP + ": " + default_url); return false; } try { default_max_age = Long.parseLong(PROPERTIES.getProperty(MAX_AGE_PROP)); } catch (NumberFormatException nfe) { LOGGER.error("Invalid configuration value in " + PATH + " file " + MAX_AGE_PROP + ": " + nfe); return false; } } catch (IOException e) { default_url = DEFAULT_PERSEO_FE_URL; default_max_age = DEFAULT_MAX_AGE; } String perseo_fe_url = System.getenv(PERSEO_FE_URL_ENV); perseo_fe_url = perseo_fe_url != null ? perseo_fe_url : default_url; if (Utils.isValidURL(perseo_fe_url)) { actionRule = perseo_fe_url + "/actions/do"; } else { LOGGER.error("Invalid configuration environment var value for " + PERSEO_FE_URL_ENV + ": " + perseo_fe_url); return false; } LOGGER.debug("actionRule: " + actionRule); String max_age_string = System.getenv(PERSEO_MAX_AGE_ENV); try { maxAge = max_age_string != null ? Long.parseLong(max_age_string) : default_max_age; } catch (NumberFormatException nfe) { LOGGER.error("Invalid configuration environment var value for " + PERSEO_MAX_AGE_ENV + ": " + nfe); return false; } return true; }</code><technical_language>I understand, Perseo Core code style camelCase for variable names</technical_language>

Target:
public static synchronized boolean reload() { LOGGER.info("Configuration is being reloaded"); InputStream stream; String defaultMaxAge; String defaultURL; String actionPath = "/actions/do"; try { PROPERTIES.clear(); stream = new FileInputStream(PATH); PROPERTIES.load(stream); stream.close(); defaultURL = PROPERTIES.getProperty(ACTION_URL_PROP); defaultMaxAge = PROPERTIES.getProperty(MAX_AGE_PROP); } catch (IOException e) { defaultURL = DEFAULT_PERSEO_FE_URL; defaultMaxAge = String.valueOf(DEFAULT_MAX_AGE); } String perseoFeURLEnv = System.getenv(PERSEO_FE_URL_ENV); perseoFeURLEnv = perseoFeURLEnv != null ? perseoFeURLEnv : defaultURL; if (Utils.isValidURL(perseoFeURLEnv)) { actionRule = perseoFeURLEnv.contains(actionPath) ? perseoFeURLEnv : perseoFeURLEnv + actionPath; } else { LOGGER.error("Invalid value for " + PERSEO_FE_URL_ENV + ": " + perseoFeURLEnv); return false; } String maxAgeEnv = System.getenv(PERSEO_MAX_AGE_ENV); try { maxAge = maxAgeEnv != null ? Long.parseLong(maxAgeEnv) : Long.parseLong(defaultMaxAge); } catch (NumberFormatException nfe) { LOGGER.error("Invalid value for " + PERSEO_MAX_AGE_ENV + ": " + nfe); return false; } return true; }
Source:
<code>private boolean isIncrementalAlarm(String reductionKey, OnmsAlarm alarm) { <START> return outstandingAlarms.containsKey(reductionKey) && <END> alarmEqualityChecker.equalsExcludingOnFirst(protobufMapper.toAlarm(alarm).build(), outstandingAlarms.get(reductionKey)); }</code><technical_language>Multiple threads call updateAlarm time, need usage of outstandingAlarms map is thread safe</technical_language>

Target:
private boolean isIncrementalAlarm(String reductionKey, OnmsAlarm alarm) { OpennmsModelProtos.Alarm existingAlarm = outstandingAlarms.get(reductionKey); return existingAlarm != null && alarmEqualityChecker.equalsExcludingOnFirst(protobufMapper.toAlarm(alarm), existingAlarm); }
Source:
<code>public UserInterface getDefaultUI() { <START> if (isHeadless()) return null; <END> if (defaultUI != null) return defaultUI; if (uiList().isEmpty()) return null; return uiList().get(0); }</code><technical_language>I this. total sense return null in a headless context. if downstream code deal it-tough. should, however, add @return clause of UIService interface's getDefaultUI() declaration, is clear</technical_language>

Target:
public UserInterface getDefaultUI() { if (isHeadless()) return HeadlessUI.getInstance(); if (defaultUI != null) return defaultUI; if (uiList().isEmpty()) return null; return uiList().get(0); }
Source:
<code>protected InternalSecurityContext( String username ) { this.username = username; <START> principals.add(SimplePrincipal.newInstance(username)); <END> }</code><technical_language>Actually, recommend initializing principals Collections.singletonList(SimplePrincipal.newInstance(username)). resulting list is immutable efficient implementation</technical_language>

Target:
protected InternalSecurityContext( String username ) { this.username = username; }
Source:
<code>private synchronized OutputStream addPostSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { ArrayList<ProcessingStep> steps = new ArrayList<>(); steps.add(new SignatureVerifier()); Set<String> skipChecksums = ARTIFACT_MD5_CHECKSUM_ENABLED ? <START> Collections.<String> <END> emptySet() : Collections.singleton(ChecksumUtilities.MD5); addChecksumVerifiers(descriptor, steps, skipChecksums, IArtifactDescriptor.ARTIFACT_CHECKSUM); if (steps.isEmpty()) return destination; ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); return handler.link(stepArray, destination, monitor); }</code><technical_language>needed Java 8</technical_language>

Target:
private synchronized OutputStream addPostSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { ArrayList<ProcessingStep> steps = new ArrayList<>(); steps.add(new SignatureVerifier()); Set<String> skipChecksums = ARTIFACT_MD5_CHECKSUM_ENABLED ? Collections.emptySet() : Collections.singleton(ChecksumUtilities.MD5); addChecksumVerifiers(descriptor, steps, skipChecksums, IArtifactDescriptor.ARTIFACT_CHECKSUM); if (steps.isEmpty()) return destination; ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); return handler.link(stepArray, destination, monitor); }
Source:
<code>private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits) { <START> return new SearchHitsImpl<String>(1, TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); <END> }</code><technical_language>suggestion return new SearchHitsImpl<String>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null);</technical_language>

Target:
private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits) { return new SearchHitsImpl<String>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); }
Source:
<code>public void run() { try { stats.addQueuedTime(Duration.nanosSince(queuedTime)); long start = System.nanoTime(); backupStore.get().backupShard(uuid, source); stats.addCopyShardDataRate(new DataSize(source.length(), BYTE), Duration.nanosSince(start)); <START> if (enableVerification) { <END> File restored = new File(localFileSystem.get().pathToFile(storageService.getStagingFile(uuid)) + ".validate"); backupStore.get().restoreShard(uuid, restored); if (!filesEqual(source, restored)) { stats.incrementBackupCorruption(); File quarantineBase = localFileSystem.get().pathToFile(storageService.getQuarantineFile(uuid)); File quarantineOriginal = new File(quarantineBase.getPath() + ".original"); File quarantineRestored = new File(quarantineBase.getPath() + ".restored"); log.error("Backup is corrupt after write. Quarantining local file: %s", quarantineBase); if (!this.source.renameTo(quarantineOriginal) || !restored.renameTo(quarantineRestored)) { log.warn("Quarantine of corrupt backup shard failed: %s", uuid); } throw new PrestoException(RAPTOR_BACKUP_CORRUPTION, "Backup is corrupt after write: " + uuid); } if (!restored.delete()) { log.warn("Failed to delete staging file: %s", restored); } } stats.incrementBackupSuccess(); } catch (Throwable t) { stats.incrementBackupFailure(); throw t; } }</code><technical_language>nit: cleaner java if (!enableVerification) { ..</technical_language>

Target:
public void run() { try { stats.addQueuedTime(Duration.nanosSince(queuedTime)); long start = System.nanoTime(); backupStore.get().backupShard(uuid, source); stats.addCopyShardDataRate(new DataSize(source.length(), BYTE), Duration.nanosSince(start)); if (!enableVerification) { stats.incrementBackupSuccess(); return; } File restored = new File(localFileSystem.get().pathToFile(storageService.getStagingFile(uuid)) + ".validate"); backupStore.get().restoreShard(uuid, restored); if (!filesEqual(source, restored)) { stats.incrementBackupCorruption(); File quarantineBase = localFileSystem.get().pathToFile(storageService.getQuarantineFile(uuid)); File quarantineOriginal = new File(quarantineBase.getPath() + ".original"); File quarantineRestored = new File(quarantineBase.getPath() + ".restored"); log.error("Backup is corrupt after write. Quarantining local file: %s", quarantineBase); if (!this.source.renameTo(quarantineOriginal) || !restored.renameTo(quarantineRestored)) { log.warn("Quarantine of corrupt backup shard failed: %s", uuid); } throw new PrestoException(RAPTOR_BACKUP_CORRUPTION, "Backup is corrupt after write: " + uuid); } if (!restored.delete()) { log.warn("Failed to delete staging file: %s", restored); } stats.incrementBackupSuccess(); } catch (Throwable t) { stats.incrementBackupFailure(); throw t; } }
Source:
<code>private PackList scanPacksImpl(final PackList old) { final Map<String, PackFile> forReuse = reuseMap(old); final FileSnapshot snapshot = FileSnapshot.save(packDirectory); final Set<String> names = listPackDirectory(); final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2); boolean foundNew = false; for (final String indexName : names) { if (indexName.length() != 49 || !indexName.endsWith(".idx")) continue; final String base = indexName.substring(0, indexName.length() - 3); final List<PackExt> extensions = new ArrayList<PackExt>( PackExt.values().length); for (PackExt ext : PackExt.values()) { <START> final String name = base + ext.getExtension(); <END> if (names.contains(name)) extensions.add(ext); } if (!extensions.contains(PACK)) { continue; } final String packName = base + PACK.getExtension(); final PackFile oldPack = forReuse.remove(packName); if (oldPack != null) { list.add(oldPack); continue; } final File packFile = new File(packDirectory, packName); list.add(new PackFile(packFile, extensions)); foundNew = true; } if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) { old.snapshot.setClean(snapshot); return old; } for (final PackFile p : forReuse.values()) { p.close(); } if (list.isEmpty()) return new PackList(snapshot, NO_PACKS.packs); final PackFile[] r = list.toArray(new PackFile[list.size()]); Arrays.sort(r, PackFile.SORT); return new PackList(snapshot, r); }</code><technical_language>inline name here, shorter</technical_language>

Target:
private PackList scanPacksImpl(final PackList old) { final Map<String, PackFile> forReuse = reuseMap(old); final FileSnapshot snapshot = FileSnapshot.save(packDirectory); final Set<String> names = listPackDirectory(); final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2); boolean foundNew = false; for (final String indexName : names) { if (indexName.length() != 49 || !indexName.endsWith(".idx")) continue; final String base = indexName.substring(0, indexName.length() - 3); final List<PackExt> extensions = new ArrayList<PackExt>( PackExt.values().length); for (PackExt ext : PackExt.values()) { if (names.contains(base + ext.getExtension())) extensions.add(ext); } if (!extensions.contains(PACK)) { continue; } final String packName = base + PACK.getExtension(); final PackFile oldPack = forReuse.remove(packName); if (oldPack != null) { list.add(oldPack); continue; } final File packFile = new File(packDirectory, packName); list.add(new PackFile(packFile, extensions)); foundNew = true; } if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) { old.snapshot.setClean(snapshot); return old; } for (final PackFile p : forReuse.values()) { p.close(); } if (list.isEmpty()) return new PackList(snapshot, NO_PACKS.packs); final PackFile[] r = list.toArray(new PackFile[list.size()]); Arrays.sort(r, PackFile.SORT); return new PackList(snapshot, r); }
Source:
<code>public Optional<Git> execute() { try { boolean newRepository = !repoDir.exists(); final org.eclipse.jgit.api.Git _git = org.eclipse.jgit.api.Git.init().setBare(true).setDirectory(repoDir).call(); if (leaders != null) { new WriteConfiguration(_git.getRepository(), cfg -> { cfg.setInt("core", null, "repositoryformatversion", 1); cfg.setString("extensions", null, "refsStorage", "reftree"); }).execute(); } final Repository repo = new FileRepositoryBuilder() .setGitDir(repoDir) .build(); final org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo); if(!sslVerify) { StoredConfig config = repo.getConfig(); config.setBoolean( "http", null, "sslVerify", false ); config.save(); <START> } <END> if (setupGitHooks(newRepository)) { final File repoHookDir = new File(repoDir, "hooks"); try { FileUtils.copyDirectory(hookDir, repoHookDir); } catch (final Exception ex) { throw new RuntimeException(ex); } for (final File file : repoHookDir.listFiles()) { if (file != null && file.isFile()) { file.setExecutable(true); } } } return Optional.of(new GitImpl(git, leaders)); } catch (final Exception ex) { throw new IOException(ex); } }</code><technical_language>Imho do sslVerify is true repositories property set false. do think? :)</technical_language>

Target:
public Optional<Git> execute() { try { boolean newRepository = !repoDir.exists(); final org.eclipse.jgit.api.Git _git = org.eclipse.jgit.api.Git.init().setBare(true).setDirectory(repoDir).call(); if (leaders != null) { new WriteConfiguration(_git.getRepository(), cfg -> { cfg.setInt("core", null, "repositoryformatversion", 1); cfg.setString("extensions", null, "refsStorage", "reftree"); }).execute(); } final Repository repo = new FileRepositoryBuilder() .setGitDir(repoDir) .build(); final org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo); setupSSLVerify(repo); if (setupGitHooks(newRepository)) { final File repoHookDir = new File(repoDir, "hooks"); try { FileUtils.copyDirectory(hookDir, repoHookDir); } catch (final Exception ex) { throw new RuntimeException(ex); } for (final File file : repoHookDir.listFiles()) { if (file != null && file.isFile()) { file.setExecutable(true); } } } return Optional.of(new GitImpl(git, leaders)); } catch (final Exception ex) { throw new IOException(ex); } }
Source:
<code>private JsonElement evaluate(LDUser user, FeatureStore featureStore, List<FeatureRequestEvent> events) throws EvaluationError { boolean prereqOk = true; for (Prerequisite prereq : prerequisites) { FeatureFlag prereqFeatureFlag = featureStore.get(prereq.getKey()); JsonElement prereqEvalResult = null; if (prereqFeatureFlag == null) { logger.error("Could not retrieve prerequisite flag: " + prereq.getKey() + " when evaluating: " + key); return null; } else if (prereqFeatureFlag.isOn()) { prereqEvalResult = prereqFeatureFlag.evaluate(user, featureStore, events); try { JsonElement variation = prereqFeatureFlag.getVariation(prereq.getVariation()); if (prereqEvalResult == null || variation == null || !prereqEvalResult.equals(variation)) { prereqOk = false; } } catch (EvaluationError err) { <START> prereqOk = false; <END> } } else { prereqOk = false; } events.add(new FeatureRequestEvent(prereqFeatureFlag.getKey(), user, prereqEvalResult, null)); } if (prereqOk) { return getVariation(evaluateIndex(user)); } return null; }</code><technical_language>I log exception here- debug warn</technical_language>

Target:
private JsonElement evaluate(LDUser user, FeatureStore featureStore, List<FeatureRequestEvent> events) throws EvaluationException { boolean prereqOk = true; for (Prerequisite prereq : prerequisites) { FeatureFlag prereqFeatureFlag = featureStore.get(prereq.getKey()); JsonElement prereqEvalResult = null; if (prereqFeatureFlag == null) { logger.error("Could not retrieve prerequisite flag: " + prereq.getKey() + " when evaluating: " + key); return null; } else if (prereqFeatureFlag.isOn()) { prereqEvalResult = prereqFeatureFlag.evaluate(user, featureStore, events); try { JsonElement variation = prereqFeatureFlag.getVariation(prereq.getVariation()); if (prereqEvalResult == null || variation == null || !prereqEvalResult.equals(variation)) { prereqOk = false; } } catch (EvaluationException err) { logger.warn("Error evaluating prerequisites: " + err.getMessage()); prereqOk = false; } } else { prereqOk = false; } events.add(new FeatureRequestEvent(prereqFeatureFlag.getKey(), user, prereqEvalResult, null)); } if (prereqOk) { return getVariation(evaluateIndex(user)); } return null; }
Source:
<code>public void deleteCourseCascade(String courseId) { if (getCourse(courseId) == null) { return; } <START> coursesDb.deleteCourse(courseId); <END> AttributesDeletionQuery query = AttributesDeletionQuery.builder() .withCourseId(courseId) .build(); instructorsLogic.deleteInstructors(query); studentsLogic.deleteStudents(query); feedbackSessionsLogic.deleteFeedbackSessions(query); fqLogic.deleteFeedbackQuestions(query); frLogic.deleteFeedbackResponses(query); frcLogic.deleteFeedbackResponseComments(query); }</code><technical_language>this done last? way, if of operations fail, safely re-run this delete operation. If this is done first, if of operations fail, end orphan entities</technical_language>

Target:
public void deleteCourseCascade(String courseId) { if (getCourse(courseId) == null) { return; } AttributesDeletionQuery query = AttributesDeletionQuery.builder() .withCourseId(courseId) .build(); frcLogic.deleteFeedbackResponseComments(query); frLogic.deleteFeedbackResponses(query); fqLogic.deleteFeedbackQuestions(query); feedbackSessionsLogic.deleteFeedbackSessions(query); studentsLogic.deleteStudents(query); instructorsLogic.deleteInstructors(query); coursesDb.deleteCourse(courseId); }
Source:
<code>public boolean sourceStatus(String servicePID) { try { List<Source> sources = helper.getSources(); for (Source source : sources) { if (source instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) source; try { Configuration config = helper.getConfiguration(cs); if (config != null && config.getProperties().get("service.pid").equals(servicePID)) { try { return source.isAvailable(); } catch (Exception e) { <START> LOGGER.debug( <END> String.format("Couldn't get availability on source %s", servicePID), e); } } } catch (IOException e) { LOGGER.debug("Couldn't find configuration for source '{}'", source.getId()); } } else { LOGGER.debug("Source '{}' not a configured service", source.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.debug("Could not get service reference list"); } return false; }</code><technical_language>do add String.format? drop set of braces</technical_language>

Target:
public boolean sourceStatus(String servicePID) { try { List<Source> sources = helper.getSources(); for (Source source : sources) { if (source instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) source; try { Configuration config = helper.getConfiguration(cs); if (config != null && config.getProperties().get("service.pid").equals(servicePID)) { try { return source.isAvailable(); } catch (Exception e) { LOGGER.debug("Couldn't get availability on source {}", servicePID, e); } } } catch (IOException e) { LOGGER.debug("Couldn't find configuration for source '{}'", source.getId()); } } else { LOGGER.debug("Source '{}' not a configured service", source.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.debug("Could not get service reference list"); } return false; }
Source:
<code>public Collection<AdvertisedSocketAddress> resolve( AdvertisedSocketAddress initialAddress ) { AdvertisedSocketAddress[] srvAddresses = new AdvertisedSocketAddress[0]; try { srvAddresses = srvRecordResolver.resolveSrvRecord( initialAddress.getHostname() ); } catch ( NamingException e ) { <START> log.error( format( "Failed to resolve srv records '%s'", initialAddress.getHostname() ), e ); <END> } Set<AdvertisedSocketAddress> addresses = new HashSet<>( Arrays.asList( srvAddresses ) ); userLog.info( "Resolved initial host '%s' to %s", initialAddress, addresses ); return addresses; }</code><technical_language>Logger formatting already, need String.format</technical_language>

Target:
public Collection<AdvertisedSocketAddress> resolve( AdvertisedSocketAddress initialAddress ) { try { Set<AdvertisedSocketAddress> addresses = srvRecordResolver .resolveSrvRecord( initialAddress.getHostname() ) .map( srvRecord -> new AdvertisedSocketAddress( srvRecord.host, srvRecord.port ) ) .collect( Collectors.toSet() ); userLog.info( "Resolved initial host '%s' to %s", initialAddress, addresses ); if ( addresses.isEmpty() ) { log.error( "Failed to resolve srv records for '%s'", initialAddress.getHostname() ); } return addresses; } catch ( NamingException e ) { log.error( "Failed to resolve srv records for '%s'", initialAddress.getHostname(), e ); return Collections.emptySet(); } }
Source:
<code>public static Bitmap getScaledBitmapFromPath(String imagePath, int outputRectangleWidth, int outputRectangleHeight, ResizeType resizeType, boolean justScaleDown) { if (imagePath == null) { return null; } int[] imageDimensions = getImageDimensions(imagePath); int originalWidth = imageDimensions[0]; int originalHeight = imageDimensions[1]; int newWidth = originalHeight; int newHeight = originalWidth; int loadingSampleSize = 1; double sampleSizeWidth = ((double) originalWidth) / (double) outputRectangleWidth; double sampleSizeHeight = ((double) originalHeight) / (double) outputRectangleHeight; double sampleSizeMinimum = Math.min(sampleSizeWidth, sampleSizeHeight); double sampleSizeMaximum = Math.max(sampleSizeWidth, sampleSizeHeight); <START> if (!(justScaleDown && outputRectangleHeight > originalHeight && outputRectangleWidth > originalWidth)) { <END> if (resizeType == ResizeType.STRETCH_TO_RECTANGLE) { newWidth = outputRectangleWidth; newHeight = outputRectangleHeight; } else if (resizeType == ResizeType.STAY_IN_RECTANGLE_WITH_SAME_ASPECT_RATIO) { newWidth = (int) Math.floor(originalWidth / sampleSizeMaximum); newHeight = (int) Math.floor(originalHeight / sampleSizeMaximum); } else if (resizeType == ResizeType.FILL_RECTANGLE_WITH_SAME_ASPECT_RATIO) { newWidth = (int) Math.floor(originalWidth / sampleSizeMinimum); newHeight = (int) Math.floor(originalHeight / sampleSizeMinimum); } } loadingSampleSize = calculateInSampleSize(originalWidth, originalHeight, outputRectangleWidth, outputRectangleHeight); BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = loadingSampleSize; bitmapOptions.inJustDecodeBounds = false; Bitmap tempBitmap = BitmapFactory.decodeFile(imagePath, bitmapOptions); return scaleBitmap(tempBitmap, newWidth, newHeight); }</code><technical_language>express this in a more readable</technical_language>

Target:
public static Bitmap getScaledBitmapFromPath(String imagePath, int outputRectangleWidth, int outputRectangleHeight, ResizeType resizeType, boolean justScaleDown) { if (imagePath == null) { return null; } int[] imageDimensions = getImageDimensions(imagePath); int originalWidth = imageDimensions[0]; int originalHeight = imageDimensions[1]; int[] scaledImageDimensions = getScaledImageDimensions(originalWidth, originalHeight, outputRectangleWidth, outputRectangleHeight, resizeType, justScaleDown); int newWidth = scaledImageDimensions[0]; int newHeight = scaledImageDimensions[1]; int loadingSampleSize = calculateInSampleSize(originalWidth, originalHeight, outputRectangleWidth, outputRectangleHeight); BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = loadingSampleSize; bitmapOptions.inJustDecodeBounds = false; Bitmap tempBitmap = BitmapFactory.decodeFile(imagePath, bitmapOptions); return scaleBitmap(tempBitmap, newWidth, newHeight); }
Source:
<code>public static boolean isMythicSpawner(String name) { <START> return (!(MythicMobs.inst().getSpawnerManager().getSpawnerByName(name) == null)); <END> }</code><technical_language>.. is this mess of parens symbols meant !=</technical_language>

Target:
public static boolean isMythicSpawner(String name) { return MythicMobs.inst().getSpawnerManager().getSpawnerByName(name) != null; }
Source:
<code>public DimensionSelector decorate(final DimensionSelector selector) { if (selector == null) { return null; } final int selectorCardinality = selector.getValueCardinality(); if (selectorCardinality < 0 || !selector.nameLookupPossibleInAdvance()) { return new PredicateFilteredDimensionSelector( selector, new Predicate<String>() { @Override public boolean apply(@Nullable String input) { <START> return NullHandling.nullToEmptyIfNeeded(input).startsWith(prefix); <END> } } ); } int count = 0; final Int2IntOpenHashMap forwardMapping = new Int2IntOpenHashMap(); forwardMapping.defaultReturnValue(-1); for (int i = 0; i < selectorCardinality; i++) { if (NullHandling.nullToEmptyIfNeeded(selector.lookupName(i)).startsWith(prefix)) { forwardMapping.put(i, count++); } } final int[] reverseMapping = new int[forwardMapping.size()]; for (Int2IntMap.Entry e : forwardMapping.int2IntEntrySet()) { reverseMapping[e.getIntValue()] = e.getIntKey(); } return new ForwardingFilteredDimensionSelector(selector, forwardMapping, reverseMapping); }</code><technical_language>result of NullHandling.nullToEmptyIfNeeded(input) needs a null check, return null if druid.generic.useDefaultValueForNull is false</technical_language>

Target:
public DimensionSelector decorate(final DimensionSelector selector) { if (selector == null) { return null; } final int selectorCardinality = selector.getValueCardinality(); if (selectorCardinality < 0 || !selector.nameLookupPossibleInAdvance()) { return new PredicateFilteredDimensionSelector( selector, new Predicate<String>() { @Override public boolean apply(@Nullable String input) { String val = NullHandling.nullToEmptyIfNeeded(input); return val == null ? false : val.startsWith(prefix); } } ); } int count = 0; final Int2IntOpenHashMap forwardMapping = new Int2IntOpenHashMap(); forwardMapping.defaultReturnValue(-1); for (int i = 0; i < selectorCardinality; i++) { String val = NullHandling.nullToEmptyIfNeeded(selector.lookupName(i)); if (val != null && val.startsWith(prefix)) { forwardMapping.put(i, count++); } } final int[] reverseMapping = new int[forwardMapping.size()]; for (Int2IntMap.Entry e : forwardMapping.int2IntEntrySet()) { reverseMapping[e.getIntValue()] = e.getIntKey(); } return new ForwardingFilteredDimensionSelector(selector, forwardMapping, reverseMapping); }
Source:
<code>public void handleAction(final ActionParameters params) throws ActionException { JSONObject job = new JSONObject(); String downloadDetails = params.getHttpParam(PARAM_DOWNLOAD_DETAILS); String strUserDetails = params.getHttpParam(PARAM_USER_DETAILS); try { JSONObject userDetails = new JSONObject(strUserDetails); JSONArray ddArray = new JSONArray(downloadDetails); <START> new SendDownloadDetailsToEmailThread(ddArray, userDetails, params.getLocale()).start(); <END> job.put("success", true); } catch (Exception e) { throw new ActionException("Could not handle DownloadInfo request: ", e); } ResponseHelper.writeResponse(params, job); }</code><technical_language>creating starting a new Thread for _every_ request. do care sending email succeeds (you're responding {"success": true}) send response client run Email sending part current thread afterwards. I change is reorganize lines in this function success response is flushed client succesfully created userDetails ddArray. change SendDownloadDetailsToEmailThread extend Runnable instead of Thread call .run() instead of .start() creating object</technical_language>

Target:
public void handleAction(final ActionParameters params) throws ActionException { String downloadDetails = params.getRequiredParam(PARAM_DOWNLOAD_DETAILS); String strUserDetails = params.getRequiredParam(PARAM_USER_DETAILS); try { JSONObject userDetails = new JSONObject(strUserDetails); JSONArray ddArray = new JSONArray(downloadDetails); new SendDownloadDetailsToEmailThread(mapLayerService, ddArray, userDetails, params.getLocale()).run(); } catch (Exception e) { throw new ActionException("Could not handle DownloadInfo request: ", e); } ResponseHelper.writeResponse(params, JSONHelper.createJSONObject("success", true)); }
Source:
<code>public void testBasicContainerUsage() { BucketDefinition bucketDefinition = new BucketDefinition("mybucket"); try (CouchbaseContainer container = new CouchbaseContainer().withBucket(bucketDefinition)) { container.start(); CouchbaseEnvironment environment = DefaultCouchbaseEnvironment .builder() <START> .bootstrapCarrierDirectPort(container.getMappedPort(11210)) .bootstrapHttpDirectPort(container.getMappedPort(8091)) <END> .build(); Cluster cluster = CouchbaseCluster.create(environment, container.getContainerIpAddress()); try { cluster.authenticate(container.getUsername(), container.getPassword()); Bucket bucket = cluster.openBucket(bucketDefinition.getName()); bucket.upsert(JsonDocument.create("foo", JsonObject.empty())); assertTrue(bucket.exists("foo")); assertNotNull(cluster.clusterManager().getBucket(bucketDefinition.getName())); } finally { cluster.disconnect(); environment.shutdown(); } } }</code><technical_language>I wondering if nicer default ports public constants in container class</technical_language>

Target:
public void testBasicContainerUsage() { BucketDefinition bucketDefinition = new BucketDefinition("mybucket"); try ( CouchbaseContainer container = new CouchbaseContainer() .withBucket(bucketDefinition) ) { container.start(); CouchbaseEnvironment environment = DefaultCouchbaseEnvironment .builder() .bootstrapCarrierDirectPort(container.getBootstrapCarrierDirectPort()) .bootstrapHttpDirectPort(container.getBootstrapHttpDirectPort()) .build(); Cluster cluster = CouchbaseCluster.create( environment, container.getContainerIpAddress() ); try { cluster.authenticate(container.getUsername(), container.getPassword()); Bucket bucket = cluster.openBucket(bucketDefinition.getName()); bucket.upsert(JsonDocument.create("foo", JsonObject.empty())); assertTrue(bucket.exists("foo")); assertNotNull(cluster.clusterManager().getBucket(bucketDefinition.getName())); } finally { cluster.disconnect(); environment.shutdown(); } } }