auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static FindPatientListener createFindPatientListener(String lastQuery, int searchId, FindPatientsSearchActivity caller) { try { <START> URI uri = new URI(null,null,null,lastQuery); <END> lastQuery = uri.toString().substring(1); }catch (Exception e){ e.printStackTrace(); } return new FindPatientListener(lastQuery, searchId, caller); }</code><technical_language>cleaner <LINK_0></technical_language>

Target:
public static FindPatientListener createFindPatientListener(String lastQuery, int searchId, FindPatientsSearchActivity caller) { try { lastQuery = URLEncoder.encode(lastQuery,"UTF-8").toString(); } catch (Exception exception) { mLogger.e(exception.toString()); } return new FindPatientListener(lastQuery, searchId, caller); }
Source:
<code>public String getinternal_drive_mapping() { int mapping = disk.getInternalDriveMapping(); <START> return (mapping != 0) ? Integer.toString(mapping) : null; <END> }</code><technical_language>change this</technical_language>

Target:
public String getinternal_drive_mapping() { return Integer.toString(disk.getInternalDriveMapping()); }
Source:
<code>public List<String> infixNotation() { final List<String> infix = new ArrayList<String>(); Tokenizer tokenizer = new Tokenizer(expression); while (tokenizer.hasNext()) { Token token = tokenizer.next(); StringBuilder sb = new StringBuilder(); sb.append("{") .append(token.type) .append(":") .append(token.surface) .append("}"); <START> infix.add(sb.toString()); <END> } return infix; }</code><technical_language>require a StringBuilder for simple concatenations, bytecode compiler JIT compiler optimize calls these: ~~~java String a = b + c + d + e; ~~~ compile to: ~~~ String a = new StringBuilder().append(b).append(c).append(d).append(e); ~~~ *require* a StringBuilder building Strings *over* a loop. For example: ~~~java StringBuilder string = new StringBuilder(); for (Item item in lotsOfItems) { string.append(item.toString()); } return string.toString(); ~~~ if do this normal String operations, memory of String copied iteration</technical_language>

Target:
public List<String> infixNotation() { final List<String> infix = new ArrayList<String>(); Tokenizer tokenizer = new Tokenizer(expression); while (tokenizer.hasNext()) { Token token = tokenizer.next(); String infixNotation = "{" + token.type + ":" + token.surface + "}"; infix.add(infixNotation); } return infix; }
Source:
<code><START> <T, R> Collector<T, ?, R> createCollectorFor(Class<R> type) { <END> for (CollectorFactory<?, ?, ?> factory : factories) { if (factory.accepts(type)) { return ((CollectorFactory<T, ?, R>) factory).newCollector(type); } } throw new IllegalStateException("No collector builder available for " + type.getName()); }</code><technical_language>I mirroring existing registries work, I if sense for return a nullable type Optional<Collector<...>> lookups done necessarily throwing exception. If so, a change done existing registries well</technical_language>

Target:
<T, R> Collector<T, ?, R> createCollectorFor(Class<R> type) { for (CollectorFactory<?, ?> factory : factories) { if (factory.accepts(type)) { return ((CollectorFactory<T, R>) factory).newCollector(type); } } throw new IllegalStateException("No collector builder available for " + type.getName()); }
Source:
<code>private void copyResources(String file) throws IOException { ClassLoader classLoader = getClass().getClassLoader(); <START> InputStream source = classLoader.getResourceAsStream("html/templates/" + file); <END> File destination = new File(targetDir + File.separator + file); Files.copy(source, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); }</code><technical_language>closing InputStream here</technical_language>

