auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ObjectCreator<T> createCreator(List<String> columnNames, ResultSetMetaData metadata, StatementContext ctx) { final int length; try { length = metadata.getColumnCount(); } catch (SQLException e) { throw new ResultSetException("Could not get column count", e, ctx); } if (length != constructor.getParameterCount()) { throw new IllegalStateException(length + " columns in result set, but constructor takes " + constructor.getParameterCount()); } final int[] columnMap = new int[length]; final ColumnMapper<?>[] mappers = new ColumnMapper<?>[length]; for (int i = 0; i < length; i++) { <START> final Type type = constructor.getGenericParameterTypes()[i]; <END> final int paramIndex = parameterIndexForColumn(columnNames.get(i)); if (mappers[paramIndex] != null) { throw new IllegalArgumentException("Column named " + columnNames.get(i) + " maps to multiple parameters"); } mappers[paramIndex] = ctx.findColumnMapperFor(type).orElseThrow(() -> new IllegalArgumentException("Could not find column mapper for type '" + type + "' of parameter for constructor " + constructor)); columnMap[i] = paramIndex; } return rs -> { final Object[] params = new Object[length]; for (int i = 0; i < length; i++) { params[columnMap[i]] = mappers[i].map(rs, i + 1, ctx); } try { return constructor.newInstance(params); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new RuntimeException(e); } }; }</code><technical_language>Need ~~reconcile~~ resolve parameter type in context of T</technical_language>

Target:
private ObjectCreator<T> createCreator(List<String> columnNames, ResultSetMetaData metadata, StatementContext ctx) { final int length = columnNames.size(); if (length != constructor.getParameterCount()) { throw new IllegalStateException(length + " columns in result set, but constructor takes " + constructor.getParameterCount()); } final int[] columnMap = new int[length]; final ColumnMapper<?>[] mappers = new ColumnMapper<?>[length]; for (int i = 0; i < length; i++) { final Type type = constructor.getGenericParameterTypes()[i]; final int paramIndex = parameterIndexForColumn(columnNames.get(i)); if (mappers[paramIndex] != null) { throw new IllegalArgumentException("Column named " + columnNames.get(i) + " maps to multiple parameters"); } mappers[paramIndex] = ctx.findColumnMapperFor(type).orElseThrow(() -> new IllegalArgumentException("Could not find column mapper for type '" + type + "' of parameter for constructor " + constructor)); columnMap[i] = paramIndex; } return rs -> { final Object[] params = new Object[length]; for (int i = 0; i < length; i++) { params[columnMap[i]] = mappers[i].map(rs, i + 1, ctx); } try { return constructor.newInstance(params); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new RuntimeException(e); } }; }
Source:
<code>public JSONObject getJSONObject() { TextFile df = getDataFile(); if(df.exists()) { long start = System.nanoTime(); try { JSONObject o = JSONObject.fromObject(df.read()); <START> LOGGER.info(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0)); <END> return o; } catch (JSONException | IOException e) { LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); df.delete(); return null; } } else { return null; } }</code><technical_language>INFO? Really? Is this notable</technical_language>

Target:
public JSONObject getJSONObject() { TextFile df = getDataFile(); if(df.exists()) { long start = System.nanoTime(); try { JSONObject o = JSONObject.fromObject(df.read()); LOGGER.fine(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0)); return o; } catch (JSONException | IOException e) { LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); df.delete(); return null; } } else { return null; } }
Source:
<code>private Producer<String, String> takeUnderLock(final boolean canCreate) { final Lock lock = canCreate ? rwLock.writeLock() : rwLock.readLock(); lock.lock(); try { if (null != activeProducer) { useCountMetric.inc(); useCount.get(activeProducer).incrementAndGet(); return activeProducer; } else if (canCreate) { activeProducer = new KafkaProducer<>(kafkaLocationManager.getKafkaProducerProperties()); useCountMetric.inc(); useCount.put(activeProducer, new AtomicInteger(1)); LOG.info("New producer instance created: " + activeProducer); return activeProducer; } else { <START> return null; <END> } } finally { lock.unlock(); } }</code><technical_language>I understand this branch. create in this case? this is do of this method. call takeUnderLock(false) if returns null call takeUnderLock(true)</technical_language>

Target:
private Producer<String, String> takeUnderLock(final boolean canCreate) { final Lock lock = canCreate ? rwLock.writeLock() : rwLock.readLock(); lock.lock(); try { if (null != activeProducer) { useCountMetric.inc(); useCount.get(activeProducer).incrementAndGet(); return activeProducer; } else if (canCreate) { activeProducer = createProducerInstance(); useCountMetric.inc(); useCount.put(activeProducer, new AtomicInteger(1)); LOG.info("New producer instance created: " + activeProducer); return activeProducer; } else { return null; } } finally { lock.unlock(); } }
Source:
<code>protected void onDestroy() { <START> super.onDestroy(); <END> lifecycleSubject.onNext(LifecycleEvent.DESTROY); }</code><technical_language>super.onXX() call</technical_language>

Target:
protected void onDestroy() { lifecycleSubject.onNext(LifecycleEvent.DESTROY); super.onDestroy(); }
Source:
<code>public Supplier<String> supplier() { return () -> { <START> System.out.println("Invoking supplier"); <END> return "hello"; }; }</code><technical_language>I need this SOUT in code all</technical_language>

