auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createToken(JCas aJCas, StringBuilder text, Map<Integer, String> tokens, Map<Integer, String> pos, Map<Integer, String> lemma, Map<String, Token> tokensStored) { int tokenBeginPosition = 0; <START> int tokenEndPosition; <END> for (int i = 1; i <= tokens.size(); i++) { tokenBeginPosition = text.indexOf(tokens.get(i), tokenBeginPosition); Token outToken = new Token(aJCas, tokenBeginPosition, text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length()); tokenEndPosition = text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length(); tokenBeginPosition = tokenEndPosition; outToken.addToIndexes(); if (!pos.get(i).equals("_")) { POS outPos = new POS(aJCas, outToken.getBegin(), outToken.getEnd()); outPos.setPosValue(pos.get(i)); outPos.addToIndexes(); outToken.setPos(outPos); } if (!lemma.get(i).equals("_")) { Lemma outLemma = new Lemma(aJCas, outToken.getBegin(), outToken.getEnd()); outLemma.setValue(lemma.get(i)); outLemma.addToIndexes(); outToken.setLemma(outLemma); } tokensStored.put("t_" + i, outToken); } }</code><technical_language>I prefer explicit initalizers for primitive variables, if initialize JVM use</technical_language>

Target:
private void createToken(JCas aJCas, StringBuilder text, Map<Integer, String> tokens, Map<Integer, String> pos, Map<Integer, String> lemma, Map<String, Token> tokensStored) { int tokenBeginPosition = 0; int tokenEndPosition = 0; for (int i = 1; i <= tokens.size(); i++) { tokenBeginPosition = text.indexOf(tokens.get(i), tokenBeginPosition); Token outToken = new Token(aJCas, tokenBeginPosition, text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length()); tokenEndPosition = text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length(); tokenBeginPosition = tokenEndPosition; outToken.addToIndexes(); if (!pos.get(i).equals("_")) { POS outPos = new POS(aJCas, outToken.getBegin(), outToken.getEnd()); outPos.setPosValue(pos.get(i)); outPos.addToIndexes(); outToken.setPos(outPos); } if (!lemma.get(i).equals("_")) { Lemma outLemma = new Lemma(aJCas, outToken.getBegin(), outToken.getEnd()); outLemma.setValue(lemma.get(i)); outLemma.addToIndexes(); outToken.setLemma(outLemma); } tokensStored.put("t_" + i, outToken); } }
Source:
<code>public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { this.configuration = configuration; this.http = http; this.webhookManager = webhookManager; this.taskHistoryHelper = taskHistoryHelper; this.objectMapper = objectMapper; this.webhookSemaphore = AsyncSemaphore.newBuilder(configuration::getMaxConcurrentWebhooks).build(); <START> this.webhookExecutorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("webhooks-%d").build()); <END> }</code><technical_language>this guy is created</technical_language>

Target:
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { this.configuration = configuration; this.http = http; this.webhookManager = webhookManager; this.taskHistoryHelper = taskHistoryHelper; this.objectMapper = objectMapper; this.webhookSemaphore = AsyncSemaphore.newBuilder(configuration::getMaxConcurrentWebhooks).build(); }
Source:
<code>public Mono<AccessToken> getToken() throws InterruptedException, ExecutionException { if (isClosed) { throw logger.logExceptionAsError( new RuntimeException("getToken called on closed CommunicationTokenCredential object")); } <START> synchronized (this) { if ((accessToken == null || accessToken.isExpired()) && refresher != null) { return fetchFreshToken() .map(token -> { accessToken = tokenParser.parseJWTToken(token); return accessToken; }); } return Mono.just(accessToken); <END> } }</code><technical_language>a [SimpleTokenCache](<LINK_0> here. refreshes token expires ensures refresh expiration period</technical_language>

Target:
public Mono<AccessToken> getToken() throws InterruptedException, ExecutionException { if (isClosed) { return FluxUtil.monoError(logger, new RuntimeException("getToken called on closed CommunicationTokenCredential object")); } if ((accessToken == null || accessToken.isExpired()) && refresher != null) { synchronized (this) { if ((accessToken == null || accessToken.isExpired()) && refresher != null) { return fetchFreshToken() .map(token -> { accessToken = tokenParser.parseJWTToken(token); return accessToken; }); } } } return Mono.just(accessToken); }
Source:
<code>public NoteMap merge(NoteMap base, NoteMap ours, NoteMap theirs) throws IOException { InMemoryNoteBucket mergedBucket = merge(0, base.getRoot(), ours.getRoot(), theirs.getRoot()); <START> return NoteMap.newMap(mergedBucket, reader); <END> }</code><technical_language>Wrap of this method body in a try finally: try { ... current code ... } finally { reader.release(); inserter.release(); } caller release resources another method call</technical_language>

Target:
public NoteMap merge(NoteMap base, NoteMap ours, NoteMap theirs) throws IOException { try { InMemoryNoteBucket mergedBucket = merge(0, base.getRoot(), ours.getRoot(), theirs.getRoot()); inserter.flush(); return NoteMap.newMap(mergedBucket, reader); } finally { reader.release(); inserter.release(); } }
Source:
<code><START> String getOffsetMapString() { <END> StringBuilder sb = new StringBuilder(); sb.append("Current offsets map: "); for (TopicPartition tp : offsets.keySet()) { sb.append("p").append(tp.partition()).append("-") .append(offsets.get(tp).offset()).append(" "); } return sb.toString(); }</code><technical_language>I this private</technical_language>

Target:
private String getOffsetMapString() { StringBuilder sb = new StringBuilder(); sb.append(getName()).append(" current offsets map: "); for (TopicPartition tp : offsets.keySet()) { sb.append("p").append(tp.partition()).append("-") .append(offsets.get(tp).offset()).append(" "); } return sb.toString(); }
Source:
<code>public final void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Failure { initOptionList(); parseCommandLine(); if (abandonChange) { if (restoreChange) { throw error("abandon and restore actions are mutually exclusive"); } if (submitChange) { throw error("abandon and submit actions are mutually exclusive"); } if (publishPatchSet) { throw error("abandon and publish actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("abandon and delete actions are mutually exclusive"); } } if (publishPatchSet) { if (restoreChange) { throw error("publish and restore actions are mutually exclusive"); } if (submitChange) { throw error("publish and submit actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("publish and delete actions are mutually exclusive"); } } boolean ok = true; for (final PatchSet.Id patchSetId : patchSetIds) { try { <START> ok = ok && approveOne(patchSetId); <END> } catch (UnloggedFailure e) { ok = false; writeError("error: " + e.getMessage() + "\n"); } catch (Exception e) { ok = false; writeError("fatal: internal server error while approving " + patchSetId + "\n"); log.error("internal error while approving " + patchSetId, e); } } if (!ok) { throw new UnloggedFailure(1, "one or more approvals failed;" + " review output above"); } } }); }</code><technical_language>badly I want this change, this feels a regression. Imagine I "--sync" I submit review multiple changes. This prevent subsequent changes attempted if fails</technical_language>

