auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public HighFrequencyDetectorStatistics newHighFrequency() { final MetricId m = metric.tagged("component", "high-freq"); final Map<MetricId, Long> highFreqMetricsMap = new ConcurrentHashMap<>(); return new HighFrequencyDetectorStatistics() { private final Counter dropped = registry.counter( m.tagged("what", "dropped-metrics", "unit", "metric")); @Override public void reportHighFrequencyMetricsDropped(int dropped) { this.dropped.inc(dropped); } @Override public void reportHighFrequencyMetrics(int marked, String... tags) { MetricId gaugeMetric = m.tagged("what", "high-freq-metrics").tagged(tags); registerGauge(gaugeMetric); highFreqMetricsMap.put(gaugeMetric, (long) marked); } <START> private synchronized void registerGauge(MetricId gauge) { <END> if (highFreqMetricsMap.containsKey(gauge)) { return; } registry.register(gauge, new Gauge<Long>() { @Override public Long getValue() { return highFreqMetricsMap.get(gauge); } }); } }; }</code><technical_language>synchronizing a read access a concurrent concurrent hashMap is defies point of it</technical_language>

Target:
public HighFrequencyDetectorStatistics newHighFrequency() { final MetricId m = metric.tagged("component", "high-freq"); final Map<MetricId, Long> highFreqMetricsMap = new ConcurrentHashMap<>(); return new HighFrequencyDetectorStatistics() { private final Counter dropped = registry.counter( m.tagged("what", "dropped-metrics", "unit", "metric")); @Override public void reportHighFrequencyMetricsDropped(int dropped) { this.dropped.inc(dropped); } @Override public void reportHighFrequencyMetrics(int marked, String... tags) { MetricId gaugeMetric = m.tagged("what", "high-freq-metrics").tagged(tags); registerGauge(gaugeMetric); highFreqMetricsMap.put(gaugeMetric, (long) marked); } private void registerGauge(MetricId gauge) { if (highFreqMetricsMap.containsKey(gauge)) { return; } try { registry.register(gauge, new Gauge<Long>() { @Override public Long getValue() { return highFreqMetricsMap.get(gauge); } }); } catch (IllegalArgumentException e) { } } }; }
Source:
<code>public void setOnValueChangedListener(NumberPicker.OnValueChangeListener listener) { <START> this.onValueChangeListener = listener; <END> }</code><technical_language>this call native implementation</technical_language>

Target:
public void setOnValueChangedListener(NumberPicker.OnValueChangeListener listener) { directlyOn(realObject, NumberPicker.class).setOnValueChangedListener(listener); this.onValueChangeListener = listener; }
Source:
<code>public MimeMessage generateNewInstructorAccountJoinEmail(InstructorAttributes instructor, String shortName, String institute) throws AddressException, MessagingException, UnsupportedEncodingException { MimeMessage messageToUser = getEmptyEmailAddressedToEmail(instructor.email); messageToUser = addBccRecipientToEmail(messageToUser, Config.SUPPORT_EMAIL); messageToUser.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT + " " + shortName)); String joinUrl = generateNewInstructorAccountJoinLink(instructor, institute); <START> String emailBody = Templates.populateTemplate(EmailTemplates.NEW_INSTRCUTOR_ACCOUNT_WELCOME, <END> "${userName}", shortName, "${joinUrl}", joinUrl); messageToUser.setContent(emailBody, "text/html"); return messageToUser; }</code><technical_language>Lets fix typo in instructor :)</technical_language>

Target:
public MimeMessage generateNewInstructorAccountJoinEmail(InstructorAttributes instructor, String shortName, String institute) throws AddressException, MessagingException, UnsupportedEncodingException { MimeMessage messageToUser = getEmptyEmailAddressedToEmail(instructor.email); messageToUser = addBccRecipientToEmail(messageToUser, Config.SUPPORT_EMAIL); messageToUser.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT + " " + shortName)); String joinUrl = generateNewInstructorAccountJoinLink(instructor, institute); String emailBody = Templates.populateTemplate(EmailTemplates.NEW_INSTRUCTOR_ACCOUNT_WELCOME, "${userName}", shortName, "${joinUrl}", joinUrl); messageToUser.setContent(emailBody, "text/html"); return messageToUser; }
Source:
<code><START> private boolean isSerializable(Type type) { <END> if (type.isPrimitive()) { return true; } if (isSerializableArray(type)) { return true; } if (isParametrized(type)) { return isSerializableParametrized((ParametrizedTypeJavaType) type); } return type.isSubtypeOf("java.io.Serializable"); }</code><technical_language>This method static, methods calls</technical_language>

Target:
private static boolean isSerializable(Type type) { if (type.isPrimitive()) { return true; } if (isSerializableArray(type)) { return true; } if (isParametrized(type)) { return isSerializableParametrized((ParametrizedTypeJavaType) type); } return type.isSubtypeOf("java.io.Serializable"); }
Source:
<code>protected String addEdge(Object sId, Object eId, String flowRule) { <START> return " " + sId + " -> " + eId + " [label=\"" + flowRule + "\"];" + lineSeparator; <END> }</code><technical_language>below, input arbitrary object, call format escaped properly for output</technical_language>

Target:
protected String addEdge(Object sId, Object eId, String flowRule) { return " " + format(sId) + " -> " + format(eId) + " [label=\"" + flowRule + "\"];" + lineSeparator; }
Source:
<code>private void rename(MetaDataUpdate md) throws IOException, ConfigInvalidException { boolean success = false; for (int attempts = 0; !success && attempts < MAX_TRIES; attempts++) { ProjectConfig config = ProjectConfig.read(md); GroupReference ref = config.getGroup(uuid); if (ref == null || newName.equals(ref.getName())) { projectCache.evict(config.getProject()); return; } ref.setName(newName); md.getCommitBuilder().setAuthor(author); md.setMessage("Rename group " + oldName + " to " + newName + "\n"); if (config.commit(md)) { projectCache.evict(config.getProject()); success = true; } else { try { Thread.sleep(25 ); } catch (InterruptedException wakeUp) { continue; } } } <START> if (!success && !tryingAgain) { <END> start(5, TimeUnit.MINUTES); tryingAgain = true; } }</code><technical_language>is tryingAgain false? 1. run() sets false 2. if tryingAgain is false reschedule command run in 5 minutes 3. 5 minutes rerunning command is setting tryingAgain false (so step 1.) I missing something</technical_language>