Target:
public Supplier<String> supplier() { return () -> "hello"; }
Source:
<code>protected Identity getObject(String distinguishedName, String scope) { LdapContext context = null; try { LdapName object = new LdapName(distinguishedName); context = getServiceContext(); Attributes search; search = context.getAttributes(object); if (!isType(search, scope) && !hasPermission(search)){ return null; } return attributesToIdentity(object); } catch (NamingException e) { <START> getLogger().info("Failed to get object: " + distinguishedName, e.getExplanation()); <END> return null; } finally { if (context != null) { getContextPool().returnObject(context); } } }</code><technical_language>@hibooboo2 hit this code verify outputs expect? I is to. I string needs a formatted string want do variable replacement</technical_language>

Target:
protected Identity getObject(String distinguishedName, String scope) { LdapContext context = null; try { LdapName object = new LdapName(distinguishedName); context = getServiceContext(); Attributes search; search = context.getAttributes(object); if (!isType(search, scope) && !hasPermission(search)){ return null; } return attributesToIdentity(object); } catch (NamingException e) { getLogger().info("Failed to get object: : {}", distinguishedName, e.getExplanation()); return null; } finally { if (context != null) { getContextPool().returnObject(context); } } }
Source:
<code>public String getComponentKey() { return getComponent(); <START> } <END></code><technical_language>![INFO](<LINK_0> 'Severity: INFO') Do forget remove this deprecated code someday. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public String getComponentKey() { return componentKey; }
Source:
<code>protected Void visitQuerySpecification(QuerySpecification node, Integer indent) { process(node.getSelect(), indent); if (node.getFrom().isPresent()) { append(indent, "FROM"); builder.append('\n'); append(indent, " "); process(node.getFrom().get(), indent); } builder.append('\n'); if (node.getWhere().isPresent()) { append(indent, "WHERE " + formatExpression(node.getWhere().get(), parameters)) .append('\n'); } if (node.getGroupBy().isPresent()) { append(indent, "GROUP BY " + (node.getGroupBy().get().isDistinct() ? " DISTINCT " : "") + formatGroupBy(node.getGroupBy().get().getGroupingElements())).append('\n'); } if (node.getHaving().isPresent()) { append(indent, "HAVING " + formatExpression(node.getHaving().get(), parameters)) .append('\n'); } if (!node.getWindow().isEmpty()) { <START> append(indent, "WINDOW " + node.getWindow().stream().map(wd -> formatWindowDefinition(wd, parameters)).collect(joining(", "))).append('\n'); <END> } if (node.getOrderBy().isPresent()) { process(node.getOrderBy().get(), indent); } if (node.getLimit().isPresent()) { append(indent, "LIMIT " + node.getLimit().get()) .append('\n'); } return null; }</code><technical_language>preferred abbreviations, please windowDefinition definition instead of wd</technical_language>

Target:
protected Void visitQuerySpecification(QuerySpecification node, Integer indent) { process(node.getSelect(), indent); if (node.getFrom().isPresent()) { append(indent, "FROM"); builder.append('\n'); append(indent, " "); process(node.getFrom().get(), indent); } builder.append('\n'); if (node.getWhere().isPresent()) { append(indent, "WHERE " + formatExpression(node.getWhere().get(), parameters)) .append('\n'); } if (node.getGroupBy().isPresent()) { append(indent, "GROUP BY " + (node.getGroupBy().get().isDistinct() ? " DISTINCT " : "") + formatGroupBy(node.getGroupBy().get().getGroupingElements())).append('\n'); } if (node.getHaving().isPresent()) { append(indent, "HAVING " + formatExpression(node.getHaving().get(), parameters)) .append('\n'); } if (!node.getWindow().isEmpty()) { append(indent, "WINDOW " + node.getWindow().stream() .map(windowDefinition -> formatWindowDefinition(windowDefinition, parameters)) .collect(joining(", "))).append('\n'); } if (node.getOrderBy().isPresent()) { process(node.getOrderBy().get(), indent); } if (node.getLimit().isPresent()) { append(indent, "LIMIT " + node.getLimit().get()) .append('\n'); } return null; }
Source:
<code>public LdapAuthHealth checkHealth() { boolean isHealthy = true; String details = null; try { <START> LDAPConnection ldapConnection = connectionPool.getConnection(); <END> if (!ldapConnection.isConnected()) { isHealthy = false; } } catch (LDAPException e) { isHealthy = false; } details = new StringBuilder("LDAPConnection [DN: ").append(ldapConfiguration.getBindDn()).append(", Status: ") .append(isHealthy).append("]").toString(); return new LdapAuthHealth(isHealthy, details); }</code><technical_language>connectionPool.getHealthCheck()-there more advanced health checks delegate there</technical_language>

Target:
public RolesProviderHealth checkHealth() { boolean isHealthy = true; StringBuilder details = null; String failureReason = null; try { LDAPConnection ldapConnection = connectionPool.getConnection(); if (!ldapConnection.isConnected()) { isHealthy = false; } connectionPool.getHealthCheck().ensureConnectionValidForContinuedUse(ldapConnection); } catch (LDAPException e) { failureReason = e.getExceptionMessage(); isHealthy = false; } details = new StringBuilder("LDAPConnection [DN: ").append(ldapConfiguration.getBindDn()).append(", Status: ") .append(isHealthy); if (failureReason != null) { details.append(ldapConfiguration.getBindDn()).append(", Failure Reason: ").append(failureReason); } details.append("]"); return new RolesProviderHealth(isHealthy, details.toString()); }
Source:
<code>private static String sanitizeUrl(final String value) { String url = value.trim(); url = url.replace("\\", "%5C").replace("|", "%7C"); if (url.matches(".*#.*#.*")) { url = url.substring(0, (url.indexOf("#", url.indexOf("#") + 1))); } url = url.replace(" ", "%20"); if (!urlValidator.isValid(url)) { <START> if (!urlValidator.isValid(url)) { <END> for (String urlSplitter : url.split("%20")) { if (urlValidator.isValid(urlSplitter)) return urlSplitter; } if (!urlValidator.isValid(url)) { if (url.matches(".*:/[^/].*")) url = url.replace(":/", "://"); if (!urlValidator.isValid(url)) { url = "http://" + url; if (!urlValidator.isValid(url)) { url = ""; LOG.info( "No absolute URI could be generated from '" + value + "'"); } } } } } return url; }</code><technical_language>I this is accidental duplicate check (checks twice, modification in between)</technical_language>