Target:
public final void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Failure { initOptionList(); parseCommandLine(); if (abandonChange) { if (restoreChange) { throw error("abandon and restore actions are mutually exclusive"); } if (submitChange) { throw error("abandon and submit actions are mutually exclusive"); } if (publishPatchSet) { throw error("abandon and publish actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("abandon and delete actions are mutually exclusive"); } } if (publishPatchSet) { if (restoreChange) { throw error("publish and restore actions are mutually exclusive"); } if (submitChange) { throw error("publish and submit actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("publish and delete actions are mutually exclusive"); } } boolean ok = true; for (final PatchSet.Id patchSetId : patchSetIds) { try { boolean oneOk = approveOne(patchSetId); ok = ok && oneOk; } catch (UnloggedFailure e) { ok = false; writeError("error: " + e.getMessage() + "\n"); } catch (Exception e) { ok = false; writeError("fatal: internal server error while approving " + patchSetId + "\n"); log.error("internal error while approving " + patchSetId, e); } } if (!ok) { throw new UnloggedFailure(1, "one or more approvals failed;" + " review output above"); } } }); }
Source:
<code>public void dumpMemory() { <START> for (Map.Entry<Double, Double> entry : new TreeMap<>(memory).entrySet()) { <END> log.info(entry.getKey() + "\t" + entry.getValue()); } }</code><technical_language>is another of sorting TreeMap. a debug method, I functionality change</technical_language>

Target:
public void dumpMemory() { Double[] keys = memory.keySet().toArray(new Double[memory.keySet().size()]); Arrays.sort(keys); for (Double key : keys) { log.info(key + "\t" + memory.get(key)); } }
Source:
<code>List<Transaction> sortTxnsByDependency(Set<Transaction> inputSet) { <START> List<Transaction> result = new ArrayList<Transaction>(inputSet); <END> for (int i = 0; i < result.size()-1; i++) { boolean txAtISpendsOtherTxInTheList; do { txAtISpendsOtherTxInTheList = false; for (int j = i+1; j < result.size(); j++) { if (spends(result.get(i), result.get(j))) { Transaction transactionAtI = result.remove(i); result.add(j, transactionAtI); txAtISpendsOtherTxInTheList = true; break; } } } while (txAtISpendsOtherTxInTheList); } return result; }</code><technical_language>Some JVMs do type sharpening e.g. Android a bit faster write out ArrayList explicitly here. a big deal</technical_language>

Target:
List<Transaction> sortTxnsByDependency(Set<Transaction> inputSet) { ArrayList<Transaction> result = new ArrayList<Transaction>(inputSet); for (int i = 0; i < result.size()-1; i++) { boolean txAtISpendsOtherTxInTheList; do { txAtISpendsOtherTxInTheList = false; for (int j = i+1; j < result.size(); j++) { if (spends(result.get(i), result.get(j))) { Transaction transactionAtI = result.remove(i); result.add(j, transactionAtI); txAtISpendsOtherTxInTheList = true; break; } } } while (txAtISpendsOtherTxInTheList); } return result; }
Source:
<code>public CompletableFuture<Registration> register(String procedure, IInvocationHandler endpoint, RegisterOptions options) { <START> if (!isAttached()) { <END> throw new IllegalStateException("The transport must be connected first"); } CompletableFuture<Registration> future = new CompletableFuture<>(); long requestID = mIDGenerator.next(); mRegisterRequest.put(requestID, new RegisterRequest(requestID, future, procedure, endpoint)); if (options != null) { mTransport.send(new Register(requestID, procedure, options.match, options.invoke)); } else { mTransport.send(new Register(requestID, procedure, null, null)); } return future; }</code><technical_language>this isConnected() .</technical_language>