Target:
private void rename(MetaDataUpdate md) throws IOException, ConfigInvalidException { boolean success = false; for (int attempts = 0; !success && attempts < MAX_TRIES; attempts++) { ProjectConfig config = ProjectConfig.read(md); GroupReference ref = config.getGroup(uuid); if (ref == null || newName.equals(ref.getName())) { projectCache.evict(config.getProject()); return; } ref.setName(newName); md.getCommitBuilder().setAuthor(author); md.setMessage("Rename group " + oldName + " to " + newName + "\n"); if (config.commit(md)) { projectCache.evict(config.getProject()); success = true; } else { try { Thread.sleep(25 ); } catch (InterruptedException wakeUp) { continue; } } } if (!success) { if (tryingAgain) { log.warn("Could not rename group " + oldName + " to " + newName + " in " + md.getProjectName().get()); } else { retryOn.add(md.getProjectName()); } } }
Source:
<code>private String computeCurrentEtag(final Set<ServerToSegment> segments, @Nullable byte[] queryCacheKey) { Hasher hasher = Hashing.sha1().newHasher(); boolean hasOnlyHistoricalSegments = true; for (ServerToSegment p : segments) { <START> log.info(p.getServer().pick().getServer().getType().toString()); <END> if (!p.getServer().pick().getServer().segmentReplicatable()) { hasOnlyHistoricalSegments = false; break; } hasher.putString(p.getServer().getSegment().getIdentifier(), Charsets.UTF_8); } if (hasOnlyHistoricalSegments) { hasher.putBytes(queryCacheKey == null ? strategy.computeCacheKey(query) : queryCacheKey); String currEtag = Base64.encodeBase64String(hasher.hash().asBytes()); responseContext.put(QueryResource.HEADER_ETAG, currEtag); return currEtag; } else { return null; } }</code><technical_language>this left accident</technical_language>

Target:
private String computeCurrentEtag(final Set<ServerToSegment> segments, @Nullable byte[] queryCacheKey) { Hasher hasher = Hashing.sha1().newHasher(); boolean hasOnlyHistoricalSegments = true; for (ServerToSegment p : segments) { if (!p.getServer().pick().getServer().segmentReplicatable()) { hasOnlyHistoricalSegments = false; break; } hasher.putString(p.getServer().getSegment().getIdentifier(), Charsets.UTF_8); } if (hasOnlyHistoricalSegments) { hasher.putBytes(queryCacheKey == null ? strategy.computeCacheKey(query) : queryCacheKey); String currEtag = Base64.encodeBase64String(hasher.hash().asBytes()); responseContext.put(QueryResource.HEADER_ETAG, currEtag); return currEtag; } else { return null; } }
Source:
<code>boolean remove(String path) throws IOException; F[] list(String path) throws IOException; void read(String source, OutputStream outputStream) throws IOException; void write(InputStream inputStream, String destination) throws IOException; void append(InputStream inputStream, String destination) throws IOException; boolean mkdir(String directory) throws IOException; boolean rmdir(String directory) throws IOException; void rename(String pathFrom, String pathTo) throws IOException; @Override void close(); boolean isOpen(); boolean exists(String path) throws IOException; String[] listNames(String path) throws IOException; InputStream readRaw(String source) throws IOException; boolean finalizeRaw() throws IOException; Object getClientInstance(); <START> String getHost(); <END> default boolean test() { return this.isOpen(); }</code><technical_language>Default</technical_language>

Target:
boolean remove(String path) throws IOException; F[] list(String path) throws IOException; void read(String source, OutputStream outputStream) throws IOException; void write(InputStream inputStream, String destination) throws IOException; void append(InputStream inputStream, String destination) throws IOException; boolean mkdir(String directory) throws IOException; boolean rmdir(String directory) throws IOException; void rename(String pathFrom, String pathTo) throws IOException; @Override void close(); boolean isOpen(); boolean exists(String path) throws IOException; String[] listNames(String path) throws IOException; InputStream readRaw(String source) throws IOException; boolean finalizeRaw() throws IOException; Object getClientInstance(); String getHostPort(); default boolean test() { return this.isOpen(); }
Source:
<code>public void testPublicIpV4Address() { <START> String ten_dot = "^10\\."; <END> String one_two_seven = "^127\\."; String one_six_nine = "^169\\.254"; String one_nine_two = "^192\\.168\\."; String one_seven_two = "^172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\\."; for (int i = 0; i < 1000; i++) { String addr = faker.internet().publicIpV4Address(); assertThat(addr.matches(ten_dot),is(false)); assertThat(addr.matches(one_two_seven),is(false)); assertThat(addr.matches(one_six_nine),is(false)); assertThat(addr.matches(one_nine_two),is(false)); assertThat(addr.matches(one_seven_two),is(false)); } }</code><technical_language>@trevershick camelcase local variables? Thanks</technical_language>

Target:
public void testPublicIpV4Address() { String tenDot = "^10\\."; String oneTwoSeven = "^127\\."; String oneSixNine = "^169\\.254"; String oneNineTwo = "^192\\.168\\."; String oneSevenTwo = "^172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\\."; for (int i = 0; i < 1000; i++) { String addr = faker.internet().publicIpV4Address(); assertThat(addr.matches(tenDot),is(false)); assertThat(addr.matches(oneTwoSeven),is(false)); assertThat(addr.matches(oneSixNine),is(false)); assertThat(addr.matches(oneNineTwo),is(false)); assertThat(addr.matches(oneSevenTwo),is(false)); } }
Source:
<code>default List<AnalyzedCheckConstraint> checkConstraints() { <START> return ImmutableList.of(); <END> }</code><technical_language>suggestion return List.of(); avoid guava if necessary</technical_language>