Target:
private static String sanitizeUrl(final String value) { String url = value.trim(); url = url.replace("\\", "%5C").replace("|", "%7C"); if (url.matches(".*#.*#.*")) { url = url.substring(0, (url.indexOf("#", url.indexOf("#") + 1))); } url = url.replace(" ", "%20"); if (!urlValidator.isValid(url)) { for (String urlSplitter : url.split("%20")) { if (urlValidator.isValid(urlSplitter)) return urlSplitter; } if (url.matches(".*:/[^/].*")) url = url.replace(":/", "://"); if (!urlValidator.isValid(url)) { url = "http://" + url; if (!urlValidator.isValid(url)) { url = ""; LOG.info("No absolute URI could be generated from '" + value + "'"); } } } return url; }
Source:
<code>public boolean isEmpty() { return (root instanceof LeafBucket) <START> && ((LeafBucket) root).size() == 0; <END> }</code><technical_language>size() counts notes. non-notes, e.g. a spurious .gitignore file in notes tree? write produce a non-empty tree. check nonNotes if null</technical_language>

Target:
public boolean isEmpty() { if (!(root instanceof LeafBucket)) { return false; } LeafBucket b = (LeafBucket) root; return b.size() == 0 && b.nonNotes == null; }
Source:
<code>disableIncludes() { <START> noExpandIncludes = true; <END> includeThrowsException = false; }</code><technical_language>Please call overload instead of assigning variables: disableIncludes(false)</technical_language>

Target:
disableIncludes() { disableIncludes(false); }
Source:
<code>private List<CourseAttributes> extractArchivedCourses(List<CourseDetailsBundle> courseBundles) { ArrayList<CourseAttributes> archivedCourses = new ArrayList<CourseAttributes>(); for (CourseDetailsBundle courseBundle : courseBundles) { CourseAttributes course = courseBundle.course; InstructorAttributes curInstructor = logic.getInstructorForGoogleId(course.id, account.googleId); if(curInstructor.isArchived != null){ <START> course.isArchived = curInstructor.isArchived.booleanValue(); <END> } if (course.isArchived) { archivedCourses.add(course); } } return archivedCourses; }</code><technical_language>Autoboxing work</technical_language>

Target:
private List<CourseAttributes> extractArchivedCourses(List<CourseDetailsBundle> courseBundles) { ArrayList<CourseAttributes> archivedCourses = new ArrayList<CourseAttributes>(); for (CourseDetailsBundle courseBundle : courseBundles) { CourseAttributes course = courseBundle.course; InstructorAttributes curInstructor = logic.getInstructorForGoogleId(course.id, account.googleId); if(curInstructor.isArchived != null){ course.isArchived = curInstructor.isArchived; } if (course.isArchived) { archivedCourses.add(course); } } return archivedCourses; }
Source:
<code>public StickyTaskAssignor(final Map<ID, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> standbyTaskIds) { this.clients = clients; this.allTaskIds = allTaskIds; this.standbyTaskIds = standbyTaskIds; <START> final int maxPairs = standbyTaskIds.size() * (standbyTaskIds.size() - 1) / 2; <END> taskPairs = new TaskPairs(maxPairs); mapPreviousTaskAssignment(clients); }</code><technical_language>taskPairs is a heuristic avoid (active-1, standby-2) (active-2, standby-1) if instances failed time lose tasks: large num.pairs means case happen. if active task a standby, in some pairs, if means new math is correct not? E.g. tasks A, B, C A standby while others do (num.replicas == 2). assignment of (active-A, standby-B, standby-C), (active-B, standby-C), (active-C, standby-B) generates pairs AB, AC, BC, right? In ways, maxPairs is for initializing hash-set decide exit early, I setting larger values matter much</technical_language>

Target:
public StickyTaskAssignor(final Map<ID, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> standbyTaskIds) { this.clients = clients; this.allTaskIds = allTaskIds; this.standbyTaskIds = standbyTaskIds; final int maxPairs = allTaskIds.size() * (allTaskIds.size() - 1) / 2; taskPairs = new TaskPairs(maxPairs); mapPreviousTaskAssignment(clients); }
Source:
<code>public boolean isRecoveryEnabled() { <START> switch (this) { <END> case FULL_XA: return true; default: return false; } }</code><technical_language>return this == FULL_XA</technical_language>