Target:
public CompletableFuture<Registration> register(String procedure, IInvocationHandler endpoint, RegisterOptions options) { if (!isConnected()) { throw new IllegalStateException("The transport must be connected first"); } CompletableFuture<Registration> future = new CompletableFuture<>(); long requestID = mIDGenerator.next(); mRegisterRequest.put(requestID, new RegisterRequest(requestID, future, procedure, endpoint)); if (options != null) { mTransport.send(new Register(requestID, procedure, options.match, options.invoke)); } else { mTransport.send(new Register(requestID, procedure, null, null)); } return future; }
Source:
<code>public void setAttributeMap(List<String> attributeMapEntries) { this.attributeMap = new HashMap<>(); for (String entry : attributeMapEntries) { String[] keyValuePair = entry.split("(?<!\\\\)(?:\\\\\\\\)*=", 2); if (keyValuePair.length == 2) { this.attributeMap.put( StringEscapeUtils.unescapeJava(keyValuePair[0]), StringEscapeUtils.unescapeJava(keyValuePair[1])); } else { <START> LOGGER.error("Invalid attribute map entry: {}", entry); <END> } } }</code><technical_language>Warning, admin fix it</technical_language>

Target:
public void setAttributeMap(List<String> attributeMapEntries) { this.attributeMap = new HashMap<>(); for (String entry : attributeMapEntries) { String[] keyValuePair = entry.split("(?<!\\\\)(?:\\\\\\\\)*=", 2); if (keyValuePair.length == 2) { this.attributeMap.put( StringEscapeUtils.unescapeJava(keyValuePair[0]), StringEscapeUtils.unescapeJava(keyValuePair[1])); } else { LOGGER.error( "Invalid attribute map entry: \"{}\". Entries must be of the form \"claim=attribute\"", entry); } } setSupportedClaims(this.attributeMap.keySet()); }
Source:
<code>public static Slice serialize(OGCGeometry input) { int wkid = input.SRID(); Geometry geometry = input.getEsriGeometry(); <START> if (geometry == null) { <END> return EMPTY_SLICE; } byte[] shape = GeometryEngine.geometryToEsriShape(geometry); if (shape == null) { return EMPTY_SLICE; } Slice result = Slices.allocate(shape.length + SIZE_WKID); result.setInt(0, wkid); result.setBytes(SIZE_WKID, shape); return result; }</code><technical_language>input is instance of GeometryCollection, geometry null. serializing GeometryCollection produce empty slice. Is this intentional? --- com.esri.core.geometry.ogc.OGCConcreteGeometryCollection public Geometry getEsriGeometry() { return null; } public GeometryCursor getEsriGeometryCursor() { return new OGCConcreteGeometryCollection.GeometryCursorOGC(this.geometries); }</technical_language>

Target:
public static Slice serialize(OGCGeometry input) { int spatialReferenceId = input.SRID(); DynamicSliceOutput sliceOutput = new DynamicSliceOutput(100); sliceOutput.appendInt(spatialReferenceId); GeometryCursor cursor = input.getEsriGeometryCursor(); while (true) { Geometry geometry = cursor.next(); if (geometry == null) { break; } byte[] shape = geometryToEsriShape(geometry); sliceOutput.appendInt(shape.length); sliceOutput.appendBytes(shape); } return sliceOutput.slice(); }
Source:
<code><START> public WebElement getToolbarLoggedInUser() { return toolbarLoggedInUser; <END> }</code><technical_language>Please return String this element [getTextFromElement](<LINK_0> includes some hacks (and more added in future). suggestion public String getToolbarLoggedInUser() { return getTextFromElement(toolbarLoggedInUser);</technical_language>

Target:
public String getToolbarLoggedInUser() { return getTextFromElement(toolbarLoggedInUser); }
Source:
<code>public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, Joiner.on(",").join(indices)); <START> } else { <END> conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, ""); } }</code><technical_language>prefer: String = ""; if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } = Joiner.on(",").join(indices); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, value);</technical_language>

Target:
public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { String value = ""; if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } value = Joiner.on(",").join(indices); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, value); }
Source:
<code>protected EntityManagerFactory newEntityManagerFactory() { logger.debug("Creating EntityManagerFactory..."); Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.url", JpaConfiguration.dbConnectionUrl); properties.put("javax.persistence.jdbc.driver", JpaConfiguration.dbDriverClass); if(JpaConfiguration.dbUserName != null) { properties.put("javax.persistence.jdbc.user", JpaConfiguration.dbUserName); } if(JpaConfiguration.dbPassword != null) { properties.put("javax.persistence.jdbc.password", JpaConfiguration.dbPassword); <START> } <END> EntityManagerFactory fac = Persistence.createEntityManagerFactory(getPersistenceUnitName(), properties); logger.debug("Creating EntityManagerFactory...done"); return fac; }</code><technical_language>a good idea INFO/WARN log a message stating strongly advice set a username + password</technical_language>

Target:
protected EntityManagerFactory newEntityManagerFactory() { logger.debug("Creating EntityManagerFactory..."); Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.url", JpaConfiguration.dbConnectionUrl); properties.put("javax.persistence.jdbc.driver", JpaConfiguration.dbDriverClass); if(JpaConfiguration.dbUserName != null) { properties.put("javax.persistence.jdbc.user", JpaConfiguration.dbUserName); } if(JpaConfiguration.dbPassword != null) { properties.put("javax.persistence.jdbc.password", JpaConfiguration.dbPassword); } if(JpaConfiguration.dbUserName != null && JpaConfiguration.dbPassword == null) { logger.warn("JPA persistence - it is recommended to use a password to protect data store"); } EntityManagerFactory fac = Persistence.createEntityManagerFactory(getPersistenceUnitName(), properties); logger.debug("Creating EntityManagerFactory...done"); return fac; }
Source:
<code>public void testCtor() throws UnsupportedEncodingException { final LocalizedMessage addExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "DefaultLogger.addException", new String[] {"myfile"}, null, <START> LocalizedMessage.class, null); <END> final OutputStream infoStream = new ByteArrayOutputStream(); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); final DefaultLogger dl = new DefaultLogger(infoStream, true, errorStream, true); dl.addException(new AuditEvent(5000, "myfile"), new IllegalStateException("upsss")); dl.auditFinished(new AuditEvent(6000, "myfile")); final String output = errorStream.toString("UTF-8"); assertTrue(output.contains(addExceptionMessage.getMessage())); assertTrue(output.contains("java.lang.IllegalStateException: upsss")); }</code><technical_language>@subkrish , please move declaration of addExceptionMessage close usage. Please apply fix for other cases in this PR</technical_language>