Target:
default List<CheckConstraint<Symbol>> checkConstraints() { return List.of(); }
Source:
<code>SQLiteConnection openConnection(boolean readonly) { SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly); if (conn == null) { return null; } if (conn.getVersion() < DB_VERSION) { if (readonly) { conn.close(); conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false); } int version = conn.getVersion(); conn.setVersion(DB_VERSION); if (version == 0) { onCreate(conn); } else { onUpgrade(conn, version, DB_VERSION); } } <START> cleanUpDatabase(conn); <END> return conn; }</code><technical_language>is often. Please move cleanUpDatabase constructor (239 line)</technical_language>

Target:
SQLiteConnection openConnection(boolean readonly) { SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly); if (conn == null) { return null; } if (conn.getVersion() < DB_VERSION) { if (readonly) { conn.close(); conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false); } int version = conn.getVersion(); conn.setVersion(DB_VERSION); if (version == 0) { onCreate(conn); } else { onUpgrade(conn, version, DB_VERSION); } } return conn; }
Source:
<code>public void downloadFile(String url, String mimeType, FileDownloaderCallback callback) { final Request request = new Request.Builder().url(url) .addHeader("Content-Type", mimeType) .build(); mCallFactory.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { <START> callback.onFailure(e); <END> } @Override public void onResponse(Call call, Response response) { try { final File outputFile = new File(mCacheDir, new File(url).getName()); BufferedSink sink = Okio.buffer(Okio.sink(outputFile)); sink.writeAll(response.body().source()); sink.close(); new Handler(Looper.getMainLooper()).post(() -> callback.onSuccess(outputFile.getPath())); } catch (IOException e) { callback.onFailure(e); } } }); }</code><technical_language>This needs wrapped new Handler(Looper.getMainLooper()).post(() -> callback.onFailure(e)) well</technical_language>

Target:
public void downloadFile(String url, String mimeType, FileDownloaderCallback callback) { final Request request = new Request.Builder().url(url) .addHeader("Content-Type", mimeType) .build(); mCallFactory.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { new Handler(Looper.getMainLooper()).post(() -> callback.onFailure(call, e)); } @Override public void onResponse(Call call, Response response) { try { final File outputFile = new File(mCacheDir, new File(url).getName()); BufferedSink sink = Okio.buffer(Okio.sink(outputFile)); sink.writeAll(response.body().source()); sink.close(); new Handler(Looper.getMainLooper()).post(() -> callback.onSuccess(outputFile.getPath())); } catch (IOException e) { this.onFailure(call, e); } } }); }
Source:
<code>public OutputStream call() throws GitAPIException { <START> final Format<?> fmt = formats.get(format); <END> return writeArchive(fmt); }</code><technical_language>return null</technical_language>

Target:
public OutputStream call() throws GitAPIException { final Format<?> fmt = lookupFormat(format); return writeArchive(fmt); }
Source:
<code><START> public void unregisterHandlers() { <END> for (HandlerRegistration reg: handlerRegistrations) { reg.removeHandler(); } handlerRegistrations.clear(); }</code><technical_language>I this final</technical_language>

Target:
public final void unregisterHandlers() { for (HandlerRegistration reg: handlerRegistrations) { reg.removeHandler(); } handlerRegistrations.clear(); }
Source:
<code>public void testRefSetup() throws Exception { SubscribedRepository r = new SubscribedRepository(publisherConfig .getSubscriber("origin", db.getDirectory().getAbsolutePath())); r.setUpRefs(); <START> assertTrue(null != db.getRef("refs/pubsub/origin/heads/master")); <END> assertTrue(null != db.getRef("refs/pubsub/origin/tags/A")); assertTrue(null != db.getRef("refs/pubsub/origin/tags/B")); }</code><technical_language>assertNotNull for these. Although, actually, write this assertion db.getRefs("refs/pubsub/origin/").keySet(): Set<String> expected = new HashSet<String>(); ... assertEquals(expected, db.getRefs("refs/pubsub/origin/").keySet());</technical_language>