Target:
public boolean isRecoveryEnabled() { return this == FULL_XA; }
Source:
<code>public List<RuleResult<Patient>> evaluate() { List<RuleResult<Patient>> ruleResults = new ArrayList<>(); <START> ruleResults.addAll(patientsWithMissingTBNumberIdentifiers("304df0d0-afe4-4a61-a917-d684b100a65a", "Unit TB Number")); <END> ruleResults.addAll(patientsWithMissingTBNumberIdentifiers("d1cda288-4853-4450-afbc-76bd4e65ea70", "HSD TB Number")); ruleResults.addAll(patientsWithMissingTBNumberIdentifiers("67e9ec2f-4c72-408b-8122-3706909d77ec", "District TB Number")); ruleResults.addAll(patientsWithSimilarTBNumberIdentifiersDuplicatedForASinglePatient("67e9ec2f-4c72-408b-8122-3706909d77ec", "District TB Number")); ruleResults.addAll(patientsWithSimilarTBNumberIdentifiersDuplicatedForASinglePatient("304df0d0-afe4-4a61-a917-d684b100a65a", "Unit TB Number")); ruleResults.addAll(patientsWithSimilarTBNumberIdentifiersDuplicatedForASinglePatient("d1cda288-4853-4450-afbc-76bd4e65ea70", "HSD TB Number")); ruleResults.addAll(patientsWithSimilarTBIdentifiersDuplicatedAcrossMultiplePatients("67e9ec2f-4c72-408b-8122-3706909d77ec", "District TB Number")); ruleResults.addAll(patientsWithSimilarTBIdentifiersDuplicatedAcrossMultiplePatients("304df0d0-afe4-4a61-a917-d684b100a65a", "Unit TB Number")); ruleResults.addAll(patientsWithSimilarTBIdentifiersDuplicatedAcrossMultiplePatients("d1cda288-4853-4450-afbc-76bd4e65ea70", "HSD TB Number")); ruleResults.addAll(patientsWithNoFinalOutcomeNineMonthsAfterStartOfTreatment(DateTime.now())); return ruleResults; }</code><technical_language>@moshonk Name methods properly - patientsWithMissingUnitTBNumber, patientsWithMissingHSDTBNumber, patientsWithMissingDistrictTBNumber ... applies duplicates</technical_language>

Target:
public List<RuleResult<Patient>> evaluate() { List<RuleResult<Patient>> ruleResults = new ArrayList<>(); ruleResults.addAll(patientsWithMissingTBNumbers(AijarConstants.UNIT_TB_NUMBER, "Unit TB Number")); ruleResults.addAll(patientsWithMissingTBNumbers(AijarConstants.HSD_TB_NUMBER, "HSD TB Number")); ruleResults.addAll(patientsWithMissingTBNumbers(AijarConstants.DISTRICT_TB_NUMBER, "District TB Number")); ruleResults.addAll(singlePatientWithDuplicateTBNumberAcrossMultipleTreatmentPrograms(AijarConstants.DISTRICT_TB_NUMBER, "District TB Number")); ruleResults.addAll(singlePatientWithDuplicateTBNumberAcrossMultipleTreatmentPrograms(AijarConstants.UNIT_TB_NUMBER, "Unit TB Number")); ruleResults.addAll(singlePatientWithDuplicateTBNumberAcrossMultipleTreatmentPrograms(AijarConstants.HSD_TB_NUMBER, "HSD TB Number")); ruleResults.addAll(multiplePatientsWithTheSameTBIdentifiers(AijarConstants.DISTRICT_TB_NUMBER, "District TB Number")); ruleResults.addAll(multiplePatientsWithTheSameTBIdentifiers(AijarConstants.UNIT_TB_NUMBER, "Unit TB Number")); ruleResults.addAll(multiplePatientsWithTheSameTBIdentifiers(AijarConstants.HSD_TB_NUMBER, "HSD TB Number")); ruleResults.addAll(patientsWithNoFinalOutcomeNineMonthsAfterStartOfTreatment(DateTime.now())); return ruleResults; }
Source:
<code>public int hashCode() { <START> return Objects.hashCode(source, destination, mode, rw); <END> }</code><technical_language>this java.util.Objects.hash(..) (we replace usage in rest of codebase too)</technical_language>

Target:
public int hashCode() { return java.util.Objects.hash(source, destination, mode, rw); }
Source:
<code>public CoreMessage putBytesProperty(final String key, final byte[] value) { messageChanged(); <START> getOrCreateProperties().putBytesProperty(key(key), value); <END> return this; }</code><technical_language>delegated as: putBytesProperty(key(key), value)</technical_language>

Target:
public CoreMessage putBytesProperty(final String key, final byte[] value) { return putBytesProperty(key(key), value); }
Source:
<code>public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); <START> Map<String, Collection<?>> data = new HashMap<String, Collection<?>>(); <END> data.put(KEY_POSITIONS, Context.getConnectionManager().getInitialState(userId)); sendData(data); Context.getConnectionManager().addListener(userId, this); }</code><technical_language>Traccar targets Java 7 higher, diamond operator right hand side</technical_language>

Target:
public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); Map<String, Collection<?>> data = new HashMap<>(); data.put(KEY_POSITIONS, Context.getConnectionManager().getInitialState(userId)); sendData(data); Context.getConnectionManager().addListener(userId, this); }
Source:
<code><START> public boolean doPostSetUserClaimValues(String userName, Map<String, String> claims, String profileName, <END> UserStoreManager userStoreManager) throws UserStoreException { removeAccessTokenFromCache(userName, userStoreManager); if (!isEnable()) { return true; } return revokeTokensOfLockedUser(userName, userStoreManager); }</code><technical_language>implement this in pre listener. need implement doPreSetUserClaimValue()</technical_language>

Target:
public boolean doPostSetUserClaimValues(String userName, Map<String, String> claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException { if (!isEnable()) { return true; } return revokeTokensOfLockedUser(userName, userStoreManager); }
Source:
<code>protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL(); String retryParam = ""; String username = getLoggedInUser(context); String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier()); try { if (context.isRetrying()) { retryParam = "&authFailure=true&authFailureMsg=login.fail.message"; } boolean isTOTPEnabled = TOTPAuthenticatorServiceComponent.getTotpManager().isTOTPEnabledForLocalUser (username); if (isTOTPEnabled) { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + request <START> .getParameter("sessionDataKey"))) <END> + "&authenticators=" + getName() + "&type=totp" + retryParam + "&username=" + username); } else { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + request .getParameter("sessionDataKey"))) + "&authenticators=" + getName() + "&type=totp_error" + retryParam + "&username=" + username); } } catch (IOException e) { throw new AuthenticationFailedException("Error when redirecting the totp login response, " + "user : " + username, e); } catch (TOTPException e) { throw new AuthenticationFailedException("Error when checking totp enabled for the user : " + username, e); } }</code><technical_language>CharacterEncoder.getSafeText()</technical_language>