Target:
public void testCtor() throws UnsupportedEncodingException { final OutputStream infoStream = new ByteArrayOutputStream(); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); final DefaultLogger dl = new DefaultLogger(infoStream, true, errorStream, true); dl.addException(new AuditEvent(5000, "myfile"), new IllegalStateException("upsss")); dl.auditFinished(new AuditEvent(6000, "myfile")); final String output = errorStream.toString("UTF-8"); final LocalizedMessage addExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "DefaultLogger.addException", new String[] {"myfile"}, null, getClass(), null); assertTrue(output.contains(addExceptionMessage.getMessage())); assertTrue(output.contains("java.lang.IllegalStateException: upsss")); }
Source:
<code>private static Geometry readPolyline(SliceInput input) { requireNonNull(input, "input is null"); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { return GEOMETRY_FACTORY.createLineString(); } int pointCount = input.readInt(); <START> LineString[] lineStrings = new LineString[partCount]; <END> int[] numnParts = new int[partCount]; input.readInt(); if (partCount > 1) { numnParts[0] = input.readInt(); for (int i = 1; i < partCount - 1; i++) { numnParts[i] = input.readInt() - numnParts[i - 1]; } numnParts[partCount - 1] = pointCount - numnParts[partCount - 2]; } else { numnParts[0] = pointCount; } for (int i = 0; i < partCount; i++) { lineStrings[i] = GEOMETRY_FACTORY.createLineString(readCoordinates(input, numnParts[i])); } if (lineStrings.length == 1) { return lineStrings[0]; } return GEOMETRY_FACTORY.createMultiLineString(lineStrings); }</code><technical_language>s/numnParts/numParts</technical_language>

Target:
private static Geometry readPolyline(SliceInput input) { requireNonNull(input, "input is null"); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { return GEOMETRY_FACTORY.createLineString(); } int pointCount = input.readInt(); LineString[] lineStrings = new LineString[partCount]; int[] partLengths = new int[partCount]; input.readInt(); if (partCount > 1) { partLengths[0] = input.readInt(); for (int i = 1; i < partCount - 1; i++) { partLengths[i] = input.readInt() - partLengths[i - 1]; } partLengths[partCount - 1] = pointCount - partLengths[partCount - 2]; } else { partLengths[0] = pointCount; } for (int i = 0; i < partCount; i++) { lineStrings[i] = GEOMETRY_FACTORY.createLineString(readCoordinates(input, partLengths[i])); } if (lineStrings.length == 1) { return lineStrings[0]; } return GEOMETRY_FACTORY.createMultiLineString(lineStrings); }
Source:
<code>protected void verifyOutput(NestedOwnerDTO source, Owner dest, boolean childrenGenerated) { if (source != null) { <START> assertNotNull(dest.getId()); assertEquals(source.getKey(), dest.getKey()); assertNotNull(dest.getDisplayName()); <END> } else { assertNull(dest); } }</code><technical_language>assertEquals(<source value>, <destination value>)</technical_language>

Target:
protected void verifyOutput(NestedOwnerDTO source, Owner dest, boolean childrenGenerated) { if (source != null) { assertEquals(source.getId(), dest.getId()); assertEquals(source.getKey(), dest.getKey()); assertEquals(source.getDisplayName(), dest.getDisplayName()); } else { assertNull(dest); } }
Source:
<code>public void start() { try { String location = configuration.location(); if (location == null || location.trim().length() == 0) location = "Infinispan-SingleFileStore"; File f = new File(location + File.separator + ctx.getCache().getName() + ".dat"); if (!f.exists()) { File dir = f.getParentFile(); <START> synchronized (SingleFileStore.class) { <END> if (!dir.exists() && !dir.mkdirs()) { throw log.directoryCannotBeCreated(dir.getAbsolutePath()); } } } file = new RandomAccessFile(f, "rw").getChannel(); entries = newEntryMap(); freeList = Collections.synchronizedSortedSet(new TreeSet<FileEntry>()); byte[] header = new byte[MAGIC.length]; if (file.read(ByteBuffer.wrap(header), 0) == MAGIC.length && Arrays.equals(MAGIC, header)) rebuildIndex(); else clear(); } catch (Exception e) { throw new CacheLoaderException(e); } }</code><technical_language>this solves problem if stores in VM. retry in a loop</technical_language>

Target:
public void start() { try { String location = configuration.location(); if (location == null || location.trim().length() == 0) location = "Infinispan-SingleFileStore"; File f = new File(location + File.separator + ctx.getCache().getName() + ".dat"); if (!f.exists()) { File dir = f.getParentFile(); if (!dir.mkdirs() && !dir.exists()) { throw log.directoryCannotBeCreated(dir.getAbsolutePath()); } } file = new RandomAccessFile(f, "rw").getChannel(); entries = newEntryMap(); freeList = Collections.synchronizedSortedSet(new TreeSet<FileEntry>()); byte[] header = new byte[MAGIC.length]; if (file.read(ByteBuffer.wrap(header), 0) == MAGIC.length && Arrays.equals(MAGIC, header)) rebuildIndex(); else clear(); } catch (Exception e) { throw new CacheLoaderException(e); } }
Source:
<code>snapshotIOStatistics(IOStatistics statistics) { IOStatisticsSnapshot stats = new IOStatisticsSnapshot(statistics); <START> stats.snapshot(statistics); <END> return stats; }</code><technical_language>do need call snapshot() again? I snapshot calculation happened in previous call constructor initialisation</technical_language>