Target:
private void copyResources(String file) throws IOException { ClassLoader classLoader = getClass().getClassLoader(); try (InputStream source = classLoader.getResourceAsStream("html/templates/" + file)) { File destination = new File(targetDir + File.separator + file); Files.copy(source, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { log.error("Exception while copying resources", e); } }
Source:
<code>public void setField(GeolocationField field) { this.field = field; <START> if (this.field.isShowLabel()) { <END> if (labelTextView != null) { labelTextView.setText(this.field.getLabel()); labelTextView.setVisibility(VISIBLE); } } else { if (labelTextView != null) { labelTextView.setVisibility(GONE); } } refresh(); }</code><technical_language>if (labelTextView != null) { labelTextView.setVisibility(this.field.isShowLabel() ? VISIBLE : GONE); labelTextView.setText(this.field.getLabel()); }</technical_language>

Target:
public void setField(GeolocationField field) { this.field = field; if (labelTextView != null) { labelTextView.setVisibility(this.field.isShowLabel() ? VISIBLE : GONE); labelTextView.setText(this.field.getLabel()); } refresh(); }
Source:
<code>public static boolean isSourceOfReplication(Database db) { <START> if (db == null) { <END> LOG.warn("db object passed is null. isSourceOfReplication is returning false"); return false; } String replPolicyIds = getReplPolicyIdString(db); return replPolicyIds != null && !replPolicyIds.isEmpty(); }</code><technical_language>assert db != null</technical_language>

Target:
public static boolean isSourceOfReplication(Database db) { assert (db != null); String replPolicyIds = getReplPolicyIdString(db); return !StringUtils.isEmpty(replPolicyIds); }
Source:
<code>public IAtsInsertion createInsertion(ArtifactId programArtifact, JaxNewInsertion newInsertion) { Long uuid = newInsertion.getUuid(); if (uuid == null || uuid <= 0) { uuid = Lib.generateArtifactIdAsInt(); } AtsChangeSet changes = (AtsChangeSet) atsServer.getStoreService().createAtsChangeSet("Create new Insertion", atsServer.getUserService().getCurrentUser()); ArtifactReadable insertionArt = (ArtifactReadable) changes.createArtifact(AtsArtifactTypes.Insertion, newInsertion.getName(), GUID.create(), uuid); <START> <END> changes.add(insertionArt); changes.relate(programArtifact, AtsRelationTypes.ProgramToInsertion_Insertion, insertionArt); changes.execute(); return getInsertion(insertionArt); }</code><technical_language>Move add AtsChangeSet 201 205 un-necessary</technical_language>

Target:
public IAtsInsertion createInsertion(ArtifactId programArtifact, JaxNewInsertion newInsertion) { Long uuid = newInsertion.getUuid(); if (uuid == null || uuid <= 0) { uuid = Lib.generateArtifactIdAsInt(); } AtsChangeSet changes = (AtsChangeSet) atsServer.getStoreService().createAtsChangeSet("Create new Insertion", atsServer.getUserService().getCurrentUser()); ArtifactReadable insertionArt = (ArtifactReadable) changes.createArtifact(AtsArtifactTypes.Insertion, newInsertion.getName(), GUID.create(), uuid); changes.relate(programArtifact, AtsRelationTypes.ProgramToInsertion_Insertion, insertionArt); changes.execute(); return getInsertion(insertionArt); }
Source:
<code>protected void start(BundleContext bundleContext) throws ConfigurationException { ConfigProvider configProvider = DataHolder.getInstance().getConfigProvider(); if (configProvider.getConfigurationObject(IdPClientConstants.SP_AUTH_NAMESPACE) == null) { DataHolder.getInstance().setInterceptorEnabled(true); DataHolder.getInstance().setExcludeURLList(new ArrayList<>()); } else { IdPClientConfiguration idPClientConfiguration = configProvider. getConfigurationObject(IdPClientConfiguration.class); String enableInterceptor = idPClientConfiguration.getProperties() .getOrDefault(IdPClientConstants.ENABLE_INTERCEPTOR, "true"); String exclude = idPClientConfiguration.getProperties().get(IdPClientConstants.EXCLUDE_INTERCEPTOR); Boolean isInterceptorEnabled = Boolean.parseBoolean(enableInterceptor); DataHolder.getInstance().setInterceptorEnabled(isInterceptorEnabled); List<String> excludeURLList = new ArrayList<>(); if (exclude != null) { <START> excludeURLList = Arrays.stream(exclude.replaceAll("\\s*", "") <END> .split(",")).collect(Collectors.toList()); } DataHolder.getInstance().setExcludeURLList(excludeURLList); } }</code><technical_language>Instead of Streams, Arrays.asList() cleaner & shorter</technical_language>

Target:
protected void start(BundleContext bundleContext) throws ConfigurationException { ConfigProvider configProvider = DataHolder.getInstance().getConfigProvider(); if (configProvider.getConfigurationObject(IdPClientConstants.SP_AUTH_NAMESPACE) == null) { DataHolder.getInstance().setInterceptorEnabled(true); DataHolder.getInstance().setExcludeURLList(new ArrayList<>()); } else { IdPClientConfiguration idPClientConfiguration = configProvider. getConfigurationObject(IdPClientConfiguration.class); String enableInterceptor = idPClientConfiguration.getProperties() .getOrDefault(IdPClientConstants.ENABLE_INTERCEPTOR, "true"); String exclude = idPClientConfiguration.getProperties().get(IdPClientConstants.EXCLUDE_INTERCEPTOR); Boolean isInterceptorEnabled = Boolean.parseBoolean(enableInterceptor); DataHolder.getInstance().setInterceptorEnabled(isInterceptorEnabled); List<String> excludeURLList = new ArrayList<>(); if (exclude != null) { excludeURLList = Arrays.asList(exclude.replaceAll("\\s*", "").split(",")); } DataHolder.getInstance().setExcludeURLList(excludeURLList); } }
Source:
<code>private void performDownloads(final GoogleRobotCredentials credentials, final FilePath localDir, final DownloadSpec spec, final String version, final String resolvedPrefix) throws IOException { RepeatOperation<IOException> a = new RepeatOperation<IOException>() { private Queue<StorageObject> objects = new LinkedList<StorageObject>( spec.objects); Executor executor = module.newExecutor(); <START> ; <END> Storage service; public void initCredentials() throws IOException { service = module.getStorageService(credentials, version); } public boolean moreWork() { return !objects.isEmpty(); } public void act() throws IOException, InterruptedException, ExecutorException { StorageObject obj = objects.peek(); String addPath = StorageUtil .getStrippedFilename(obj.getName(), resolvedPrefix); FilePath localName = localDir.withSuffix("/" + addPath); performDownloadWithRetry(executor, service, obj, localName, module); objects.remove(); } }; try { RetryStorageOperation.performRequestWithReinitCredentials(a); } catch (ExecutorException e) { throw new IOException(Messages.Download_DownloadException(), e); } catch (InterruptedException e) { throw new IOException(Messages.Download_DownloadException(), e); } }</code><technical_language>Remove extra semicolon</technical_language>

Target:
private void performDownloads(final GoogleRobotCredentials credentials, final FilePath localDir, final DownloadSpec spec, final String version, final String resolvedPrefix) throws IOException { RepeatOperation<IOException> a = new RepeatOperation<IOException>() { private Queue<StorageObject> objects = new LinkedList<StorageObject>( spec.objects); Executor executor = module.newExecutor(); Storage service; public void initCredentials() throws IOException { service = module.getStorageService(credentials, version); } public boolean moreWork() { return !objects.isEmpty(); } public void act() throws IOException, InterruptedException, ExecutorException { StorageObject obj = objects.peek(); String addPath = StorageUtil .getStrippedFilename(obj.getName(), resolvedPrefix); FilePath localName = localDir.withSuffix("/" + addPath); performDownloadWithRetry(executor, service, obj, localName, module); objects.remove(); } }; try { RetryStorageOperation.performRequestWithReinitCredentials(a); } catch (ExecutorException e) { throw new IOException(Messages.Download_DownloadException(), e); } catch (InterruptedException e) { throw new IOException(Messages.Download_DownloadException(), e); } }
Source:
<code>public void updateMetrics(final Long vmId, final Long size, final Long virtualSize) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { SearchCriteria<UsageBackupVO> sc = this.createSearchCriteria(); sc.addAnd("vmId", SearchCriteria.Op.EQ, vmId); UsageBackupVO vo = findOneBy(sc); if (vo != null) { vo.setSize(size); vo.setProtectedSize(virtualSize); update(vo.getId(), vo); } } catch (final Exception e) { LOGGER.error("Error updating backup metrics: " + e.getMessage(), e); } finally { <START> txn.close(); <END> } }</code><technical_language>+1 explicitly close transaction. Transaction.execute() method is widely codebase, strange closing handled</technical_language>

Target:
public void updateMetrics(final Long vmId, final Long size, final Long virtualSize) { try (TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB)) { SearchCriteria<UsageBackupVO> sc = this.createSearchCriteria(); sc.addAnd("vmId", SearchCriteria.Op.EQ, vmId); UsageBackupVO vo = findOneBy(sc); if (vo != null) { vo.setSize(size); vo.setProtectedSize(virtualSize); update(vo.getId(), vo); } } catch (final Exception e) { LOGGER.error("Error updating backup metrics: " + e.getMessage(), e); } }
Source:
<code>private boolean hasEmptyLineBefore(DetailAST token) { boolean result = false; final int lineNo = token.getLineNo(); if (lineNo != 1) { final List<EnumSet<LineFlag>> flags = categorizeLines(); for (int i = lineNo - 2; i >= 0; i--) { final EnumSet<LineFlag> lineFlags = flags.get(i); if (!lineFlags.contains(LineFlag.COMMENT)) { if (lineFlags.contains(LineFlag.EMPTY)) { result = true; } <START> if (lineFlags.contains(LineFlag.CODE)) { <END> result = false; } break; } } } return result; }</code><technical_language>this else if</technical_language>