Target:
public void testRefSetup() throws Exception { SubscribedRepository r = new SubscribedRepository(publisherConfig .getSubscriber("origin", db.getDirectory().getAbsolutePath())); r.setUpRefs(); Set<String> keys = db.getRefDatabase() .getRefs("refs/pubsub/origin/").keySet(); assertEquals(13, keys.size()); assertNotNull(db.getRef("refs/pubsub/origin/heads/master")); assertNotNull(db.getRef("refs/pubsub/origin/tags/A")); assertNotNull(db.getRef("refs/pubsub/origin/tags/B")); }
Source:
<code>public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { IJavaElement elem = (IJavaElement) receiver; IJavaProject javaProject = elem.getJavaProject(); if (javaProject == null) { return false; } <START> if (PROP_IS_IN_BND_MAVEN_PROJECT.equals(property)) { <END> try { IMavenProjectFacade projectFacade = getMavenProjectFacade(javaProject.getResource()); return javaProject.exists() && (projectFacade != null) && hasBndMavenPlugin(projectFacade); } catch (CoreException e) { logger.logError("Error testing '" + PROP_IS_IN_BND_MAVEN_PROJECT + "' property on java element.", e); return false; } } else if (PROP_IS_RESOLVABLE_BND_MAVEN_PROJECT.equals(property)) { try { IMavenProjectFacade projectFacade = getMavenProjectFacade(javaProject.getResource()); return javaProject.exists() && (projectFacade != null) && hasBndResolverMavenPlugin(projectFacade); } catch (CoreException e) { logger.logError("Error testing '" + PROP_IS_RESOLVABLE_BND_MAVEN_PROJECT + "' property on java element.", e); return false; } } else if (PROP_IS_TESTABLE_BND_MAVEN_PROJECT.equals(property)) { try { IMavenProjectFacade projectFacade = getMavenProjectFacade(javaProject.getResource()); return javaProject.exists() && (projectFacade != null) && hasBndTestingMavenPlugin(projectFacade); } catch (CoreException e) { logger.logError("Error testing '" + PROP_IS_TESTABLE_BND_MAVEN_PROJECT + "' property on java element.", e); return false; } } return false; }</code><technical_language>a switch statement? I prefer if/then/else a series of strings</technical_language>

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { IJavaElement elem = (IJavaElement) receiver; IJavaProject javaProject = elem.getJavaProject(); if (javaProject == null) { return false; } switch (property) { case PROP_IS_IN_BND_MAVEN_PROJECT : try { IMavenProjectFacade projectFacade = getMavenProjectFacade(javaProject.getResource()); return javaProject.exists() && (projectFacade != null) && hasBndMavenPlugin(projectFacade); } catch (CoreException e) { logger.logError("Error testing '" + PROP_IS_IN_BND_MAVEN_PROJECT + "' property on java element.", e); return false; } case PROP_IS_RESOLVABLE_BND_MAVEN_PROJECT : try { IMavenProjectFacade projectFacade = getMavenProjectFacade(javaProject.getResource()); return javaProject.exists() && (projectFacade != null) && hasBndResolverMavenPlugin(projectFacade); } catch (CoreException e) { logger.logError("Error testing '" + PROP_IS_RESOLVABLE_BND_MAVEN_PROJECT + "' property on java element.", e); return false; } case PROP_IS_TESTABLE_BND_MAVEN_PROJECT : try { IMavenProjectFacade projectFacade = getMavenProjectFacade(javaProject.getResource()); return javaProject.exists() && (projectFacade != null) && hasBndTestingMavenPlugin(projectFacade); } catch (CoreException e) { logger.logError("Error testing '" + PROP_IS_TESTABLE_BND_MAVEN_PROJECT + "' property on java element.", e); return false; } default : return false; } }
Source:
<code>private static Properties calcEnvironment(IConfiguration cfg){ Properties envProps = new Properties(); ICConfigurationDescription cfgDes = ManagedBuildManager.getDescriptionForConfiguration(cfg); IEnvironmentVariableManager mngr = CCorePlugin.getDefault().getBuildEnvironmentManager(); IEnvironmentVariable[] vars = mngr.getVariables(cfgDes, true); for(int i = 0; i < vars.length; i++){ <START> String key = vars[i].getName(); <END> String value = vars[i].getValue(); if (key != null) envProps.setProperty(key, value == null ? "" : value); } return envProps; }</code><technical_language>get NPE vars[i] is null. need a check "if (vars[i] != null)" here</technical_language>

Target:
private static Properties calcEnvironment(IConfiguration cfg){ Properties envProps = new Properties(); ICConfigurationDescription cfgDes = ManagedBuildManager.getDescriptionForConfiguration(cfg); IEnvironmentVariableManager mngr = CCorePlugin.getDefault().getBuildEnvironmentManager(); IEnvironmentVariable[] vars = mngr.getVariables(cfgDes, true); for(int i = 0; i < vars.length; i++) { if (vars[i] != null && vars[i].getName() != null) { String value = vars[i].getValue(); envProps.setProperty(vars[i].getName(), value == null ? "" : value); } } return envProps; }
Source:
<code>public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); byte[] result = PING_RESPONSE.getBytes(); byte[] subscribeResult = "".getBytes(); if (commandElems.size() > 1) { result = commandElems.get(1); subscribeResult = result; } <START> if (!context.getPubSub().findSubscribedChannels(context.getClient()).isEmpty()) { <END> return RedisResponse .array(Arrays.asList(PING_RESPONSE.toLowerCase().getBytes(), subscribeResult)); } return RedisResponse.string(result); }</code><technical_language>consider refactoring this compute RedisResponse for subscribe if find a client (an else) compute RedisResponse subscribed. I logic initializing results end other. prefer state top shared branch (for example commandElems). RedisResponse is done fall a command return</technical_language>

Target:
public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); RedisResponse redisResponse; if (context.getPubSub().findSubscribedChannels(context.getClient()).isEmpty()) { byte[] result; if (commandElems.size() > 1) { result = commandElems.get(1); } else { result = PING_RESPONSE.getBytes(); } redisResponse = RedisResponse.string(result); } else { byte[] result; if (commandElems.size() > 1) { result = commandElems.get(1); } else { result = "".getBytes(); } redisResponse = RedisResponse.array(Arrays.asList(PING_RESPONSE.toLowerCase().getBytes(), result)); } return redisResponse; }
Source:
<code>public void testAvailableTargetTypes() throws IOException { doImport("examples/src/scala/org/pantsbuild/example/hello/"); VirtualFile vfile = myProjectRoot.findFileByRelativePath("BUILD"); assertNotNull(vfile); PsiFile build = PsiManager.getInstance(myProject).findFile(vfile); String input = new String(myProjectRoot.findFileByRelativePath("BUILD").contentsToByteArray()); <START> final PsiReference reference = build.findReferenceAt(input.indexOf("files(") + 1); <END> assertNotNull("no reference", reference); final Collection<PsiElement> elements = TargetElementUtil.getInstance().getTargetCandidates(reference); assertNotNull(elements); assertEquals(1, elements.size()); }</code><technical_language>Is this testing this file? $ cat examples/src/scala/org/pantsbuild/example/hello/BUILD #This is a dummy build file for Intellij Plugin integration test. #Please do remove this BUILD file target( dependencies = [ 'examples/src/scala/org/pantsbuild/example/hello/exe:exe', ] ) if files( coming from</technical_language>