Target:
snapshotIOStatistics(IOStatistics statistics) { return new IOStatisticsSnapshot(statistics); }
Source:
<code>private long countMapWithBackupReadEnabled(Node node) { return maps.stream().filter(distributedObject -> node.getConfig(). <START> getMapConfig(distributedObject.getName()).isReadBackupData()).count(); <END> }</code><technical_language>worried config.getMapConfig() returning null in some edge cases (eg. if map exists collect maps node, is destroyed this line executed?). please this NPE-proof</technical_language>

Target:
private long countMapWithBackupReadEnabled(Node node) { return maps.stream().filter(distributedObject -> { MapConfig config = node.getConfig().getMapConfig(distributedObject.getName()); if (config != null) { return config.isReadBackupData(); } return false; }).count(); }
Source:
<code>public long hash(int value) { <START> ByteBuffer plain = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE); <END> plain.order(ByteOrder.LITTLE_ENDIAN).putInt(value); return hashFunction.hashByteBuffer(plain); }</code><technical_language>speed hashing a ByteBuffer cache created class level. create a 64bit long buffer set ordering once. Then, clear buffer putting a in flip invoking hashByteBuffer. In other hand I functions hashLong hashInt in LongHashFunction. worth update HashFunction interface call directly. I options is performs better</technical_language>

Target:
public long hash(int value) { cacheBuffer.putInt(value); return doHash(); }
Source:
<code>public void newEvent(long bucketKey, T event) { int bucketIdx = (int) (bucketKey % noOfBuckets); AbstractBucket<T> bucket = buckets[bucketIdx]; logger.debug("Adding event to bucket index {}", event, bucketIdx); if(bucket != null){ logger.debug("Old Bucket Key {}, Requested {}", bucket.bucketKey, bucketKey); } if (bucket == null || bucket.bucketKey != bucketKey) { <START> bucket = createBucket(bucketKey); <END> buckets[bucketIdx] = bucket; dirtyBuckets.put(bucketIdx, bucket); } else if (dirtyBuckets.get(bucketIdx) == null) { dirtyBuckets.put(bucketIdx, bucket); } bucket.addNewEvent(bucket.getEventKey(event), writeEventKeysOnly ? null : event); bucketCounters.getCounter(BucketManager.CounterKeys.EVENTS_IN_MEMORY).increment(); Long max = maxExpiryPerBucket[bucketIdx]; long eventTime = getExpiryKey(event); if (max == null || eventTime > max) { maxExpiryPerBucket[bucketIdx] = eventTime; } }</code><technical_language>Do need decrement EVENTS_IN_MEMORY</technical_language>

Target:
public void newEvent(long bucketKey, T event) { super.newEvent(bucketKey, event); int bucketIdx = (int) (bucketKey % noOfBuckets); Long max = maxExpiryPerBucket[bucketIdx]; long expiryKey = getExpiryKey(event); if (max == 0 || expiryKey > max) { maxExpiryPerBucket[bucketIdx] = expiryKey; } }
Source:
<code>private static String setupDatabase() { List<String> statements = STATEMENT_SPLITTER.splitToList(scriptContents); for (int i = 1; i < statements.size(); i++) { String statement = statements.get(i); try { SESSION_RULE.session().execute(statement); } catch (Exception e) { fail("Error executing statement %s (%s)", statement, e); } } <START> return scriptContents; <END> }</code><technical_language>nit: return is</technical_language>

Target:
private static void setupDatabase() { List<String> statements = STATEMENT_SPLITTER.splitToList(scriptContents); for (int i = 1; i < statements.size(); i++) { String statement = statements.get(i); try { SESSION_RULE.session().execute(statement); } catch (Exception e) { fail("Error executing statement %s (%s)", statement, e); } } }
Source:
<code>private static Instance initializeOpenSourceSoftwareInstanceBuilder(String url) { Instance instance = new Instance(); instance.setInstancetype(INSTANCE_TYPE_SOFTWARE); instance.setAccessright(ACCESS_RIGHT_OPEN_SOURCE); <START> instance.setUrl(Arrays.asList(url)); <END> return instance; }</code><technical_language>IDE Collections.singletonList</technical_language>

Target:
private static Instance initializeOpenSourceSoftwareInstanceBuilder(String url) { Instance instance = new Instance(); instance.setInstancetype(INSTANCE_TYPE_SOFTWARE); instance.setAccessright(ACCESS_RIGHT_OPEN_SOURCE); instance.setUrl(Collections.singletonList(url)); return instance; }
Source:
<code>public static void waitForIndexState(Connection conn, String fullIndexName, PIndexState expectedIndexState) throws InterruptedException, SQLException { int maxTries = 60; <START> RetryCounter retrier = new RetryCounter(maxTries, <END> 1, TimeUnit.SECONDS); while (retrier.shouldRetry()) { String schema = SchemaUtil.getSchemaNameFromFullName(fullIndexName); String index = SchemaUtil.getTableNameFromFullName(fullIndexName); String query = "SELECT " + PhoenixDatabaseMetaData.INDEX_STATE + " FROM " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME + " WHERE (" + PhoenixDatabaseMetaData.TABLE_SCHEM + "," + PhoenixDatabaseMetaData.TABLE_NAME + ") = (" + "'" + schema + "','" + index + "') " + "AND " + PhoenixDatabaseMetaData.COLUMN_FAMILY + " IS NULL AND " + PhoenixDatabaseMetaData.COLUMN_NAME + " IS NULL"; ResultSet rs = conn.createStatement().executeQuery(query); PIndexState actualIndexState = null; if (rs.next()) { actualIndexState = PIndexState.fromSerializedValue(rs.getString(1)); boolean matchesExpected = (actualIndexState == expectedIndexState); if (matchesExpected) { return; } } retrier.sleepUntilNextRetry(); } fail("Ran out of time waiting for index state to become " + expectedIndexState); }</code><technical_language>@gokceni - Unfortunately, RetryCounter is InterfaceAudience.Private in HBase, means projects Phoenix depend it</technical_language>