Target:
private boolean hasEmptyLineBefore(DetailAST token) { boolean result = false; final int lineNo = token.getLineNo(); if (lineNo != 1) { final List<EnumSet<LineFlag>> flags = categorizeLines(); for (int i = lineNo - 2; i >= 0; i--) { final EnumSet<LineFlag> lineFlags = flags.get(i); if (!lineFlags.contains(LineFlag.COMMENT)) { if (lineFlags.contains(LineFlag.EMPTY)) { result = true; break; } } } } return result; }
Source:
<code>private List<RuleEntry> getSortedEntries() { <START> List<RuleEntry> ruleEntries = new ArrayList<RuleEntry>(); <END> for (MethodRule rule : methodRules) { ruleEntries.add(new MethodRuleEntry(rule, orderValues.get(rule))); } for (TestRule rule : testRules) { ruleEntries.add(new TestRuleEntry(rule, orderValues.get(rule))); } Collections.sort(ruleEntries, ENTRY_COMPARATOR); return ruleEntries; }</code><technical_language>Nit: new ArrayList<RuleEntry>(methodRules.size() + testRules.size())</technical_language>

Target:
private List<RuleEntry> getSortedEntries() { List<RuleEntry> ruleEntries = new ArrayList<RuleEntry>( methodRules.size() + testRules.size()); for (MethodRule rule : methodRules) { ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_METHOD_RULE, orderValues.get(rule))); } for (TestRule rule : testRules) { ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_TEST_RULE, orderValues.get(rule))); } Collections.sort(ruleEntries, ENTRY_COMPARATOR); return ruleEntries; }
Source:
<code>public int compareTo(IntervalBase comparedInterval) { int res = getEnd().compareTo(comparedInterval.getEnd()); if (res == 0 && !this.equals(comparedInterval)) { res = -1; } <START> return res; <END> }</code><technical_language>Hm, is this solution semantically correct? assume IntervalBase a, b a != b. compareTo(a,b) = -1 compareTo(b, a) = -1 (and compareTo(b,a) = 1). I missing something</technical_language>

Target:
public int compareTo(IntervalBase comparedInterval) { int res = getEnd().compareTo(comparedInterval.getEnd()); if (res == 0 && !this.equals(comparedInterval)) { res = getStart().compareTo(comparedInterval.getStart()); if (res == 0) { res = getType().compareTo(comparedInterval.getType()) > 0 ? 1 : -1; } } return res; }
Source:
<code>public Session create() throws Exception { JSch jsch = new JSch(); session = jsch .getSession(loginCredentials.getUser(), hostAndPort.getHostText(), hostAndPort.getPortOrDefault(22)); if (sessionTimeout != 0) session.setTimeout(sessionTimeout); if (loginCredentials.getPrivateKey() == null) { session.setPassword(loginCredentials.getPassword()); } else if (JschSshClient.hasValidPrivateKey(loginCredentials)) { byte[] privateKey = loginCredentials.getPrivateKey().getBytes(); jsch.addIdentity(loginCredentials.getUser(), privateKey, null, emptyPassPhrase); } else { <START> Connector con = JschSshClient.getSSHAgentConnector(); <END> if(con != null ){ IdentityRepository irepo = new RemoteIdentityRepository(con); jsch.setIdentityRepository(irepo); } } java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); if (proxy.isPresent()) session.setProxy(proxy.get()); session.connect(connectTimeout); return session; }</code><technical_language>If for injectable factory/supplier above, inject here, too</technical_language>

Target:
public Session create() throws Exception { JSch jsch = new JSch(); session = jsch .getSession(loginCredentials.getUser(), hostAndPort.getHostText(), hostAndPort.getPortOrDefault(22)); if (sessionTimeout != 0) session.setTimeout(sessionTimeout); if (loginCredentials.getPrivateKey() == null) { session.setPassword(loginCredentials.getPassword()); } else if (loginCredentials.hasUnencryptedPrivateKey()) { byte[] privateKey = loginCredentials.getPrivateKey().getBytes(); jsch.addIdentity(loginCredentials.getUser(), privateKey, null, emptyPassPhrase); } else if (agentConnector.isPresent()) { JSch.setConfig("PreferredAuthentications", "publickey"); jsch.setIdentityRepository(new RemoteIdentityRepository(agentConnector.get())); } java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); if (proxy.isPresent()) session.setProxy(proxy.get()); session.connect(connectTimeout); return session; }
Source:
<code>private static Block asBlock(IBlock block) { Object internal = block.getDefinition().getInternal(); if (!(internal instanceof Block)) { CraftTweakerAPI.logError("Not a valid block: " + block); } <START> return (Block) internal; <END> }</code><technical_language>this throw a ClassCastException if condition for logError is met? return null in instanceof Check</technical_language>