Target:
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL(); String retryParam = ""; String username = getLoggedInUser(context); String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier()); try { if (context.isRetrying()) { retryParam = "&authFailure=true&authFailureMsg=login.fail.message"; } boolean isTOTPEnabled = TOTPAuthenticatorServiceComponent.getTotpManager().isTOTPEnabledForLocalUser (username); if (isTOTPEnabled) { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + CharacterEncoder .getSafeText(request.getParameter("sessionDataKey")))) + "&authenticators=" + getName() + "&type=totp" + retryParam + "&username=" + username); } else { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + CharacterEncoder .getSafeText(request.getParameter("sessionDataKey")))) + "&authenticators=" + getName() + "&type=totp_error" + retryParam + "&username=" + username); } } catch (IOException e) { throw new AuthenticationFailedException("Error when redirecting the totp login response, " + "user : " + username, e); } catch (TOTPException e) { throw new AuthenticationFailedException("Error when checking totp enabled for the user : " + username, e); } }
Source:
<code>public void testResourceGroupMatch() throws IOException { Path configurationFile = Files.createTempFile("file-session-test", "properties"); <START> ImmutableMap<String, String> properties = ImmutableMap.of("PROPERTY1", "VALUE1", "PROPERTY2", "VALUE2"); <END> SessionMatchSpec spec = new SessionMatchSpec( Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(Pattern.compile("global.pipeline.user_.*")), properties); Files.write(configurationFile, CODEC.toJsonBytes(ImmutableList.of(spec))); SessionPropertyConfigurationManager manager = new FileSessionPropertyManager(new FileSessionPropertyManagerConfig().setConfigFile(configurationFile.toString())); assertEquals(manager.getSystemSessionProperties(CONTEXT), properties); Files.delete(configurationFile); }</code><technical_language>Nit: declare Map</technical_language>

Target:
public void testResourceGroupMatch() throws IOException { Map<String, String> properties = ImmutableMap.of("PROPERTY1", "VALUE1", "PROPERTY2", "VALUE2"); SessionMatchSpec spec = new SessionMatchSpec( Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(Pattern.compile("global.pipeline.user_.*")), properties); assertProperties(properties, spec); }
Source:
<code>public void notSupported() throws Exception { context.checking(new Expectations() {{ oneOf(catalog).isSupported(255555); will(returnValue(false)); <START> oneOf(constraintValidator).getDefaultConstraintMessageTemplate(); <END> oneOf(constraintValidator).buildConstraintViolationWithTemplate(with(any(String.class))); }}); boolean isValid = validator.isValid(Sets.newHashSet(255555), constraintValidator); assertFalse(isValid); }</code><technical_language>return a string</technical_language>

Target:
public void notSupported() throws Exception { context.checking(new Expectations() {{ oneOf(catalog).isSupported(255555); will(returnValue(false)); oneOf(constraintValidator).getDefaultConstraintMessageTemplate(); will(returnValue("Found capability id that is not supported")); oneOf(constraintValidator).buildConstraintViolationWithTemplate("Found capability id that is not supported"); }}); List<Integer> ids = Lists.newArrayList(255555); boolean isValid = validator.isValid(ids, constraintValidator); assertFalse(isValid); }
Source:
<code>public void close() { if (deepCopy) throw new RuntimeException("Calling close on a deep copy is not supported"); closeDeepCopies(); closeLocalityGroupReaders(); if (sampleReaders != null) { for (LocalityGroupReader lgr : sampleReaders) { lgr.close(); } } try { reader.close(); } catch (IOException e) { <START> throw new RuntimeException(e); <END> } finally { } }</code><technical_language>new UncheckedIOException wrapper IOException is wrapped</technical_language>

Target:
public void close() { if (deepCopy) throw new RuntimeException("Calling close on a deep copy is not supported"); closeDeepCopies(); closeLocalityGroupReaders(); if (sampleReaders != null) { for (LocalityGroupReader lgr : sampleReaders) { lgr.close(); } } try { reader.close(); } catch (IOException e) { throw new UncheckedIOException(e); } finally { } }
Source:
<code>public Action getActionInformation() { <START> return action; <END> }</code><technical_language>reason change getActionInformation (i.e. instead of returning a new instance of action, update it)</technical_language>

Target:
public Action getActionInformation() { return new Action() { @Override public Optional<JabRefIcon> getIcon() { return Optional.of(application.getIcon()); } @Override public Optional<KeyBinding> getKeyBinding() { return Optional.of(KeyBinding.PUSH_TO_APPLICATION); } @Override public String getText() { return Localization.lang("Push entries to external application (%0)", application.getApplicationName()); } @Override public String getDescription() { return ""; } }; }
Source:
<code>public void testInspectBigQueryTable() throws InterruptedException, ExecutionException, IOException { InspectBigQueryTable.inspectBigQueryTable( PROJECT_ID, DATASET_ID, TABLE_ID, TOPIC_ID, SUBSCRIPTION_ID); String output = bout.toString(); assertThat(output, containsString("Job created: ")); <START> String jobId = output.split("Job created: ")[1].split("\n")[0]; CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } <END> }</code><technical_language>Fine if works, bet happen right other. (some hysteresis). (and a flaky test again)</technical_language>