Target:
public static void waitForIndexState(Connection conn, String fullIndexName, PIndexState expectedIndexState) throws InterruptedException, SQLException { int maxTries = 60, nTries = 0; do { String schema = SchemaUtil.getSchemaNameFromFullName(fullIndexName); String index = SchemaUtil.getTableNameFromFullName(fullIndexName); Thread.sleep(1000); String query = "SELECT " + PhoenixDatabaseMetaData.INDEX_STATE + " FROM " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME + " WHERE (" + PhoenixDatabaseMetaData.TABLE_SCHEM + "," + PhoenixDatabaseMetaData.TABLE_NAME + ") = (" + "'" + schema + "','" + index + "') " + "AND " + PhoenixDatabaseMetaData.COLUMN_FAMILY + " IS NULL AND " + PhoenixDatabaseMetaData.COLUMN_NAME + " IS NULL"; ResultSet rs = conn.createStatement().executeQuery(query); PIndexState actualIndexState = null; if (rs.next()) { actualIndexState = PIndexState.fromSerializedValue(rs.getString(1)); boolean matchesExpected = (actualIndexState == expectedIndexState); if (matchesExpected) { return; } } } while (++nTries < maxTries); fail("Ran out of time waiting for index state to become " + expectedIndexState); }
Source:
<code>public void release() { if (referenceCount.decrementAndGet() == 0) { Futures.addCallback(pagesFuture, new FutureCallback<NestedLoopJoinPages>() { @Override public void onSuccess(NestedLoopJoinPages result) { result.freeMemory(); } @Override public void onFailure(Throwable t) { } <START> }, directExecutor()); <END> } }</code><technical_language>Replace addSuccessCallback MoreFutures</technical_language>

Target:
public void release() { if (referenceCount.decrementAndGet() == 0) { addSuccessCallback(pagesFuture, result -> result.freeMemory()); } }
Source:
<code>public String resolveElasticServerDir() { final String value = configuration.esServerDir(); if ( !nullToEmpty( value ).isBlank() ) { return value; } <START> return HomeDir.get().toString() + "/../elasticsearch"; <END> }</code><technical_language>Do contacte file paths. HomeDir.toFile().toPath() resolve it</technical_language>

Target:
public String resolveElasticServerDir() { final String value = configuration.esServerDir(); return getPathOfDirAsString( value, "../elasticsearch" ); }
Source:
<code>public static void updateLRAContext(ClientRequestContext context) { URL lraId = Current.peek(); if (lraId != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraId); } else { <START> Object lraContext = getState("suspendedLRA"); <END> if (lraContext == null) lraContext = context.getProperty(LRA_HTTP_HEADER); if (lraContext != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraContext); } else { context.getHeaders().remove(LRA_HTTP_HEADER); } } }</code><technical_language>Is worth a "final static String" here</technical_language>

Target:
public static void updateLRAContext(ClientRequestContext context) { URL lraId = Current.peek(); if (lraId != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraId); } else { Object lraContext = context.getProperty(LRA_HTTP_HEADER); if (lraContext != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraContext); } else { context.getHeaders().remove(LRA_HTTP_HEADER); } } }
Source:
<code>public static void setupEventTypeWithEvents() throws JsonProcessingException, InterruptedException { eventType = createEventType(); final CountDownLatch finished = new CountDownLatch(1); final AtomicReference<String[]> inTimeCursors = new AtomicReference<>(); createParallelConsumer(eventType.getName(), 8, finished, inTimeCursors::set); final long start = System.currentTimeMillis(); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); finished.await(); cursorsDuringPublish = inTimeCursors.get(); <START> System.out.println("Total took: " + (System.currentTimeMillis() - start)/1000); <END> }</code><technical_language>do need that</technical_language>

Target:
public static void setupEventTypeWithEvents() throws JsonProcessingException, InterruptedException { eventType = createEventType(); final CountDownLatch finished = new CountDownLatch(1); final AtomicReference<String[]> inTimeCursors = new AtomicReference<>(); createParallelConsumer(eventType.getName(), 8, finished, inTimeCursors::set); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); finished.await(); cursorsDuringPublish = inTimeCursors.get(); }
Source:
<code>public void append(Entry entry) throws IOException { <START> transactionEntries.add(entry); <END> }</code><technical_language>Instead of collecting transaction edit logs here, add count header in AbstractTransactionLog.sync() method calling append, right? edit logs collected there, avoid code duplication</technical_language>

Target:
public void append(Entry entry) throws IOException { internalWriter.append(entry.getKey(), entry.getEdit()); }
Source:
<code>public void testReadPipePosixCommandStartFailure() throws CommandFailedException { FS fs = FS.DETECTED.newInstance(); <START> assumeTrue(fs instanceof FS_POSIX); <END> FS.readPipe(fs.userHome(), new String[] { "this-command-does-not-exist" }, Charset.defaultCharset().name()); }</code><technical_language>do assume fs posix? This test fail a windows machine, or</technical_language>