Target:
private static Block asBlock(IBlock block) { Object internal = block.getDefinition().getInternal(); if (!(internal instanceof Block)) { CraftTweakerAPI.logError("Not a valid block: " + block); return null; } return (Block) internal; }
Source:
<code>public boolean compareWithOther(Feed other) { if (super.compareWithOther(other)) { return true; } if (other.imageUrl != null) { if (imageUrl == null || !TextUtils.equals(imageUrl, other.imageUrl)) { return true; } } if (!TextUtils.equals(feedTitle, other.feedTitle)) { return true; } if (other.feedIdentifier != null) { if (feedIdentifier == null || !feedIdentifier.equals(other.feedIdentifier)) { return true; } } if (other.link != null) { if (link == null || !link.equals(other.link)) { return true; } } if (other.description != null) { if (description == null || !description.equals(other.description)) { return true; } } if (other.language != null) { if (language == null || !language.equals(other.language)) { return true; } } if (other.author != null) { if (author == null || !author.equals(other.author)) { return true; } } if (other.paymentLink != null) { if (paymentLink == null || !paymentLink.equals(other.paymentLink)) { return true; } } if (other.isPaged() && !this.isPaged()) { return true; } <START> return !TextUtils.equals(other.getNextPageLink(), this.getNextPageLink()); <END> }</code><technical_language>I this is harder read. breaks symmetry of items compared nextPageLink a special case. for other compare functions</technical_language>

Target:
public boolean compareWithOther(Feed other) { if (super.compareWithOther(other)) { return true; } if (other.imageUrl != null) { if (imageUrl == null || !TextUtils.equals(imageUrl, other.imageUrl)) { return true; } } if (!TextUtils.equals(feedTitle, other.feedTitle)) { return true; } if (other.feedIdentifier != null) { if (feedIdentifier == null || !feedIdentifier.equals(other.feedIdentifier)) { return true; } } if (other.link != null) { if (link == null || !link.equals(other.link)) { return true; } } if (other.description != null) { if (description == null || !description.equals(other.description)) { return true; } } if (other.language != null) { if (language == null || !language.equals(other.language)) { return true; } } if (other.author != null) { if (author == null || !author.equals(other.author)) { return true; } } if (other.paymentLink != null) { if (paymentLink == null || !paymentLink.equals(other.paymentLink)) { return true; } } if (other.isPaged() && !this.isPaged()) { return true; } if (!TextUtils.equals(other.getNextPageLink(), this.getNextPageLink())) { return true; } return false; }
Source:
<code>public long calculateRelativeIndex(int index) { <START> if (CHECK_BOUNDS && index > capacity) { <END> throw new IndexOutOfBoundsException( "index " + index + " is out of bounds, capacity is " + capacity); } long relativeIndex; long mask; if (index >= twoRelativeIndex) { relativeIndex = twoReadIndex + (index - oneReadableBytes); mask = TWO_MASK; } else { relativeIndex = oneReadIndex + index; mask = ONE_MASK; } return relativeIndex | mask; }</code><technical_language>able disable bounds checking - this a property. I a property netty for bounds checking - want one</technical_language>

Target:
long calculateRelativeIndex(int index) { checkIndex(index, 0); long relativeIndex; long mask; if (index >= twoRelativeIndex) { relativeIndex = twoReadIndex + (index - oneReadableBytes); mask = TWO_MASK; } else { relativeIndex = oneReadIndex + index; mask = ONE_MASK; } return relativeIndex | mask; }
Source:
<code>public static IPSecEncryptionAlgorithm forValue(String v) { return <START> valueOf(IPSecSiteConnection.convertFromIpsecString(v)); <END> }</code><technical_language>this method name is strange. Implies some sort of cast is place. normalizeIpsecString</technical_language>

Target:
public static IPSecEncryptionAlgorithm forValue(String v) { return valueOf(IPSecSiteConnection.normalizeIpSecEnumString(v)); }
Source:
<code>public void doNotKillProcessWithCookie() throws Exception { <START> ProcessTree.enabled = true; <END> SpawnBuilder spawner = new SpawnBuilder(); FreeStyleProject p = j.createFreeStyleProject(); p.getBuildersList().add(spawner); try { j.buildAndAssertSuccess(p); assertTrue("Process should be running", spawner.proc.isAlive()); } finally { spawner.proc.kill(); assertTrue("Process should be dead", !spawner.proc.isAlive()); } }</code><technical_language>fail windows nohup is - (or pass for wrong reason)</technical_language>

Target:
public void doNotKillProcessWithCookie() throws Exception { Assume.assumeFalse("This test does not involve windows", Functions.isWindows()); ProcessTree.enabled = true; SpawnBuilder spawner = new SpawnBuilder(); FreeStyleProject p = j.createFreeStyleProject(); p.getBuildersList().add(spawner); try { j.buildAndAssertSuccess(p); assertTrue("Process should be running", spawner.proc.isAlive()); } finally { spawner.proc.kill(); assertTrue("Process should be dead", !spawner.proc.isAlive()); } }
Source:
<code>public KeyPair getKeyPair() throws NoSuchAlgorithmException { if (keyPairs.isEmpty()) { synchronized (keyPairs) { keyPairs.notify(); } } try { KeyPair keyPair = null; if (!future.isDone()) { keyPair = keyPairs.poll(loopTimeout * 3, timeUnit); if (keyPair == null) { LOGGER.warn("Background thread is still working but there is nothing in the queue."); keyPair = generateAndAddKeyPairs(); } } else { <START> LOGGER.error("Background thread is dead so we generate key by ourselves."); <END> keyPair = generateAndAddKeyPairs(); } return keyPair; } catch (InterruptedException e) { LOGGER.error(e); return generateAndAddKeyPairs(); } }</code><technical_language>I change 'by ourselves' 'synchronously'</technical_language>

Target:
public KeyPair getKeyPair() throws NoSuchAlgorithmException { KeyPair keyPair = keyPairs.poll(); if (keyPair == null) { LOGGER.warn("Key pair queue is empty, generating a key pair now"); keyPair = generateAndAddKeyPairs(); } return keyPair; }
Source:
<code>public void shouldConnectorMatchWithConnectorDefinition() throws IOException { processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_IMAGE_CONNECTORS_PROCESS) .withVariable("input-variable-name-1", "input-variable-name-1") .withVariable("input-variable-name-2", "input-variable-name-2") .withVariable("expectedKey", true) <START> .build()); <END> }</code><technical_language>I suggest a process a user task connector check variable updates connector execution</technical_language>