Target:
public void testAvailableTargetTypes() throws IOException { String helloProjectPath = "examples/src/scala/org/pantsbuild/example/hello/"; doImport(helloProjectPath); if (PantsUtil.isCompatiblePantsVersion(myProjectRoot.getPath(), "1.24.0")) { VirtualFile vfile = myProjectRoot.findFileByRelativePath(helloProjectPath + "BUILD"); assertNotNull(vfile); String input = new String(vfile.contentsToByteArray()); PsiFile build = PsiManager.getInstance(myProject).findFile(vfile); final PsiReference reference = build.findReferenceAt(input.indexOf("target(") + 1); assertNotNull("no reference", reference); final Collection<PsiElement> elements = TargetElementUtil.getInstance().getTargetCandidates(reference); assertNotNull(elements); assertEquals(1, elements.size()); } }
Source:
<code><START> public void setLanguage(String language) { <END> this.language = language; }</code><technical_language>follow Fluent pattern</technical_language>

Target:
public TextDocumentInput setLanguage(String language) { this.language = language; return this; }
Source:
<code>public MultimapAggregationStateSerializer(Type keyType, Type valueType) { <START> this.keyType = keyType; <END> this.valueType = valueType; this.arrayType = new ArrayType(RowType.anonymous(ImmutableList.of(valueType, keyType))); }</code><technical_language>add requireNonNull for parameters</technical_language>

Target:
public MultimapAggregationStateSerializer(Type keyType, Type valueType) { this.keyType = requireNonNull(keyType); this.valueType = requireNonNull(valueType); this.arrayType = new ArrayType(RowType.anonymous(ImmutableList.of(valueType, keyType))); }
Source:
<code>public static Future<List> allOf(Collection<Future> futures) { if (futures.isEmpty()) return CompletableFuture.completedFuture(null); return new Future<List>() { @Override @SuppressWarnings("unchecked") public List get() throws InterruptedException, ExecutionException { <START> List result = new LinkedList<>(); <END> for (Future current : futures) { result.add(current.get()); } return result; } @Override @SuppressWarnings("unchecked") public List get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { List result = new LinkedList<>(); long deadline = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, unit); for (Future current : futures) { long remaining = deadline - System.nanoTime(); if (remaining <= 0) throw new TimeoutException(); result.add(current.get(remaining, TimeUnit.NANOSECONDS)); } return result; } @Override public boolean cancel(boolean mayInterruptIfRunning) { for (Future current : futures) { if (!current.cancel(mayInterruptIfRunning)) return false; } return true; } @Override public boolean isCancelled() { for (Future current : futures) { if (!current.isCancelled()) return false; } return true; } @Override public boolean isDone() { for (Future current : futures) { if (!current.isDone()) return false; } return true; } }; }</code><technical_language>Is a reason for choosing a LinkedList ArrayList</technical_language>

Target:
public static Future<List> allOf(Collection<Future> futures) { if (futures.isEmpty()) return CompletableFuture.completedFuture(null); return new Future<List>() { @Override @SuppressWarnings("unchecked") public List get() throws InterruptedException, ExecutionException { List result = new ArrayList<>(futures.size()); for (Future current : futures) { result.add(current.get()); } return result; } @Override @SuppressWarnings("unchecked") public List get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { List result = new ArrayList<>(futures.size()); long deadline = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, unit); for (Future current : futures) { long remaining = deadline - System.nanoTime(); if (remaining <= 0) throw new TimeoutException(); result.add(current.get(remaining, TimeUnit.NANOSECONDS)); } return result; } @Override public boolean cancel(boolean mayInterruptIfRunning) { for (Future current : futures) { if (!current.cancel(mayInterruptIfRunning)) return false; } return true; } @Override public boolean isCancelled() { for (Future current : futures) { if (!current.isCancelled()) return false; } return true; } @Override public boolean isDone() { for (Future current : futures) { if (!current.isDone()) return false; } return true; } }; }
Source:
<code>public void sanityCheckMultiClientGetCommitTimestampsAgainstConjureTimelockService() { TestableTimelockServer leader = cluster.currentLeaderFor(client.namespace()); MultiClientConjureTimelockService service = leader.multiClientService(); Set<String> expectedNamespaces = ImmutableSet.of("alpha", "beta"); List<NamespacedGetCommitTimestampsResponse> commitTimestamps = service.getCommitTimestamps( AUTH_HEADER, defaultNamespacedGetCommitTimestampsRequests(expectedNamespaces)); Set<String> namespaces = commitTimestamps.stream() .map(NamespacedGetCommitTimestampsResponse::getNamespace) .collect(Collectors.toSet()); assertThat(namespaces).hasSameElementsAs(expectedNamespaces); commitTimestamps.forEach(namespacedGetCommitTimestampsResponse -> { GetCommitTimestampsResponse conjureTimelockServiceGetCommitTimestampResponse = leader.client( namespacedGetCommitTimestampsResponse.getNamespace()) .namespacedConjureTimelockService() .getCommitTimestamps(defaultCommitTimestampRequest()); assertThat(namespacedGetCommitTimestampsResponse .getLockWatchUpdate() .logId()) .isEqualTo(conjureTimelockServiceGetCommitTimestampResponse .getLockWatchUpdate() .logId()); assertThat(namespacedGetCommitTimestampsResponse.getInclusiveUpper()) <START> .isEqualTo(conjureTimelockServiceGetCommitTimestampResponse.getInclusiveLower() - 1); <END> }); }</code><technical_language>nit/suggestion: assertions assertThat(actual).isEqualTo(expected), flip two. Also, as(String) in English assertion is doing, I is useful for this one, verifies timestamps contiguously increasing namespace if elections</technical_language>