Target:
public void testInspectBigQueryTable() throws InterruptedException, ExecutionException, IOException { InspectBigQueryTable.inspectBigQueryTable( PROJECT_ID, DATASET_ID, TABLE_ID, TOPIC_ID, SUBSCRIPTION_ID); TimeUnit.SECONDS.sleep(3); String output = bout.toString(); assertThat(output, containsString("Job created: ")); String jobId = output.split("Job created: ")[1].split("\n")[0]; CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } }
Source:
<code>public OAuth2TokenAttributes(Map<String, Object> attributes) { Assert.notEmpty(attributes, "attributes cannot be empty"); <START> this.attributes = attributes; <END> }</code><technical_language>Please a copy of attributes immutable copy</technical_language>

Target:
public OAuth2TokenAttributes(Map<String, Object> attributes) { this.attributes = Collections.unmodifiableMap(attributes); }
Source:
<code>public HostAddress searchByStartName(Protocol secondaryProtocol, List<HostAddress> loopAddress) { if (!isSecondaryHostFail()) { int checkWriterAttempts = 3; HostAddress currentWriter = null; do { try { currentWriter = searchForMasterHostAddress(secondaryProtocol, loopAddress); } catch (QueryException qe) { if (proxy.hasToHandleFailover(qe) && setSecondaryHostFail()) { addToBlacklist(secondaryProtocol.getHostAddress()); return null; } } checkWriterAttempts--; } while (currentWriter == null && checkWriterAttempts > 0); if (currentWriter == null && getClusterHostAddress() != null) { AuroraProtocol tempProtocol = AuroraProtocol.getNewProtocol(getProxy(), getUrlParser()); tempProtocol.setHostAddress(getClusterHostAddress()); try { tempProtocol.connect(); <START> return searchForMasterHostAddress(tempProtocol, loopAddress); <END> } catch (QueryException qe) { if (proxy.hasToHandleFailover(qe)) { addToBlacklist(tempProtocol.getHostAddress()); } } finally { tempProtocol.close(); } } return currentWriter; } return null; }</code><technical_language>remark previous : goal is current master host connect current master instance. if master is connected, need try a connection ward, set current master this protocol</technical_language>

Target:
public HostAddress searchByStartName(Protocol secondaryProtocol, List<HostAddress> loopAddress) { if (!isSecondaryHostFail()) { int checkWriterAttempts = 3; HostAddress currentWriter = null; do { try { currentWriter = searchForMasterHostAddress(secondaryProtocol, loopAddress); } catch (QueryException qe) { if (proxy.hasToHandleFailover(qe) && setSecondaryHostFail()) { addToBlacklist(secondaryProtocol.getHostAddress()); return null; } } checkWriterAttempts--; } while (currentWriter == null && checkWriterAttempts > 0); if (currentWriter == null && getClusterHostAddress() != null) { AuroraProtocol possibleMasterProtocol = AuroraProtocol.getNewProtocol(getProxy(), getUrlParser()); possibleMasterProtocol.setHostAddress(getClusterHostAddress()); try { possibleMasterProtocol.connect(); possibleMasterProtocol.setMustBeMasterConnection(true); foundActiveMaster(possibleMasterProtocol); } catch (QueryException qe) { if (proxy.hasToHandleFailover(qe)) { addToBlacklist(possibleMasterProtocol.getHostAddress()); } } } return currentWriter; } return null; }
Source:
<code>private Map<URI, KafkaStreamImporterConfig> createKafkaImporterConfigFromProperties(KafkaExternalLoaderCLIArguments properties) throws Exception { List<HostAndPort> brokerList; String brokerListString; if (!properties.zookeeper.trim().isEmpty()) { brokerList = getBrokersFromZookeeper(properties.zookeeper); brokerListString = StringUtils.join(brokerList.stream().map(s -> s.getHost() + ":" + s.getPort()).collect(Collectors.toList()), ","); } else { brokerListString = properties.brokers.trim(); <START> brokerList = Arrays.stream(brokerListString.split(",")).map(s -> HostAndPort.fromString(s)).collect(Collectors.toList()); <END> } String brokerKey = KafkaStreamImporterConfig.getBrokerKey(brokerListString); FormatterBuilder fb = createFormatterBuilder(properties); return KafkaStreamImporterConfig.getConfigsForPartitions(brokerKey, brokerList, properties.topic, properties.groupid, properties.procedure, properties.timeout, properties.buffersize, properties.commitPolicy, fb); }</code><technical_language>If zookeeper option is supplied need interact zookeeper -> dependency zookeeper libs in path, correct? If so, lets if user specifies brokers list instead of zookeeper host logic require user supply zookeeper libs</technical_language>