Target:
public void shouldConnectorMatchWithConnectorDefinition() { processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_IMAGE_CONNECTORS_PROCESS) .withVariable("input-variable-name-1", "input-variable-name-1") .withVariable("input-variable-name-2", "input-variable-name-2") .withVariable("expectedKey", true) .build()); }
Source:
<code>public boolean deletePersonname() { if (selectedPersonname != null) { if (CollectionUtils.isNotEmpty(personnameList) && personnameList.size() > 1) { <START> LOG.info("deleting-Personname"); <END> return loadTestDataService.deletePersonname(selectedPersonname); } else { addPatientErrorMessages("Patient-personname cannot be empty: fail to delete the last record"); } } else { addPatientErrorMessages("Personname have to be select to be deleted"); } return false; }</code><technical_language>Refactor save code GenericDAO remove redundant logic</technical_language>

Target:
public boolean deletePersonname() { boolean result = false; if (selectedPersonname != null) { if (CollectionUtils.isNotEmpty(personnameList) && personnameList.size() > 1) { LOG.info("deleting-Personname"); result = loadTestDataService.deletePersonname(selectedPersonname); } else { addPatientErrorMessages("Patient-personname cannot be empty: fail to delete the last record"); } } else { addPatientErrorMessages(msgForSelectDelete("additional-name")); } return result; }
Source:
<code>private int updateStopTimesForPatternStop(ObjectNode patternStop, int previousTravelTime) throws SQLException { String sql = String.format( "update %s.stop_times st set arrival_time = ?, departure_time = ? from %s.trips t " + "where st.trip_id = t.trip_id AND t.%s = ? AND st.%s = ?", tablePrefix, tablePrefix, "pattern_id", <START> "stop_sequence" <END> ); PreparedStatement statement = connection.prepareStatement(sql); int oneBasedIndex = 1; int travelTime = patternStop.get("default_travel_time").asInt(); int arrivalTime = previousTravelTime + travelTime; statement.setInt(oneBasedIndex++, arrivalTime); int dwellTime = patternStop.get("default_dwell_time").asInt(); statement.setInt(oneBasedIndex++, arrivalTime + dwellTime); statement.setString(oneBasedIndex++, patternStop.get("pattern_id").asText()); statement.setInt(oneBasedIndex++, patternStop.get("stop_sequence").asInt()); LOG.debug(statement.toString()); int entitiesUpdated = statement.executeUpdate(); LOG.debug("{} stop_time arrivals/departures updated", entitiesUpdated); return travelTime + dwellTime; }</code><technical_language>hardcoded strings, included in base string</technical_language>

Target:
private int updateStopTimesForPatternStop(ObjectNode patternStop, int previousTravelTime) throws SQLException { String sql = String.format( "update %s.stop_times st set arrival_time = ?, departure_time = ? from %s.trips t " + "where st.trip_id = t.trip_id AND t.pattern_id = ? AND st.stop_sequence = ?", tablePrefix, tablePrefix ); PreparedStatement statement = connection.prepareStatement(sql); int oneBasedIndex = 1; int travelTime = patternStop.get("default_travel_time").asInt(); int arrivalTime = previousTravelTime + travelTime; statement.setInt(oneBasedIndex++, arrivalTime); int dwellTime = patternStop.get("default_dwell_time").asInt(); statement.setInt(oneBasedIndex++, arrivalTime + dwellTime); statement.setString(oneBasedIndex++, patternStop.get("pattern_id").asText()); statement.setInt(oneBasedIndex++, patternStop.get("stop_sequence").asInt()); LOG.debug(statement.toString()); int entitiesUpdated = statement.executeUpdate(); LOG.debug("{} stop_time arrivals/departures updated", entitiesUpdated); return travelTime + dwellTime; }
Source:
<code>EnumerableValues(RelOptCluster cluster, RelDataType rowType, <START> ImmutableList<ImmutableList<RexLiteral>> tuples, RelTraitSet traitSet) { <END> super(cluster, rowType, tuples, traitSet); }</code><technical_language>create instead of new directly</technical_language>

Target:
private EnumerableValues(RelOptCluster cluster, RelDataType rowType, ImmutableList<ImmutableList<RexLiteral>> tuples, RelTraitSet traitSet) { super(cluster, rowType, tuples, traitSet); }
Source:
<code>public Statement apply(Statement base, Description description) { <START> return rule.apply(base, createFrameworkMethod(description), description.getTestClass()); <END> }</code><technical_language>object passed parameter of MethodRule.apply() needs test instance, test class. get is caller pass in test instance TestRuleAdapter constructor</technical_language>