Target:
public void sanityCheckMultiClientGetCommitTimestampsAgainstConjureTimelockService() { TestableTimelockServer leader = cluster.currentLeaderFor(client.namespace()); MultiClientConjureTimelockService service = leader.multiClientService(); Set<String> expectedNamespaces = ImmutableSet.of("alpha", "beta"); List<NamespacedGetCommitTimestampsResponse> commitTimestamps = service.getCommitTimestamps( AUTH_HEADER, defaultNamespacedGetCommitTimestampsRequests(expectedNamespaces)); Set<String> namespaces = commitTimestamps.stream() .map(NamespacedGetCommitTimestampsResponse::getNamespace) .collect(Collectors.toSet()); assertThat(namespaces).hasSameElementsAs(expectedNamespaces); commitTimestamps.forEach(namespacedGetCommitTimestampsResponse -> { GetCommitTimestampsResponse conjureTimelockServiceGetCommitTimestampResponse = leader.client( namespacedGetCommitTimestampsResponse.getNamespace()) .namespacedConjureTimelockService() .getCommitTimestamps(defaultCommitTimestampRequest()); assertThat(conjureTimelockServiceGetCommitTimestampResponse .getLockWatchUpdate() .logId()) .isEqualTo(namespacedGetCommitTimestampsResponse .getLockWatchUpdate() .logId()); assertThat(conjureTimelockServiceGetCommitTimestampResponse.getInclusiveLower()) .as("timestamps should contiguously increase per namespace if there are no elections.") .isEqualTo(namespacedGetCommitTimestampsResponse.getInclusiveUpper() + 1); }); }
Source:
<code>public static void setFilterPredicate(Configuration configuration, FilterPredicate filterPredicate) { Preconditions.checkArgument(getUnboundRecordFilter(configuration) == null, "You cannot provide a FilterPredicate after providing an UnboundRecordFilter"); try { <START> SerializationUtil.writeObjectToConfAsBase64(FILTER_PREDICATE, filterPredicate, configuration); <END> } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>In general I prefer readable Configuration settings. helps debugability. this serialized in JSON? examples in parquet-thrift</technical_language>

Target:
public static void setFilterPredicate(Configuration configuration, FilterPredicate filterPredicate) { checkArgument(getUnboundRecordFilter(configuration) == null, "You cannot provide a FilterPredicate after providing an UnboundRecordFilter"); configuration.set(FILTER_PREDICATE + ".human.readable", filterPredicate.toString()); try { SerializationUtil.writeObjectToConfAsBase64(FILTER_PREDICATE, filterPredicate, configuration); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>protected void generateReport(ISuite suite) { XMLStringBuffer document = new XMLStringBuffer(); document.addComment("Generated by " + getClass().getName()); long elapsedTime = 0; long testCount = 0; for (List<ITestResult> testResults : m_allTests.values()) { for (ITestResult tr : testResults) { elapsedTime += (tr.getEndMillis() - tr.getStartMillis()); testCount++; } } Properties attrs = new Properties(); attrs.setProperty(XMLConstants.ATTR_TESTS, "" + testCount); attrs.setProperty(XMLConstants.ATTR_TIME, "" + elapsedTime / 1000.0); attrs.setProperty(XMLConstants.ATTR_NAME, getModuleSuffix()); attrs.setProperty("skipped", "" + m_numSkipped); attrs.setProperty(XMLConstants.ATTR_ERRORS, "0"); attrs.setProperty(XMLConstants.ATTR_FAILURES, "" + (m_numFailed.get())); document.push(XMLConstants.TESTSUITE, attrs); showProperties(document); document.addComment("Tests results"); createElementFromTestResults(document, m_allTests.values()); document.pop(); Utils.writeUtf8File( <START> suite.getOutputDirectory().replaceAll(String.format("%sSurefire suite", File.pathSeparator), ""), <END> generateFileName(suite) + ".xml", document.toXML()); }</code><technical_language>Actually, replaceAll takes a regex parameter write: Utils.writeUtf8File(suite.getOutputDirectory().replaceAll(".Surefire suite", "") instead</technical_language>

Target:
protected void generateReport(ISuite suite) { XMLStringBuffer document = new XMLStringBuffer(); document.addComment("Generated by " + getClass().getName()); long elapsedTime = 0; long testCount = 0; for (List<ITestResult> testResults : m_allTests.values()) { for (ITestResult tr : testResults) { elapsedTime += (tr.getEndMillis() - tr.getStartMillis()); testCount++; } } Properties attrs = new Properties(); attrs.setProperty(XMLConstants.ATTR_TESTS, "" + testCount); attrs.setProperty(XMLConstants.ATTR_TIME, "" + elapsedTime / 1000.0); attrs.setProperty(XMLConstants.ATTR_NAME, getModuleSuffix()); attrs.setProperty("skipped", "" + m_numSkipped); attrs.setProperty(XMLConstants.ATTR_ERRORS, "0"); attrs.setProperty(XMLConstants.ATTR_FAILURES, "" + (m_numFailed.get())); document.push(XMLConstants.TESTSUITE, attrs); showProperties(document); document.addComment("Tests results"); createElementFromTestResults(document, m_allTests.values()); document.pop(); Utils.writeUtf8File(suite.getOutputDirectory().replaceAll(".Surefire suite", ""), generateFileName(suite) + ".xml", document.toXML()); }
Source:
<code>public void result(byte[] resultRowKey, WriteResult result) { boolean added = false; for (KVPair kvPair : resultsMap.keySet()) { byte[] currentRowKey = kvPair.getRowKey(); if (Arrays.equals(currentRowKey, resultRowKey)) { resultsMap.put(kvPair, result); added = true; break; } } if (!added) { for (KVPair kvPair : resultsMap.keySet()) { <START> byte[] currentRowKey = kvPair.getRowKey(); <END> resultsMap.put(kvPair, result); } } }</code><technical_language>currentRowKey is</technical_language>

Target:
public void result(byte[] resultRowKey, WriteResult result) { for (KVPair kvPair : resultsMap.keySet()) { byte[] currentRowKey = kvPair.getRowKey(); if (Arrays.equals(currentRowKey, resultRowKey)) { resultsMap.put(kvPair, result); return; } } throw new IllegalArgumentException("expected existing value in resultsMap"); }
Source:
<code>protected List<String> getInstallPlugins() { File root; try { root = distroLocator.locate(); } catch (FileNotFoundException e) { <START> log.warn("Couldn't open folder containing plugins." <END> + " No plugin will be installed"); return null; } ArrayList<String> result = Lists.newArrayList(); File plugins = new File(root, InitPlugins.PLUGIN_DIR); for (File p : plugins.listFiles()) { String pluginJarName = p.getName(); String pluginName = pluginJarName.substring(0, pluginJarName.length() - InitPlugins.JAR.length()); result.add(pluginName); } return result; }</code><technical_language>"Couldn't find distribution archive location."</technical_language>

Target:
protected List<String> getInstallPlugins() { File root; try { root = distroLocator.locate(); } catch (FileNotFoundException e) { log.warn("Couldn't find distribution archive location." + " No plugin will be installed"); return null; } ArrayList<String> result = Lists.newArrayList(); File plugins = new File(root, InitPlugins.PLUGIN_DIR); for (File p : plugins.listFiles()) { String pluginJarName = p.getName(); String pluginName = pluginJarName.substring(0, pluginJarName.length() - InitPlugins.JAR.length()); result.add(pluginName); } return result; }
Source:
<code>private Object[] getArgs(Method method) { int methodArity = method.getParameterTypes().length; <START> if (args.size() == methodArity) <END> return args.toArray(); if (args.size() > methodArity) throw new IllegalArgumentException(String.format("linkTo param args must have the same or lower length as method param args. linkTo args: %d | method args: %d", args.size(), methodArity)); Object[] noMissingParamsArgs = new Object[methodArity]; System.arraycopy(args.toArray(), 0, noMissingParamsArgs, 0, args.size()); return noMissingParamsArgs; }</code><technical_language>{} inline condition, please (in ifs here)</technical_language>

Target:
private Object[] getArgs(Method method) { int methodArity = method.getParameterTypes().length; if (args.size() == methodArity) { return args.toArray(); } if (args.size() > methodArity) { throw new IllegalArgumentException(String.format("linkTo param args must have the same or lower length as method param args. linkTo args: %d | method args: %d", args.size(), methodArity)); } Object[] noMissingParamsArgs = new Object[methodArity]; System.arraycopy(args.toArray(), 0, noMissingParamsArgs, 0, args.size()); return noMissingParamsArgs; }
Source:
<code>public Member suspendMember(PerunSession sess, Member member, String message) throws InternalErrorException, MemberNotValidYetException { if(this.haveStatus(sess, member, Status.SUSPENDED)) { log.warn("Trying to suspend member who is already suspended. Suspend operation will be procesed anyway (to be shure)." + member); } if(this.haveStatus(sess, member, Status.INVALID)) throw new MemberNotValidYetException(member); getMembersManagerImpl().setStatus(sess, member, Status.SUSPENDED); member.setStatus(Status.SUSPENDED); try { Attribute attribute = perunBl.getAttributesManagerBl().getAttribute(sess, member, "urn:perun:member:attribute-def:def:suspensionInfo"); HashMap<String, String> map = new LinkedHashMap<>(); if (message != null) { map.put("reason", message); } int id = -1; <START> User user = sess.getPerunPrincipal().getUser(); <END> if (user != null){ id = user.getId(); } map.put("userId", String.valueOf(id)); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); map.put("timestamp", String.valueOf(timestamp)); attribute.setValue(map); perunBl.getAttributesManagerBl().setAttribute(sess, member, attribute); } catch (WrongAttributeAssignmentException | AttributeNotExistsException | WrongAttributeValueException | WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } getPerunBl().getAuditer().log(sess, new MemberSuspended(member, Auditer.engineForceKeyword)); return member; }</code><technical_language>this fallback, call sess.getPerunPrincipal().getUserId()</technical_language>

Target:
public Member suspendMember(PerunSession sess, Member member, String message) throws InternalErrorException, MemberNotValidYetException { if(this.haveStatus(sess, member, Status.SUSPENDED)) { log.warn("Trying to suspend member who is already suspended. Suspend operation will be procesed anyway (to be shure)." + member); } if(this.haveStatus(sess, member, Status.INVALID)) throw new MemberNotValidYetException(member); getMembersManagerImpl().setStatus(sess, member, Status.SUSPENDED); member.setStatus(Status.SUSPENDED); try { Attribute attribute = perunBl.getAttributesManagerBl().getAttribute(sess, member, "urn:perun:member:attribute-def:def:suspensionInfo"); HashMap<String, String> map = new LinkedHashMap<>(); if (message != null) { map.put("reason", message); } int id = sess.getPerunPrincipal().getUserId(); map.put("userId", String.valueOf(id)); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); map.put("timestamp", String.valueOf(timestamp)); attribute.setValue(map); perunBl.getAttributesManagerBl().setAttribute(sess, member, attribute); } catch (WrongAttributeAssignmentException | AttributeNotExistsException | WrongAttributeValueException | WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } getPerunBl().getAuditer().log(sess, new MemberSuspended(member, Auditer.engineForceKeyword)); return member; }
Source:
<code>public void register(ManagementResourceRegistration parentRegistration) { ManagementResourceRegistration registration = parentRegistration.registerSubModel(this); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(Attribute.class) .addCapabilities(Capability.class) <START> .addRequiredSingletonChildren(ConnectionPoolResourceDefinition.PATH) <END> .addRequiredSingletonChildren(NoNearCacheResourceDefinition.PATH) .addRequiredSingletonChildren(ClientThreadPoolResourceDefinition.class) ; ResourceServiceHandler handler = new RemoteCacheContainerServiceHandler(); new AddStepHandler(descriptor, handler).register(registration); new RemoveStepHandler(descriptor, handler).register(registration); new ConnectionPoolResourceDefinition().register(registration); new InvalidationNearCacheResourceDefinition().register(registration); new NoNearCacheResourceDefinition().register(registration); EnumSet.allOf(ClientThreadPoolResourceDefinition.class).forEach(p -> p.register(registration)); }</code><technical_language>addRequiredChilden(...) "singleton children" means resource children child type, child resource is allowed exist for a child type. e.g. near-cache=invalidation near-cache=none</technical_language>

Target:
public ManagementResourceRegistration register(ManagementResourceRegistration parentRegistration) { ManagementResourceRegistration registration = parentRegistration.registerSubModel(this); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(Attribute.class) .addCapabilities(Capability.class) .addRequiredChildren(ConnectionPoolResourceDefinition.PATH) .addRequiredChildren(ThreadPoolResourceDefinition.CLIENT.getPathElement()) .addRequiredSingletonChildren(NoNearCacheResourceDefinition.PATH) ; ResourceServiceHandler handler = new RemoteCacheContainerServiceHandler(builderFactory); new RestartParentResourceRegistration<>(builderFactory, descriptor, handler).register(registration); new ConnectionPoolResourceDefinition().register(registration); new RemoteClusterResourceDefinition(builderFactory).register(registration); new InvalidationNearCacheResourceDefinition().register(registration); new NoNearCacheResourceDefinition().register(registration); ThreadPoolResourceDefinition.CLIENT.register(registration); return registration; }
Source:
<code><START> private void inlineSignatureValueIncludes(Element element, Collection<Attachment> attachments) throws IOException { <END> NodeList signatureNodes = element.getElementsByTagNameNS(SamlConstants.XML_SIGNATURE_NS, SamlConstants.SIGNATURE_VALUE_TAG); inlineIncludes(signatureNodes, attachments); }</code><technical_language>Please inlineSignatureValueIncludes static</technical_language>

Target:
private static void inlineSignatureValueIncludes(Element element, Collection<Attachment> attachments) throws IOException { NodeList signatureNodes = element.getElementsByTagNameNS(SamlConstants.XML_SIGNATURE_NS, SamlConstants.SIGNATURE_VALUE_TAG); inlineIncludes(signatureNodes, attachments); }
Source:
<code><START> public int[] getAdnRecordsSize(int efid) { <END> if (DBG) logd("getAdnRecordsSize: efid=" + efid); synchronized(mLock) { checkThread(); recordSize = new int[3]; Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE); ((SIMFileHandler)phone.getIccFileHandler()).getEFLinearRecordSize(efid, response); try { mLock.wait(); } catch (InterruptedException e) { logd("interrupted while trying to load from the SIM"); } } return recordSize; }</code><technical_language>Promote base class if casting needed</technical_language>

Target:
public int[] getAdnRecordsSize(int efid) { if (DBG) logd("getAdnRecordsSize: efid=" + efid); synchronized(mLock) { checkThread(); recordSize = new int[3]; Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE); phone.getIccFileHandler().getEFLinearRecordSize(efid, response); try { mLock.wait(); } catch (InterruptedException e) { logd("interrupted while trying to load from the SIM"); } } return recordSize; }
Source:
<code>public FileStatus getFileStatus(Path path) throws IOException { String key = keyFromPath(path); ObjectMetadata metadata = getS3ObjectMetadata(key); if (path.getName().isEmpty()) { if (metadata != null) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } if (metadata == null) { Iterator<LocatedFileStatus> iterator = listPrefix(path); <START> if (iterator.hasNext() || getS3ObjectMetadata(key + PATH_SEPARATOR) != null) { <END> return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } return new FileStatus( getObjectSize(path, metadata), false, 1, BLOCK_SIZE.toBytes(), lastModifiedTime(metadata), qualifiedPath(path)); }</code><technical_language>I missing here, but, path is /a, listPrefix list objects prefix /a/ (listPrefix appends PATH_SEPARATOR key). If returned iterator elements (so objects exist a key starts prefix /a/), getS3ObjectMetadata("/a/") return a non-null value</technical_language>

Target:
public FileStatus getFileStatus(Path path) throws IOException { if (path.getName().isEmpty()) { if (getS3ObjectMetadata(path) != null) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } ObjectMetadata metadata = getS3ObjectMetadata(path); if (metadata == null) { if (exists(path)) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } else { throw new FileNotFoundException("File does not exist: " + path); } } return new FileStatus( getObjectSize(path, metadata), false, 1, BLOCK_SIZE.toBytes(), lastModifiedTime(metadata), qualifiedPath(path)); }
Source:
<code>public void run() { Paging paging = new Paging(1, 200); List<Status> statuses = null; boolean KeepGoing = true; boolean hadFailure = false; do { int keepTrying = 0; while (keepTrying < 5) { try { statuses = client.getUserTimeline(id, paging); for (Status tStat : statuses) { String json = TwitterObjectFactory.getRawJSON(tStat); try { <START> provider.lock.readLock().lock(); <END> ComponentUtils.offerUntilSuccess(new StreamsDatum(json), provider.providerQueue); } finally { provider.lock.readLock().unlock(); } } paging.setPage(paging.getPage() + 1); keepTrying = 10; } catch(TwitterException twitterException) { keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException); } catch(Exception e) { keepTrying += TwitterErrorHandler.handleTwitterError(client, e); } } } while (provider.shouldContinuePulling(statuses)); LOGGER.info(id + " Thread Finished"); }</code><technical_language>broken encapsulation. accessing fields of provider class here, create a method in provider contains logic ass protected void addDatum(StreamsDatum datum) { try { lock.readLock().lock(); ComponentUtils.offerUntilSuccess(datum, providerQueue); } finally { lock.readLock().unlock(); } }</technical_language>

Target:
public void run() { Paging paging = new Paging(1, 200); List<Status> statuses = null; do { int keepTrying = 0; while (keepTrying < 5) { try { this.client = provider.getTwitterClient(); statuses = client.getUserTimeline(id, paging); for (Status tStat : statuses) { String json = TwitterObjectFactory.getRawJSON(tStat); provider.addDatum(new StreamsDatum(json)); } paging.setPage(paging.getPage() + 1); keepTrying = 10; } catch(TwitterException twitterException) { keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException); } catch(Exception e) { keepTrying += TwitterErrorHandler.handleTwitterError(client, e); } } } while (provider.shouldContinuePulling(statuses)); LOGGER.info(id + " Thread Finished"); }