Target:
private Map<URI, KafkaStreamImporterConfig> createKafkaImporterConfigFromProperties(KafkaExternalLoaderCLIArguments properties) throws Exception { List<HostAndPort> brokerList; String brokerListString; if (!properties.zookeeper.trim().isEmpty()) { brokerList = getBrokersFromZookeeper(properties.zookeeper, properties.zookeeperSessionTimeoutMillis); brokerListString = StringUtils.join(brokerList.stream().map(s -> s.getHost() + ":" + s.getPort()).collect(Collectors.toList()), ","); } else { brokerListString = properties.brokers.trim(); brokerList = Arrays.stream(brokerListString.split(",")).map(s -> HostAndPort.fromString(s)).collect(Collectors.toList()); } String brokerKey = KafkaStreamImporterConfig.getBrokerKey(brokerListString); FormatterBuilder builder = createFormatterBuilder(properties); return KafkaStreamImporterConfig.getConfigsForPartitions(brokerKey, brokerList, properties.topic, properties.groupid, properties.procedure, properties.timeout, properties.buffersize, properties.commitPolicy, builder); }
Source:
<code>List<StartIdentifiedAtlasDbTransactionResponse> startIdentifiedAtlasDbTransactionBatch(int count) { return autobatcher.applyBatch( IntStream.range(0, count).mapToObj($ -> (Void) null).collect(Collectors.toList())) .stream() .map(result -> { try { return result.get(); } catch (ExecutionException e) { <START> throw Throwables.throwUncheckedException(e.getCause()); <END> } catch (Throwable t) { throw Throwables.throwUncheckedException(t); } }).collect(Collectors.toList()); }</code><technical_language>Again, I throw exceptions here: @gmaretic correct me, I timelock 1. choose return transactions asked for. 2. Dunno if disruptor guarantee requested number of transactions end in a single batch timelock. Therefore, I assume of futures fail independently, need decide handle that. need do leak resources: StartIdentifiedAtlasDbTransactionResponse contains immutable timestamp lock (again more versed in this explain is leaked), in #wrap method is explicitly unlocked fails</technical_language>

Target:
List<StartIdentifiedAtlasDbTransactionResponse> startIdentifiedAtlasDbTransactionBatch(int count) { List<StartIdentifiedAtlasDbTransactionResponse> responses = new ArrayList<>(); try { autobatcher.applyBatch( IntStream.range(0, count).mapToObj($ -> (Void) null).collect(Collectors.toList())) .forEach(result -> { try { responses.add(result.get()); } catch (Throwable t) { throw new RuntimeException(t); } }); return responses; } catch (RuntimeException e) { responses.forEach(response -> unlock(ImmutableSet.of(response.immutableTimestamp().getLock()))); throw e; } }
Source:
<code>public static boolean isInvalidCard(String cardNumber) { <START> return (ERROR_CARDS.containsKey(cardNumber)); <END> }</code><technical_language>Please remove unnecessary brackets</technical_language>

Target:
public static boolean isInvalidCard(String cardNumber) { return ERROR_CARDS.containsKey(cardNumber); }
Source:
<code>public void assetsDone() { cAquariumConfig = new Configuration(); cStartScreen = new StartScreen(); <START> setScreen(cStartScreen); <END> }</code><technical_language>done in 1 line</technical_language>

Target:
public void assetsDone() { cAquariumConfig = new Configuration(); setScreen(new StartScreen()); }
Source:
<code>public Substr() { super(new Column[] { <START> new Column("org/apache/tajo/storage/text", TajoDataTypes.Type.TEXT), <END> new Column("from", TajoDataTypes.Type.INT4), new Column("length", TajoDataTypes.Type.INT4) }); }</code><technical_language>This changed while refactor 'text'</technical_language>

Target:
public Substr() { super(new Column[] { new Column("text", TajoDataTypes.Type.TEXT), new Column("from", TajoDataTypes.Type.INT4), new Column("length", TajoDataTypes.Type.INT4) }); }
Source:
<code>private void sendProcessingMessages(SurveyInstance domain) { QueueFactory.getQueue("dataSummarization").add( <START> TaskOptions.Builder.withUrl("/app_worker/datasummarization") <END> .param("objectKey", domain.getKey().getId() + "") .param("type", "SurveyInstance")); QueueFactory.getDefaultQueue().add( TaskOptions.Builder .withUrl("/app_worker/surveyalservlet") .param(SurveyalRestRequest.ACTION_PARAM, SurveyalRestRequest.INGEST_INSTANCE_ACTION) .param(SurveyalRestRequest.SURVEY_INSTANCE_PARAM, domain.getKey().getId() + "")); }</code><technical_language>Lines 401-406, constants extracted? Some of (see lines 407-409)</technical_language>

Target:
private void sendProcessingMessages(SurveyInstance domain) { QueueFactory.getQueue(DATA_SUMMARIZATION_QUEUE).add( TaskOptions.Builder.withUrl(DATA_SUMMARIZATION_URL) .param(OBJECT_KEY_PARAM, domain.getKey().getId() + "") .param(TYPE_PARAM, SI_TYPE)); QueueFactory.getDefaultQueue().add( TaskOptions.Builder.withUrl(SURVEYAL_URL) .param(SurveyalRestRequest.ACTION_PARAM, SurveyalRestRequest.INGEST_INSTANCE_ACTION) .param(SurveyalRestRequest.SURVEY_INSTANCE_PARAM, domain.getKey().getId() + "")); }
Source:
<code>public void initialise() { playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); lightGeometryMaterial = getMaterial(LIGHT_GEOMETRY_MATERIAL); addDesiredStateChange(new EnableMaterial(LIGHT_GEOMETRY_MATERIAL.toString())); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); addDesiredStateChange(new EnableBlending()); addDesiredStateChange(new SetBlendFunction(GL_ONE, GL_ONE_MINUS_SRC_COLOR)); addDesiredStateChange(new DisableDepthTest()); <START> addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); <END> update(); initLightSphereDisplayList(); displayResolutionDependentFBOs.subscribe(this); }</code><technical_language>need a SetViewportToSizeOf line here</technical_language>