Target:
public Statement apply(Statement base, Description description) { try { String methodName = description.getMethodName(); Method method = testObject.getClass().getDeclaredMethod(methodName); return rule.apply(base, new FrameworkMethod(method), testObject); } catch (final NoSuchMethodException e) { return new Statement() { @Override public void evaluate() throws Throwable { throw e; } }; } }
Source:
<code>@Test public void testTableFunctionInSelectWithUnion() { sql("select * from (" <START> + "select a.deptno, table_func(a.deptno) as (f0, f1)" <END> + " from (select * from dept) a " + " union all " + " select 1, table_func(b.deptno) as (f0, f1) from dept b" + ")") .conformance(SqlConformance.HIVE) .ok(); }</code><technical_language>is a limitations in Hive[1].Other expressions allowed in SELECT. other expressions allowed in SELECT SELECT pageid, explode(adid_list) myCol... is supported [1] [<LINK_1>](<LINK_0></technical_language>

Target:
@Test public void testTableFunctionInSelectWithUnion() { sql("select * from (" + "select a.deptno, table_func(a.deptno) as (f0, f1)" + " from (select * from dept) a " + " union all " + " select 1, table_func(b.deptno) as (f0, f1) from dept b" + ")") .conformance(SqlConformanceEnum.HIVE) .ok(); }
Source:
<code>public StaticSelector(Optional<Pattern> userRegex, Optional<Pattern> sourceRegex, Optional<List<String>> clientTags, Optional<String> queryType, ResourceGroupIdTemplate group) { this.userRegex = requireNonNull(userRegex, "userRegex is null"); this.sourceRegex = requireNonNull(sourceRegex, "sourceRegex is null"); <START> this.clientTags = requireNonNull(clientTags, "clientTags is null").map(ImmutableSet::copyOf).orElse(ImmutableSet.of()); <END> this.queryType = requireNonNull(queryType, "queryType is null"); this.group = requireNonNull(group, "group is null"); }</code><technical_language>nit: I find this easier read requireNonNull(clientTags, "clientTags is null"); this.clientTags = ImmutableSet.copyOf(clientTags.orElse(ImmutableList.of()));</technical_language>

Target:
public StaticSelector(Optional<Pattern> userRegex, Optional<Pattern> sourceRegex, Optional<List<String>> clientTags, Optional<String> queryType, ResourceGroupIdTemplate group) { this.userRegex = requireNonNull(userRegex, "userRegex is null"); this.sourceRegex = requireNonNull(sourceRegex, "sourceRegex is null"); requireNonNull(clientTags, "clientTags is null"); this.clientTags = ImmutableSet.copyOf(clientTags.orElse(ImmutableList.of())); this.queryType = requireNonNull(queryType, "queryType is null"); this.group = requireNonNull(group, "group is null"); }
Source:
<code>public OAuth2TokenValidatorResult validate(Jwt jwt) { Assert.notNull(jwt, "jwt cannot be null"); Instant expiry = jwt.getExpiresAt(); if (expiry != null) { if (Instant.now(this.clock).minus(clockSkew).isAfter(expiry)) { <START> if (logger.isDebugEnabled()){ <END> logger.debug("Failed to validate OAuth2 token claim. Token has expired"); } OAuth2Error error = new OAuth2Error( OAuth2ErrorCodes.INVALID_REQUEST, String.format("Jwt expired at %s", jwt.getExpiresAt()), "<LINK_0>"); return OAuth2TokenValidatorResult.failure(error); } } Instant notBefore = jwt.getNotBefore(); if (notBefore != null) { if (Instant.now(this.clock).plus(clockSkew).isBefore(notBefore)) { if (logger.isDebugEnabled()){ logger.debug("Failed to validate OAuth2 token claim. Token should not be used before: " + isoDateTime(notBefore)); } OAuth2Error error = new OAuth2Error( OAuth2ErrorCodes.INVALID_REQUEST, String.format("Jwt used before %s", jwt.getNotBefore()), "<LINK_0>"); return OAuth2TokenValidatorResult.failure(error); } } return OAuth2TokenValidatorResult.success(); }</code><technical_language>I point is potential collect multiple errors is exception message, logging in places information gap. error message debug message align? For example, like: java String reason = String.format("Jwt expired %s", isoDateTime(jwt.getExpiresAt())); if (logger.isDebugEnabled()) { logger.debug("Failed validate " + reason); } OAuth2Error error = new OAuth2Error(..., reason, ...);</technical_language>

Target:
public OAuth2TokenValidatorResult validate(Jwt jwt) { Assert.notNull(jwt, "jwt cannot be null"); Instant expiry = jwt.getExpiresAt(); if (expiry != null) { if (Instant.now(this.clock).minus(clockSkew).isAfter(expiry)) { final OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt expired at %s", jwt.getExpiresAt())); return OAuth2TokenValidatorResult.failure(oAuth2Error); } } Instant notBefore = jwt.getNotBefore(); if (notBefore != null) { if (Instant.now(this.clock).plus(clockSkew).isBefore(notBefore)) { final OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt used before %s", jwt.getNotBefore())); return OAuth2TokenValidatorResult.failure(oAuth2Error); } } return OAuth2TokenValidatorResult.success(); }
Source:
<code>public static void main(String[] args){ <START> try { createTestSAM(); } catch(IOException e) { ; } <END> }</code><technical_language>is this needed</technical_language>

Target:
public static void main(String[] args) { try { createTestSAM("TestSam"); } catch(IOException e) { ; } }
Source:
<code>String process(int requestCode, int resultCode, Intent i) { trace(this, "process() :: requestCode=%s", requestCode); switch(requestCode) { case GRAB_MRDT_PHOTO: { try { byte[] data = i.getByteArrayExtra("data"); String base64data = Base64.encodeToString(data, Base64.NO_WRAP); long timeTaken = i.getLongExtra("timeTaken", 0); <START> return safeFormat("angular.element(document.body).injector().get('AndroidApi').v1.mrdtResponse('\"%s|%s\"')", String.valueOf(timeTaken), base64data); <END> } catch(Exception ex) { warn(ex, "Problem serialising mrdt image."); return safeFormat("console.log('Problem serialising mrdt image: %s')", ex); } } default: throw new RuntimeException("Bad request type: " + requestCode); } }</code><technical_language>worried changing data contract android webapp in a need release apps time. a get('AndroidApi').v2 this change compatible</technical_language>

Target:
String process(int requestCode, int resultCode, Intent i) { trace(this, "process() :: requestCode=%s", requestCode); switch(requestCode) { case GRAB_MRDT_PHOTO: { try { byte[] data = i.getByteArrayExtra("data"); String base64data = Base64.encodeToString(data, Base64.NO_WRAP); long timeTaken = i.getLongExtra("timeTaken", 0); String javaScript = "var api = angular.element(document.body).injector().get('AndroidApi');" + "if (api.v1.mrdtTimeTakenResponse) {" + " api.v1.mrdtTimeTakenResponse('\"%s\"');" + "}" + "api.v1.mrdtResponse('\"%s\"');"; return safeFormat(javaScript, String.valueOf(timeTaken), base64data); } catch(Exception ex) { warn(ex, "Problem serialising mrdt image."); return safeFormat("console.log('Problem serialising mrdt image: %s')", ex); } } default: throw new RuntimeException("Bad request type: " + requestCode); } }
Source:
<code>public static String mongoGetRegistrationKey(final Authenticator authenticator, final DB database, final String authId, final String bankProblemId) throws AuthenticationException, DatabaseAccessException { <START> final DBCollection collection = database.getCollection(getCollectionFromType(School.ItemType.BANK_PROBLEM)); <END> final DBObject cursor = collection.findOne(convertStringToObjectId(bankProblemId)); if (cursor == null) { throw new DatabaseAccessException("BankProblem was not found with the following ID " + bankProblemId); } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckIsRegistrationRequired(true) .setCheckingAdmin(true) .setCheckIsPublished(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, bankProblemId.trim(), authId, 0, authType); if ((!responder.isRegistrationRequired() && responder.isItemPublished()) || responder.hasTeacherPermission()) { return (String) cursor.get(DatabaseStringConstants.REGISTRATION_KEY); } return null; }</code><technical_language>please change name problemBank problemBankCollection problemCollwction</technical_language>