Target:
public void testReadPipePosixCommandStartFailure() throws CommandFailedException { FS fs = FS.DETECTED.newInstance(); FS.readPipe(fs.userHome(), new String[] { "this-command-does-not-exist" }, Charset.defaultCharset().name()); }
Source:
<code>private boolean release0(int decrement) { int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { <START> maxCapacity(-rawMaxCapacity()); <END> deallocate(); return true; } return retryRelease0(decrement); } return releaseNonFinal0(decrement, rawCnt, realCnt); }</code><technical_language>assert this positive</technical_language>

Target:
private boolean release0(int decrement) { int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { maxCapacity(-maxCapacity()); deallocate(); return true; } return retryRelease0(decrement); } return releaseNonFinal0(decrement, rawCnt, realCnt); }
Source:
<code><START> public static EchoTagStatementTree newEchoTagStatement(ExpressionTree expression, InternalSyntaxToken eosToken) { <END> SeparatedList<ExpressionTree> expressionList = new SeparatedListImpl(Collections.singletonList(expression), Collections.emptyList()); return newEchoTagStatement(expressionList, eosToken); }</code><technical_language>this method private</technical_language>

Target:
private static EchoTagStatementTree newEchoTagStatement(ExpressionTree expression, InternalSyntaxToken eosToken) { SeparatedList<ExpressionTree> expressionList = new SeparatedListImpl<>(Collections.singletonList(expression), Collections.emptyList()); return newEchoTagStatement(expressionList, eosToken); }
Source:
<code>boolean wouldPushProject(Project.NameKey project) { if (projects.length < 1) { return true; } for (final String projectMatch : projects) { if (isRE(projectMatch)) { <START> if ((new RegExp(projectMatch, RegExp.NONE)). <END> toAutomaton().run(project.get())) return true; } else if (projectMatch.endsWith("/*")) { if (project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1))) return true; } else if (project.get().equals(projectMatch)) { return true; } } return false; }</code><technical_language>nit: extra set of parrens new block kind of confusing</technical_language>

Target:
boolean wouldPushProject(Project.NameKey project) { if (projects.length < 1) { return true; } for (final String projectMatch : projects) { if (isRE(projectMatch)) { if (new RegExp(projectMatch, RegExp.NONE). toAutomaton().run(project.get())) return true; } else if (projectMatch.endsWith("/*")) { if (project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1))) return true; } else if (project.get().equals(projectMatch)) { return true; } } return false; }
Source:
<code><START> public Map<String, String> getQuota() { <END> return quota; }</code><technical_language>@waymirec -- splitting this 2 methods -- for maxSpace & spaceUsed -- non-String return types</technical_language>