Target:
public void initialise() { playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); lightGeometryMaterial = getMaterial(LIGHT_GEOMETRY_MATERIAL); addDesiredStateChange(new EnableMaterial(LIGHT_GEOMETRY_MATERIAL.toString())); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); addDesiredStateChange(new EnableBlending()); addDesiredStateChange(new SetBlendFunction(GL_ONE, GL_ONE_MINUS_SRC_COLOR)); addDesiredStateChange(new DisableDepthTest()); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); update(); displayResolutionDependentFBOs.subscribe(this); initLightSphereDisplayList(); }
Source:
<code>public void before() { daoConfig.addTreatReferencesAsLogical("<LINK_1>*"); <START> daoConfig.addTreatReferencesAsLogical("<LINK_0>*"); <END> }</code><technical_language>unit tests making external calls HTTP server project. this replaced a local Jetty server simulating right calls</technical_language>

Target:
public void before() throws IOException { PackageCacheManager packageCacheManager = new PackageCacheManager(true, 1); InputStream stream; stream = IgInstallerTestDstu3.class.getResourceAsStream("erroneous-ig.tar.gz"); packageCacheManager.addPackageToCache("erroneous-ig", "1.0.0", stream, "erroneous-ig"); stream = IgInstallerTestDstu3.class.getResourceAsStream("NHSD.Assets.STU3.tar.gz"); packageCacheManager.addPackageToCache("NHSD.Assets.STU3", "1.0.0", stream, "NHSD.Assets.STU3"); stream = IgInstallerTestDstu3.class.getResourceAsStream("basisprofil.de.tar.gz"); packageCacheManager.addPackageToCache("basisprofil.de", "0.2.40", stream, "basisprofil.de"); }
Source:
<code>private void throwUnsupported(String feature) { <START> throw new UnsupportedOperationException(feature + " is not supported on this operating system"); <END> }</code><technical_language>s/operating/file/</technical_language>

Target:
private void throwUnsupported(String feature) { throw new UnsupportedOperationException(feature + " is not supported on this file system"); }
Source:
<code>public void shouldGetActiveConditions() { Patient patient = new Patient(2); List<Condition> active = dao.getActiveConditions(patient); assertEquals(active.size(), 2); assertEquals(active.get(0).getClinicalStatus(), ConditionClinicalStatus.INACTIVE); <START> assertEquals(active.get(0).getVerificationStatus(), ConditionVerificationStatus.PROVISIONAL); <END> assertEquals(active.get(1).getClinicalStatus(), ConditionClinicalStatus.ACTIVE); assertEquals(active.get(1).getVerificationStatus(), ConditionVerificationStatus.CONFIRMED); Patient secondPatient = new Patient(8); List<Condition> active2 = dao.getActiveConditions(secondPatient); assertEquals(active2.size(), 1); assertEquals(active2.get(0).getClinicalStatus(), ConditionClinicalStatus.ACTIVE); assertEquals(active2.get(0).getVerificationStatus(), ConditionVerificationStatus.CONFIRMED); }</code><technical_language>status unique pointless assertions for fields, instead need compare database id ensure matches expected</technical_language>

Target:
public void shouldGetActiveConditions() { Patient patient = new Patient(2); List<Condition> active = dao.getActiveConditions(patient); assertEquals(2, active.size()); }
Source:
<code>public DelegatingResourceDescription getRepresentationDescription(Representation representation) { if (representation instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("condition"); description.addProperty("clinicalStatus"); description.addProperty("verificationStatus"); <START> description.addProperty("previousVersion"); <END> description.addProperty("onsetDate"); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); return description; } else if (representation instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("condition"); description.addProperty("clinicalStatus"); description.addProperty("verificationStatus"); description.addProperty("previousVersion"); description.addProperty("onsetDate"); description.addProperty("additionalDetail"); description.addSelfLink(); return description; } return null; }</code><technical_language>Do wanna add for RefRepresentation</technical_language>

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation representation) { if (representation instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addProperty("condition"); description.addProperty("patient", Representation.REF); description.addProperty("clinicalStatus"); description.addProperty("verificationStatus"); description.addProperty("previousVersion"); description.addProperty("onsetDate"); description.addProperty("voided"); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); return description; } else if (representation instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addProperty("condition"); description.addProperty("patient", Representation.REF); description.addProperty("clinicalStatus"); description.addProperty("verificationStatus"); description.addProperty("previousVersion"); description.addProperty("onsetDate"); description.addProperty("additionalDetail"); description.addProperty("voided"); description.addProperty("auditInfo"); description.addSelfLink(); return description; } return null; }
Source:
<code>public boolean willEnter(Object request, Object target) { int modifierKeys = <START> 0; <END> if (request instanceof SelectionRequest) { modifierKeys = ((SelectionRequest) request).getModifiers(); } else if (request instanceof MouseEvent) { modifierKeys = ((MouseEvent) request).stateMask; } return (modifierKeys == SWT.CONTROL + SWT.SHIFT); }</code><technical_language>meaning of 0</technical_language>

Target:
public boolean willEnter(Object request, Object target) { int modifierKeys = SWT.NONE; if (request instanceof SelectionRequest) { modifierKeys = ((SelectionRequest) request).getModifiers(); } else if (request instanceof MouseEvent) { modifierKeys = ((MouseEvent) request).stateMask; } return (modifierKeys == SWT.CONTROL + SWT.SHIFT); }
Source:
<code>protected String acquireIpAddress() { <START> if(ipTable != null) { <END> for(Map.Entry<String, Boolean> entry : ipTable.entrySet()) { if(! entry.getValue()) { entry.setValue(true); return entry.getKey(); } } } return null; }</code><technical_language>This test useless if map initialized in class</technical_language>

Target:
protected String acquireIpAddress() { for(Map.Entry<String, Boolean> entry : ipTable.entrySet()) { if(! entry.getValue()) { entry.setValue(true); return entry.getKey(); } } return null; }