Target:
public static String mongoGetRegistrationKey(final Authenticator authenticator, final DB database, final String authId, final String bankProblemId) throws AuthenticationException, DatabaseAccessException { final DBCollection bankProblemCollection = database.getCollection(getCollectionFromType(School.ItemType.BANK_PROBLEM)); final DBObject cursor = bankProblemCollection.findOne(convertStringToObjectId(bankProblemId)); if (cursor == null) { throw new DatabaseAccessException("BankProblem was not found with the following ID " + bankProblemId); } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckIsRegistrationRequired(true) .setCheckingAdmin(true) .setCheckIsPublished(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, bankProblemId.trim(), authId, 0, authType); if ((!responder.isRegistrationRequired() && responder.isItemPublished()) || responder.hasTeacherPermission()) { return (String) cursor.get(DatabaseStringConstants.REGISTRATION_KEY); } return null; }
Source:
<code>public List<SAMValidationError> isValid(final boolean firstOnly) { if (!initializedFields.contains(LazyField.REFERENCE_NAME)) { getReferenceName(); } if (!initializedFields.contains(LazyField.MATE_REFERENCE_NAME)) { getMateReferenceName(); } getFlags(); <START> return super.isValid(firstOnly); <END> }</code><technical_language>currently written, isValid() fully validate data in record, some fields (like base qualities, etc.) lazily initialized yet</technical_language>

Target:
public List<SAMValidationError> isValid(final boolean firstOnly) { loadFields(); getFlags(); getBinaryAttributes(); return super.isValid(firstOnly); }
Source:
<code>private void updateOrderLabel() { ECTransition transition = getModel(); if (null != transition.getSource()) { if (1 < transition.getSource().getOutTransitions().size()) { int i = 1 + transition.getSource().getOutTransitions().indexOf(transition); getConnectionFigure().setTransitionOder(Integer.toString(i)); } else { <START> getConnectionFigure().setTransitionOder(""); <END> } } }</code><technical_language>typo</technical_language>

Target:
private void updateOrderLabel() { ECTransition transition = getModel(); if (null != transition.getSource()) { if (1 < transition.getSource().getOutTransitions().size()) { int i = 1 + transition.getSource().getOutTransitions().indexOf(transition); getConnectionFigure().setTransitionOrder(Integer.toString(i)); } else { getConnectionFigure().setTransitionOrder(""); } } }
Source:
<code>public void expunge(List<Long> knownDeletedUids) throws MessagingException { if (knownDeletedUids == null || knownDeletedUids.isEmpty()) { return; } open(OPEN_MODE_RW); checkOpen(); try { if (connection.isUidPlusCapable()) { UidExpungeCommand uidExpungeCommand = new UidExpungeCommand.Builder() .idSet(knownDeletedUids) .build(); uidExpungeCommand.execute(connection, this); } else { <START> UidSearchCommand searchCommand = new UidSearchCommand.Builder() <END> .requiredFlags(Collections.singleton(Flag.DELETED)) .useUids(true, true) .idSet(knownDeletedUids) .build(); List<Long> unknownDeletedUids = searchCommand.execute(connection, this).getNumbers(); setFlagsInternal(unknownDeletedUids, Collections.singleton(Flag.DELETED), false); executeSimpleCommand("EXPUNGE"); setFlagsInternal(unknownDeletedUids, Collections.singleton(Flag.DELETED), true); } } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } }</code><technical_language>I this warrants method. also, a reference rfc nice, this type of fallback method a spec is common</technical_language>

Target:
public void expunge(List<Long> knownDeletedUids) throws MessagingException { if (knownDeletedUids == null || knownDeletedUids.isEmpty()) { return; } open(OPEN_MODE_RW); checkOpen(); try { if (connection.isUidPlusCapable()) { UidExpungeCommand uidExpungeCommand = new UidExpungeCommand.Builder() .idSet(knownDeletedUids) .build(); uidExpungeCommand.execute(connection, this); } else { expungeWithoutUidPlus(knownDeletedUids); } } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } }
Source:
<code>public void executeCommand() { if (getParameters().getTopImage().getSize() == getParameters().getBaseImage().getSize()) { log.debug("No image size update required"); setSucceeded(true); setCommandStatus(CommandStatus.SUCCEEDED); return; } if (isBaseRawBlock()) { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = extendImageSize(); if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getParameters().setVdsmTaskIds(new ArrayList<Guid>()); Guid result = createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId()); getReturnValue().getInternalVdsmTaskIdList().add(result); getReturnValue().getVdsmTaskIdList().add(result); getParameters().getVdsmTaskIds().add(result); setSucceeded(vdsReturnValue.getSucceeded()); persistCommand(getParameters().getParentCommand(), true); log.info("Successfully started task to extend base image size in preparation for live merge"); } else { log.error("Failed to extend base image for live merge"); setSucceeded(false); setCommandStatus(CommandStatus.FAILED); } } else { <START> updateSizeInDb(); <END> setSucceeded(true); setCommandStatus(CommandStatus.SUCCEEDED); } }</code><technical_language>I completely understood this part, elaborate</technical_language>