Target:
public EmailQuota getQuota() { return quota; }
Source:
<code>public int execute() { try { AtlasReplInfo atlasReplInfo = createAtlasReplInfo(); LOG.info("Dumping Atlas metadata of srcDb: {}, for TgtDb: to staging location:", atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir()); atlasRestClient = new AtlasRestClientBuilder(atlasReplInfo.getAtlasEndpoint()) .getClient(atlasReplInfo.getConf()); AtlasRequestBuilder atlasRequestBuilder = new AtlasRequestBuilder(); String entityGuid = checkHiveEntityGuid(atlasRequestBuilder, atlasReplInfo.getSrcCluster(), atlasReplInfo.getSrcDB()); long currentModifiedTime = getCurrentTimestamp(atlasReplInfo, entityGuid); AtlasDumpLogger replLogger = new AtlasDumpLogger(atlasReplInfo.getSrcDB(), atlasReplInfo.getStagingDir().toString()); <START> replLogger.startLog(); <END> long numBytesWritten = dumpAtlasMetaData(atlasRequestBuilder, atlasReplInfo); LOG.debug("Finished dumping atlas metadata, total:{} bytes written", numBytesWritten); replLogger.endLog(0L); createDumpMetadata(atlasReplInfo, currentModifiedTime); return 0; } catch (Exception e) { LOG.error("Exception while dumping atlas metadata", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }</code><technical_language>start called atlas dump task starts. This give complete estimate of time taken</technical_language>

Target:
public int execute() { try { AtlasReplInfo atlasReplInfo = createAtlasReplInfo(); LOG.info("Dumping Atlas metadata of srcDb: {}, for TgtDb: to staging location:", atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir()); AtlasDumpLogger replLogger = new AtlasDumpLogger(atlasReplInfo.getSrcDB(), atlasReplInfo.getStagingDir().toString()); replLogger.startLog(); atlasRestClient = new AtlasRestClientBuilder(atlasReplInfo.getAtlasEndpoint()) .getClient(atlasReplInfo.getConf()); AtlasRequestBuilder atlasRequestBuilder = new AtlasRequestBuilder(); String entityGuid = checkHiveEntityGuid(atlasRequestBuilder, atlasReplInfo.getSrcCluster(), atlasReplInfo.getSrcDB()); long currentModifiedTime = getCurrentTimestamp(atlasReplInfo, entityGuid); long numBytesWritten = dumpAtlasMetaData(atlasRequestBuilder, atlasReplInfo); LOG.debug("Finished dumping atlas metadata, total:{} bytes written", numBytesWritten); createDumpMetadata(atlasReplInfo, currentModifiedTime); replLogger.endLog(0L); return 0; } catch (Exception e) { LOG.error("Exception while dumping atlas metadata", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }
Source:
<code>public static Map<String, Integer> getDRTableNamePartitionColumnMapping(Database db) { Map<String, Integer> res = new HashMap<String, Integer>(); for (Table tb : db.getTables()) { <START> if (tb.getIsdred()) { <END> res.put(tb.getTypeName(), tb.getPartitioncolumn().getIndex()); } } return res; }</code><technical_language>ignore replicated tables</technical_language>

Target:
public static Map<String, Integer> getDRTableNamePartitionColumnMapping(Database db) { Map<String, Integer> res = new HashMap<String, Integer>(); for (Table tb : db.getTables()) { if (!tb.getIsreplicated() && tb.getIsdred()) { res.put(tb.getTypeName(), tb.getPartitioncolumn().getIndex()); } } return res; }
Source:
<code><START> LockFactory pickLockFactory(RuntimeEnvironment env) { <END> String luceneLocking = env.getLuceneLocking(); switch (luceneLocking) { case LuceneLockName.OFF: return NoLockFactory.INSTANCE; case LuceneLockName.ON: case LuceneLockName.SIMPLE: return SimpleFSLockFactory.INSTANCE; case LuceneLockName.NATIVE: return NativeFSLockFactory.INSTANCE; default: LOGGER.log(Level.WARNING, "Unknown Lucene locking mode: {0}", luceneLocking); return NoLockFactory.INSTANCE; } }</code><technical_language>lockpick factory :-D</technical_language>

Target:
LockFactory pickLockFactory(RuntimeEnvironment env) { switch (env.getLuceneLocking()) { case ON: case SIMPLE: return SimpleFSLockFactory.INSTANCE; case NATIVE: return NativeFSLockFactory.INSTANCE; case OFF: default: return NoLockFactory.INSTANCE; } }
Source:
<code><START> public final void create() throws Exception { <END> final String name = "test-repo"; final Github github = RtReposITCase.github(); final Repos repos = github.repos(); final Repo repo = repos.create(request(name)); MatcherAssert.assertThat(repo, Matchers.notNullValue()); }</code><technical_language>good, work once. If I run twice, execution fail, a repository this name (test-repo) exists. options: 1) generate a unique name test run, RandomStringUtils, for example, 2) delete repository test execution in finally block. I recommend options</technical_language>

Target:
public final void create() throws Exception { final String name = RandomStringUtils.randomNumeric(5); final Repos repos = RtReposITCase.github().repos(); try { MatcherAssert.assertThat( repos.create(request(name)), Matchers.notNullValue() ); } finally { final Coordinates.Simple coordinates = new Coordinates.Simple( RtReposITCase.github().users().self().login(), name ); repos.remove(coordinates); } }
Source:
<code>public String getReleaseNotesForFixVersion(String projectKey, String versionName, String filter) throws IOException { JiraSession session = getSession(); if (session == null) { return ""; } List<Issue> issues = session.getIssuesWithFixVersion(projectKey, versionName, filter); if (issues == null) { return ""; } Map<String, Set<String>> releaseNotes = new HashMap<String, Set<String>>(); for (Issue issue : issues) { String key = issue.getKey(); String summary = issue.getSummary(); String status = issue.getStatus().getName(); String type = issue.getIssueType().getName(); Set<String> issueSet; if (!releaseNotes.containsKey(type)) { issueSet = new HashSet<String>(); releaseNotes.put(type, issueSet); } else { <START> issueSet = releaseNotes.get(type); <END> } issueSet.add(String.format(" - [%s] %s (%s)", key, summary, status)); } StringBuilder sb = new StringBuilder(); for (String type : releaseNotes.keySet()) { sb.append(String.format("# %s\n", type)); for (String issue : releaseNotes.get(type)) { sb.append(issue); sb.append("\n"); } } return sb.toString(); }</code><technical_language>This fixes issue. fallback UNKNOWN in case issueType is known... Also, this needs a test</technical_language>

Target:
public String getReleaseNotesForFixVersion(String projectKey, String versionName, String filter) throws IOException { JiraSession session = getSession(); if (session == null) { return ""; } List<Issue> issues = session.getIssuesWithFixVersion(projectKey, versionName, filter); if (issues == null) { return ""; } Map<String, Set<String>> releaseNotes = new HashMap<String, Set<String>>(); for (Issue issue : issues) { String key = issue.getKey(); String summary = issue.getSummary(); String status = issue.getStatus().getName(); String type = "UNKNOWN"; if (issue.getIssueType() != null && issue.getIssueType().getName() != null) { type = issue.getIssueType().getName(); } Set<String> issueSet; if (!releaseNotes.containsKey(type)) { issueSet = new HashSet<String>(); releaseNotes.put(type, issueSet); } else { issueSet = releaseNotes.get(type); } issueSet.add(String.format(" - [%s] %s (%s)", key, summary, status)); } StringBuilder sb = new StringBuilder(); for (String type : releaseNotes.keySet()) { sb.append(String.format("# %s\n", type)); for (String issue : releaseNotes.get(type)) { sb.append(issue); sb.append("\n"); } } return sb.toString(); }
Source:
<code>public void gotoExternalComponentSettings() { <START> activeSection = 3; <END> editorStatus.saveSelectedOption(displayerSettings.getUUID(), activeSection); initComponentEditor(); view.gotoExternalComponentSettings(externalComponentPropertiesEditor); }</code><technical_language>Consider creating a constant enum representing active section replace 3 (and others). improve readability of switch-case above</technical_language>

Target:
public void gotoExternalComponentSettings() { activeSection = EXTERNAL_COMPONENT_SECTION; editorStatus.saveSelectedOption(displayerSettings.getUUID(), activeSection); initComponentEditor(); view.gotoExternalComponentSettings(externalComponentPropertiesEditor); }