Target:
public void executeCommand() { if (getParameters().getTopImage().getSize() == getParameters().getBaseImage().getSize()) { log.debug("No image size update required"); setSucceeded(true); setCommandStatus(CommandStatus.SUCCEEDED); return; } if (isBaseRawBlock()) { extendImageSize(); } else { updateSizeInDb(); setCommandStatus(CommandStatus.SUCCEEDED); } setSucceeded(true); }
Source:
<code>public Map<String, Node> get(String uri) { GetResponse response; Map<String, Node> result = new HashMap<>(); if(uri != null) { response = client.prepareGet(INDEX_NAME, docDef.getEntityField(), uri).get(); if(response != null && !response.isSourceEmpty()) { String entityField = response.getId(); Node entity = NodeFactory.createURI(entityField) ; result.put(docDef.getEntityField(), entity); for (String field: docDef.fields()) { GetField fieldResponse = response.getField(field); if(fieldResponse == null || fieldResponse.getValue() == null) { continue; } if(fieldResponse instanceof List<?>) { continue; } String fieldValue = (String)fieldResponse.getValue(); <START> Node fieldNode = NodeFactoryExtra.createLiteralNode(fieldValue, null, null); <END> result.put(field, fieldNode); } } } return result; }</code><technical_language>return language-tagged values here</technical_language>

Target:
public Map<String, Node> get(String uri) { GetResponse response; Map<String, Node> result = new HashMap<>(); if(uri != null) { response = client.prepareGet(indexName, docDef.getEntityField(), uri).get(); if(response != null && !response.isSourceEmpty()) { String entityField = response.getId(); Node entity = NodeFactory.createURI(entityField) ; result.put(docDef.getEntityField(), entity); Map<String, Object> source = response.getSource(); for (String field: docDef.fields()) { Object fieldResponse = source.get(field); if(fieldResponse == null) { continue; } else if(fieldResponse instanceof List<?>) { List<?> responseList = (List<?>)fieldResponse; if(responseList != null && responseList.size() > 0) { String fieldValue = (String)responseList.get(0); Node fieldNode = NodeFactoryExtra.createLiteralNode(fieldValue, null, null); result.put(field, fieldNode); } } } } } return result; }
Source:
<code>public void statusUpdate(SchedulerDriver driver, TaskStatus status) { switch (status.getState()) { case TASK_STAGING: case TASK_STARTING: LOG.debug("Received status update: {}", taskStatusToString(status)); break; case TASK_RUNNING: LOG.info("Received status update: {}", taskStatusToString(status)); break; case TASK_FINISHED: case TASK_FAILED: case TASK_KILLED: case TASK_LOST: case TASK_ERROR: <START> LOG.info("Received status update: {}", taskStatusToString(status)); <END> break; default: LOG.warn("Received unrecognized status update: {}", taskStatusToString(status)); break; } }</code><technical_language>action for terminal cases is for TASK_RUNNING; combine cases. i.e., Line 97 is line 104, is longer this special taskTerminated method invoked for terminal cases</technical_language>

Target:
public void statusUpdate(SchedulerDriver driver, TaskStatus status) { String msg = String.format("Received status update: %s", taskStatusToString(status)); switch (status.getState()) { case TASK_STAGING: case TASK_STARTING: LOG.debug(msg); break; case TASK_RUNNING: LOG.info(msg); break; case TASK_FINISHED: case TASK_FAILED: case TASK_KILLED: case TASK_LOST: case TASK_ERROR: LOG.info(msg); break; default: LOG.warn("Received unrecognized status update: {}", taskStatusToString(status)); break; } }
Source:
<code><START> public void testAdd() throws ArrayIndexOutOfBoundsException { <END> SizeLimitedVector slv = new SizeLimitedVector(10); slv.add("testString"); assertEquals(slv.getMaxSize(), 10); assertEquals(slv.get(0), "testString"); }</code><technical_language>dont declare this RuntimeException do you? of functions throwing exceptions</technical_language>

Target:
public void testAdd() { SizeLimitedVector slv = new SizeLimitedVector(10); slv.add("testString"); assertEquals(slv.getMaxSize(), 10); assertEquals(slv.get(0), "testString"); }
Source:
<code>private boolean parentClassImplementsEquals(ClassTree tree) { Tree superClass = tree.superClass(); if (superClass != null) { <START> TypeSymbol superClassSymbol = ((AbstractTypedTree) superClass).getSymbolType().getSymbol(); <END> while (!superClassSymbol.getType().is("java.lang.Object")) { if (hasEqualsMethod(superClassSymbol)) { return true; } Type superClassType = superClassSymbol.getSuperclass(); if (superClassType == null) { break; } superClassSymbol = superClassType.getSymbol(); } } return false; }</code><technical_language>Minor detail check type assign a TypeSymbol variable</technical_language>

Target:
private boolean parentClassImplementsEquals(ClassTree tree) { Tree superClass = tree.superClass(); if (superClass != null) { Type superClassType = ((AbstractTypedTree) superClass).getSymbolType(); while (!superClassType.getSymbol().getType().isTagged(Type.UNKNOWN) && !superClassType.is("java.lang.Object")) { TypeSymbol superClassSymbol = superClassType.getSymbol(); if (hasEqualsMethod(superClassSymbol)) { return true; } superClassType = superClassSymbol.getSuperclass(); } } return false; }
Source:
<code>public static<T> T loadFromConf(Configuration conf, String dataKey) throws IOException { String classKey = dataKey + "._class"; String className = conf.get(classKey); try { return (T) DefaultStringifier.load(conf, dataKey, ClassLoadingUtils.loadClass(className)); <START> } catch (Exception ex) { <END> throw new IOException(ex); } }</code><technical_language>This throw a more specific exception. DefaultStringifier.load() throws IOException. this aligned latest discussion @alfonsonishikawa @nishadi wrapping exceptions GoraExceptions. is input this guys</technical_language>

Target:
public static<T> T loadFromConf(Configuration conf, String dataKey) throws IOException { String classKey = dataKey + "._class"; String className = conf.get(classKey); try { return (T) DefaultStringifier.load(conf, dataKey, ClassLoadingUtils.loadClass(className)); } catch (IOException | ClassNotFoundException ex) { throw new IOException(ex); } }