auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public EventHubMessage receive() { logger.debug("Retrieving messages for partition: " + partitionId); <START> int countToRetrieve = pending.size() - config.getMaxPendingMsgsPerPartition(); <END> if (countToRetrieve >= 0) { Log.debug("Pending queue has more than " + config.getMaxPendingMsgsPerPartition() + " messages. No new events will be retrieved from EventHub."); return null; } EventHubMessage ehm = null; if (!toResend.isEmpty()) { ehm = toResend.pollFirst(); } else { if (waitingToEmit.isEmpty()) { fill(); } ehm = waitingToEmit.pollFirst(); } if (ehm == null) { logger.debug("No messages pending or waiting for reprocessing."); return null; } lastOffset = ehm.getOffset(); pending.put(lastOffset, ehm); return ehm; }</code><technical_language>name this is confusing. number of messages pending is limit, number of messages retrieve</technical_language>

Target:
public EventHubMessage receive() { logger.debug("Retrieving messages for partition: " + this.partitionPath); if (pendingAcks.size() >= config.getMaxPendingMsgsPerPartition()) { logger.debug(String.format( "Pending queue full(%s) - no new events will be received from EventHub Partition: %s.", config.getMaxPendingMsgsPerPartition(), this.partitionPath)); return null; } final EventHubMessage ehm; if (!failed.isEmpty()) { ehm = failed.pollFirst(); } else { final Iterable<EventData> events = this.receiver.receive(1); ehm = (events == null || !events.iterator().hasNext()) ? null : new EventHubMessage(events.iterator().next(), this.partitionId); } if (ehm == null) { logger.debug( String.format("No messages available from EventHubPartition: %s, or waiting for reprocessing.", this.partitionPath)); return null; } this.firstEventTracker.set(ehm); pendingAcks.put(ehm.getOffset(), ehm); return ehm; }
Source:
<code>private void handleConnectionChange(final String oldValue, final String v, boolean supportUndo) { try { <START> context.setConnecteeName(comp, connector, v); <END> } catch (IOException iae) { new JOptionPane(iae.getMessage(), JOptionPane.ERROR_MESSAGE).createDialog(null, "Error").setVisible(true); return; } handleConnectionChangeCommon(); if (supportUndo) { AbstractUndoableEdit auEdit = new AbstractUndoableEdit() { @Override public void undo() throws CannotUndoException { super.undo(); setConnectedToNameAndPropagateChange(oldValue, false); } @Override public String getUndoPresentationName() { return "Undo "+connector.getName()+" change"; } @Override public void redo() throws CannotRedoException { super.redo(); setConnectedToNameAndPropagateChange(v, true); } @Override public String getRedoPresentationName() { return "Redo "+connector.getName()+" change"; } }; ExplorerTopComponent.addUndoableEdit(auEdit); } }</code><technical_language>Is this attempting set connection OpenSimContext's cached model</technical_language>

Target:
private void handleConnectionChange(final String oldValue, final String v, boolean supportUndo) { try { context.setSocketConnecteeName(connector, v); } catch (IOException iae) { new JOptionPane(iae.getMessage(), JOptionPane.ERROR_MESSAGE).createDialog(null, "Error").setVisible(true); return; } handleConnectionChangeCommon(); if (supportUndo) { AbstractUndoableEdit auEdit = new AbstractUndoableEdit() { @Override public void undo() throws CannotUndoException { super.undo(); setConnectedToNameAndPropagateChange(oldValue, false); } @Override public String getUndoPresentationName() { return "Undo "+connector.getName()+" change"; } @Override public void redo() throws CannotRedoException { super.redo(); setConnectedToNameAndPropagateChange(v, true); } @Override public String getRedoPresentationName() { return "Redo "+connector.getName()+" change"; } }; ExplorerTopComponent.addUndoableEdit(auEdit); } }
Source:
<code>public static <R extends BaseResource> UriBuilder getUriBuilder(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { UriBuilder uriBuilder = builderMap.get(model.getClass()); if (uriBuilder == null) { Collection collection = getCollection(model, suggestedParentType); if (collection == null) { return null; } if (collection.getParentType() != NO_PARENT) { BaseResource parent = getParentModel(model, collection.getParentType()); Collection parentCollection = getCollection(parent, suggestedParentType); String path = getPath(collection.getCollectionType(), parentCollection.getResourceType(), model.getClass()); uriBuilder = getUriBuilder(uriInfo, parent).path(path); } else { String path = getPath(collection.getCollectionType()); uriBuilder = uriInfo != null ? UriBuilder.fromPath(uriInfo.getBaseUri().getPath()).path(path) : UriBuilder.fromPath(path); } builderMap.put(model.getClass(), uriBuilder.clone()); } else { uriBuilder = uriBuilder.clone(); <START> } <END> return uriBuilder.path(model.getId()); }</code><technical_language>if this work correctly in cases. account state of UriBuilder depend class of model, classes of parent models. A model, for example a Disk, in multiple places: in /disks collection (no parent), in /vm/{vm:id}/disks collection (the parent is VM), in /storagedomain/{storagedomain:id}/disks collection (the parent is Storage Domain), etc. In cases if cache builder based in model class calculating URL incorrectly in of scenarios</technical_language>

Target:
public static <R extends BaseResource> UriBuilder getUriBuilder(UriInfo uriInfo, R model, Class<? extends BaseResource> suggestedParentType) { Collection collection = getCollection(model, suggestedParentType); if (collection == null) { return null; } UriBuilder uriBuilder = builderMap.get(collection); if (uriBuilder == null) { if (collection.getParentType() != NO_PARENT) { BaseResource parent = getParentModel(model, collection.getParentType()); Collection parentCollection = getCollection(parent, suggestedParentType); String path = getPath(collection.getCollectionType(), parentCollection.getResourceType(), model.getClass()); uriBuilder = getUriBuilder(uriInfo, parent).path(path); } else { String path = getPath(collection.getCollectionType()); uriBuilder = uriInfo != null ? UriBuilder.fromPath(uriInfo.getBaseUri().getPath()).path(path) : UriBuilder.fromPath(path); } builderMap.put(collection, uriBuilder.clone()); } else { uriBuilder = uriBuilder.clone(); } return uriBuilder.path(model.getId()); }
Source:
<code>public List<Application> getApplications() throws ApplicationException { try(Connection connection = PlatformConnection.getInstance().getConnection()) { if (isSystemAdministrator()) { return applicationBusiness.getApplications(connection); } else if (isGroupAdministrator()) { List<String> classes = classBusiness.getUserClassesName( getSessionUser().getEmail(), true, connection); return applicationBusiness.getApplications(classes, connection); } List<AppClass> classes = classBusiness.getUserClasses( getSessionUser().getEmail(), false, connection); List<String> classNames = new ArrayList<>(); for (AppClass c : classes) { classNames.add(c.getName()); <START> } <END> return applicationBusiness.getApplications(classNames, connection); } catch (BusinessException | CoreException ex) { throw new ApplicationException(ex); } catch (SQLException ex) { logger.error("Error handling a connection", ex); throw new ApplicationException(ex); } }</code><technical_language>List<String> classNames = classList.stream().map(AppClass::getName).collect(Collectors.toList());</technical_language>

Target:
public List<Application> getApplications() throws ApplicationException { try(Connection connection = PlatformConnection.getInstance().getConnection()) { if (isSystemAdministrator()) { return applicationBusiness.getApplications(connection); } else if (isGroupAdministrator()) { List<String> classes = classBusiness.getUserClassesName( getSessionUser().getEmail(), true, connection); return applicationBusiness.getApplications(classes, connection); } List<AppClass> classes = classBusiness.getUserClasses( getSessionUser().getEmail(), false, connection); List<String> classNames = classes.stream().map(AppClass::getName).collect(Collectors.toList()); return applicationBusiness.getApplications(classNames, connection); } catch (BusinessException | CoreException ex) { throw new ApplicationException(ex); } catch (SQLException ex) { logger.error("Error handling a connection", ex); throw new ApplicationException(ex); } }
Source:
<code>protected boolean addedValid(IConfigurationElement element) { <START> String rankName = element.getAttribute(ATT_RANK); <END> final int rank; if (rankName == null) { rank = DEFAULT_RANK_VALUE; } else { rank = Integer.valueOf(rankName).intValue(); } String typeAttribute = element.getAttribute(ATT_COMPARISON_TYPE); final ComparisonType type; if (typeAttribute != null) { type = ComparisonType.valueOf(typeAttribute); } else { type = ComparisonType.BOTH; } String label = element.getAttribute(ATT_LABEL); String description = element.getAttribute(ATT_DESCRIPTION); DifferenceDescriptorWrapper itemDescriptor = new DifferenceDescriptorWrapper(label, description, element, rank, type); IItemDescriptor<Descriptor> previous = groupProviderRegistry.add(itemDescriptor); if (previous != null) { log(IStatus.WARNING, element, "The group provider descriptor'" + element.getAttribute(ATT_CLASS) + "' is registered twice."); } return true; }</code><technical_language>"Name"? "rankValue" "rankRaw" instead</technical_language>

Target:
protected boolean addedValid(IConfigurationElement element) { String rankValue = element.getAttribute(ATT_RANK); final int rank; if (rankValue == null) { rank = DEFAULT_RANK_VALUE; } else { rank = Integer.valueOf(rankValue).intValue(); } String typeAttribute = element.getAttribute(ATT_COMPARISON_TYPE); final ComparisonType type; if (typeAttribute != null) { type = ComparisonType.valueOf(typeAttribute); } else { type = ComparisonType.BOTH; } String label = element.getAttribute(ATT_LABEL); String description = element.getAttribute(ATT_DESCRIPTION); DifferenceDescriptorWrapper itemDescriptor = new DifferenceDescriptorWrapper(label, description, element, rank, type); IItemDescriptor<Descriptor> previous = groupProviderRegistry.add(itemDescriptor); if (previous != null) { log(IStatus.WARNING, element, "The group provider descriptor'" + element.getAttribute(ATT_CLASS) + "' is registered twice."); } return true; }
Source:
<code>public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { Class<?> targetClass = AopUtils.isAopProxy(bean) ? AopUtils.getTargetClass(bean) : bean.getClass(); ReflectionUtils.doWithMethods(targetClass, method -> { StreamEmitter streamEmitter = AnnotatedElementUtils.findMergedAnnotation(method, StreamEmitter.class); <START> if (streamEmitter != null && !method.isBridge()) { <END> mappedStreamEmitterMethods.add(bean, method); } }); return bean; }</code><technical_language>reason find @StreamEmitter annotation if !method.isBridge(). OTOH ReflectionUtils.doWithMethods() MethodFilter argument. is ReflectionUtils.USER_DECLARED_METHODS matter simplify MethodCallback impl</technical_language>

Target:
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { ReflectionUtils.doWithMethods(bean.getClass(), method -> { StreamEmitter streamEmitter = AnnotatedElementUtils.findMergedAnnotation(method, StreamEmitter.class); if (streamEmitter != null) { mappedStreamEmitterMethods.add(bean, method); } }, ReflectionUtils.USER_DECLARED_METHODS); return bean; }
Source:
<code>public void stopListening() { log.debug("Stop listening event seen."); <START> commError = false; <END> if (this.autoListen && !this.speaking) { if (System.currentTimeMillis() - lastAutoListenEvent > 300) { startListening(); } else { if (listening) { error("Please close zombie tabs and check Internet connection"); commError = true; } } lastAutoListenEvent = System.currentTimeMillis(); } else { log.debug("micNotListening"); listening = false; } if (!commError) { broadcastState(); } }</code><technical_language>this variable defined locally this method if of this method</technical_language>

Target:
public void stopListening() { log.debug("Stop listening event seen."); boolean commError = false; if (this.autoListen && !this.speaking) { if (System.currentTimeMillis() - lastAutoListenEvent > 300) { startListening(); } else { if (listening) { error("Please close zombie tabs and check Internet connection"); commError = true; } } lastAutoListenEvent = System.currentTimeMillis(); } else { log.debug("micNotListening"); listening = false; } if (!commError) { broadcastState(); } }
Source:
<code>public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); snapshot.put(PARTITION_ID, toPathString()); snapshot.put(PARTITION_WRITE_STATE, getPartitionState().name()); snapshot.put(PARTITION_CLASS, getPartitionClass()); <START> snapshot.put(PARTITION_RESOURCE_ID, getResourceName()); <END> JSONArray replicas = new JSONArray(); getReplicaIds().forEach(replica -> replicas.put(replica.getSnapshot())); snapshot.put(PARTITION_REPLICAS, replicas); return snapshot; }</code><technical_language>align naming convention PARTITION_RESOURCE_ID resourceName</technical_language>

Target:
public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); snapshot.put(PARTITION_ID, toPathString()); snapshot.put(PARTITION_WRITE_STATE, getPartitionState().name()); snapshot.put(PARTITION_CLASS, getPartitionClass()); snapshot.put(PARTITION_RESOURCE_NAME, getResourceName()); JSONArray replicas = new JSONArray(); getReplicaIds().forEach(replica -> replicas.put(replica.getSnapshot())); snapshot.put(PARTITION_REPLICAS, replicas); return snapshot; }
Source:
<code>public static Date castToDate(Object x, int targetSqlType) throws SQLException { if (x instanceof Date) { return (Date) x; } if (x instanceof java.util.Date) { return new Date(((java.util.Date) x).getTime()); } if (x instanceof String) { <START> throw new SQLException("Conversion from String to Date not yet supported"); <END> } throw invalidConversion(x, targetSqlType); }</code><technical_language>nit: is java.sql.Date#valueOf(java.lang.String)</technical_language>

Target:
public static Date castToDate(Object x, int targetSqlType) throws SQLException { if (x instanceof Date) { return (Date) x; } if (x instanceof java.util.Date) { return new Date(((java.util.Date) x).getTime()); } if (x instanceof LocalDate) { return Date.valueOf((LocalDate) x); } if (x instanceof LocalDateTime) { return Date.valueOf(((LocalDateTime) x).toLocalDate()); } try { if (x instanceof String) { return Date.valueOf((String) x); } } catch (RuntimeException e) { throw invalidConversion(x, targetSqlType, e); } throw invalidConversion(x, targetSqlType); }
Source:
<code>public Matrix power(int n, Factory factory) { <START> return exponentBySqaring(this, n, factory); <END> }</code><technical_language>I meant, need a separate method. Lets do in power</technical_language>

Target:
public Matrix power(int n, Factory factory) { if (n < 0) throw new IllegalArgumentException( "The exponent has to be larger than 0."); else if (n == 0) return factory.createIdentityMatrix(rows); else if (n > 0) { Matrix result = factory.createIdentityMatrix(rows); Matrix x = this; while (n > 0) { if (n % 2 == 1) { result = result.multiply(x); } n /= 2; x = x.multiply(x); } return result; } throw new IllegalArgumentException( "You used illegal arguments for the power()-function."); }
Source:
<code>protected FileSplit makeSplit(Path file, long start, long length, String[] hosts, String[] inMemoryHosts) { <START> long cachedStart = getCachedStartIndex(file); <END> long cachedEnd = getCachedEndIndex(file); if (cachedStart > start + length) { return new NullRowsInputFormat.DummyInputSplit(file); } else if (cachedStart > start) { length = length - (cachedStart - start); start = cachedStart; } if (cachedEnd > - 1 && cachedEnd < start) { return new NullRowsInputFormat.DummyInputSplit(file); } else if (cachedEnd < start + length) { length = cachedEnd - start; } return super.makeSplit(file, start, length, hosts, inMemoryHosts); }</code><technical_language>logic obtain start length duplicated in 2 methods. a private methods for it</technical_language>

Target:
protected FileSplit makeSplit(Path file, long start, long length, String[] hosts, String[] inMemoryHosts) { return makeSplitInternal(file, start, length, hosts, inMemoryHosts); }
Source:
<code>public void testNestedNonTerminals2() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resy = new Grammar.RegExState(new Grammar.StateId("RegExStidy"), nt1, new Grammar.State.OrderingInfo(3), Pattern.compile("y")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(nts); nt1.entryState.next.add(nt1.exitState); nts.next.add(resy); resy.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("yy")).parse(nt1, 0); Term expected = amb(klist(amb(klist(amb(klist(amb(KList.EMPTY), Token.kAppOf("K", "y"))), Token.kAppOf("K", "y"))))); assertEquals("y^n check: ", expected, result); } <START> assertEquals("Expected Nullable NTs", 1, NullabilityCheck.getReachableNullableNT(nt1).size()); <END> }</code><technical_language>Please assert nullable nonterminal is</technical_language>

Target:
public void testNestedNonTerminals2() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resy = new Grammar.RegExState(new Grammar.StateId("RegExStidy"), nt1, new Grammar.State.OrderingInfo(3), Pattern.compile("y")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(nts); nt1.entryState.next.add(nt1.exitState); nts.next.add(resy); resy.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); Assert.assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("yy")).parse(nt1, 0); Term expected = amb(klist(amb(klist(amb(klist(amb(KList.EMPTY), Token.kAppOf("K", "y"))), Token.kAppOf("K", "y"))))); Assert.assertEquals("y^n check: ", expected, result); } Assert.assertEquals("Expected Nullable NTs", nt1, NullabilityCheck.getReachableNullableNT(nt1).iterator().next()); }
Source:
<code>public Tuple exec(final Tuple inputTuple) throws IOException { final Object objA = extractFieldAtIndex(inputTuple, 0); Sketch sketchA = null; if (objA != null) { final DataByteArray dbaA = (DataByteArray)objA; final Memory srcMem = Memory.wrap(dbaA.get()); <START> sketchA = Sketch.wrap(srcMem, DEFAULT_UPDATE_SEED); <END> } final Object objB = extractFieldAtIndex(inputTuple, 1); Sketch sketchB = null; if (objB != null) { final DataByteArray dbaB = (DataByteArray)objB; final Memory srcMem = Memory.wrap(dbaB.get()); sketchB = Sketch.wrap(srcMem, DEFAULT_UPDATE_SEED); } final double[] jaccardTupple = com.yahoo.sketches.theta.JaccardSimilarity.jaccard(sketchA, sketchB); return doubleArrayToTuple(jaccardTupple); }</code><technical_language>needs optional API accommodate a user supplying a seed other assuming DEFAULT_UPDATE_SEED. Otherwise, resulting Jaccard garbage if original Tuple sketches created a seed</technical_language>

Target:
public Tuple exec(final Tuple inputTuple) throws IOException { final Object objA = extractFieldAtIndex(inputTuple, 0); Sketch sketchA = null; if (objA != null) { final DataByteArray dbaA = (DataByteArray)objA; final Memory srcMem = Memory.wrap(dbaA.get()); sketchA = Sketch.wrap(srcMem, seed); } final Object objB = extractFieldAtIndex(inputTuple, 1); Sketch sketchB = null; if (objB != null) { final DataByteArray dbaB = (DataByteArray)objB; final Memory srcMem = Memory.wrap(dbaB.get()); sketchB = Sketch.wrap(srcMem, seed); } final double[] jaccardTupple = com.yahoo.sketches.theta.JaccardSimilarity.jaccard(sketchA, sketchB); return doubleArrayToTuple(jaccardTupple); }
Source:
<code>public void setup() throws Exception { scheduledExecutorService = Executors.newScheduledThreadPool(0); <START> cache = StandaloneCacheBuilder.newCacheBuilder(Number.class, String.class, LoggerFactory.getLogger(Ehcache.class+"StatisticsTest")) <END> .withStatisticsExecutor(scheduledExecutorService) .withCapacity(capacity).build(); cache.init(); }</code><technical_language>Separator :-)</technical_language>

Target:
public void setup() throws Exception { scheduledExecutorService = Executors.newScheduledThreadPool(0); cache = StandaloneCacheBuilder.newCacheBuilder(Number.class, String.class, LoggerFactory.getLogger(Ehcache.class + "-" + "StatisticsTest")) .withStatisticsExecutor(scheduledExecutorService) .withCapacity(capacity).build(); cache.init(); }
Source:
<code>public void inflatedisbusmentDate() { mfDatePicker = MFDatePicker.newInsance(this); tvDisbursementOnDate.setText(MFDatePicker.getDatePickedAsString()); <START> tvDisbursementOnDate.setOnClickListener(new View.OnClickListener() { <END> @Override public void onClick(View view) { mfDatePicker.show(getActivity().getSupportFragmentManager(), FragmentConstants .DFRAG_DATE_PICKER); } }); }</code><technical_language>ButterKnife. Please remove this OnClickListener implementation Butter Knife @OnClick annotation</technical_language>

Target:
public void inflatedisbusmentDate() { mfDatePicker = MFDatePicker.newInsance(this); tvDisbursementOnDate.setText(MFDatePicker.getDatePickedAsString()); }
Source:
<code>public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; final String token = tokenExtractor.getToken(request); if (shouldSkipAuthentication(request, token)) { chain.doFilter(req, res); return; } final String requestURI = request.getRequestURI(); if (token == null) { LOG.debug("No 'Authorization' header for {}", requestURI); send403(res); return; } Jws<Claims> jwt; try { jwt = Jwts.parser().setSigningKey(getJwtPublicKey(false)).parseClaimsJws(token); <START> LOG.debug("JWT = " + jwt.toString()); <END> } catch (SignatureException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException e) { LOG.error("Failed verifying the JWT token", e); try { LOG.info("Retrying after updating the public key", e); jwt = Jwts.parser().setSigningKey(getJwtPublicKey(true)).parseClaimsJws(token); LOG.debug("JWT = " + jwt.toString()); } catch (SignatureException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException ee) { LOG.error("Failed verifying the JWT token after public key update", e); send403(res); return; } } request.setAttribute("token", jwt); chain.doFilter(req, res); }</code><technical_language>+ call toString if required</technical_language>

Target:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; final String token = tokenExtractor.getToken(request); if (shouldSkipAuthentication(request, token)) { chain.doFilter(req, res); return; } final String requestURI = request.getRequestURI(); if (token == null) { LOG.debug("No 'Authorization' header for {}", requestURI); send403(res); return; } Jws<Claims> jwt; try { jwt = Jwts.parser().setSigningKey(getJwtPublicKey(false)).parseClaimsJws(token); LOG.debug("JWT = ", jwt); } catch (SignatureException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException e) { LOG.error("Failed verifying the JWT token", e); try { LOG.info("Retrying after updating the public key", e); jwt = Jwts.parser().setSigningKey(getJwtPublicKey(true)).parseClaimsJws(token); LOG.debug("JWT = ", jwt); } catch (SignatureException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException ee) { LOG.error("Failed verifying the JWT token after public key update", e); send403(res); return; } } request.setAttribute("token", jwt); chain.doFilter(req, res); }
Source:
<code>public static TokenState fromString(final String state) { try { return TokenState.valueOf(state.toUpperCase()); } catch (Exception e) { <START> return ACTIVE; <END> } }</code><technical_language>want log error this a programming defect</technical_language>

Target:
public static TokenState fromString(final String state) { try { return TokenState.valueOf(state.toUpperCase()); } catch (Exception e) { LOGGER.error("Unknown token state: " + state); return ACTIVE; } }
Source:
<code>public void execute() { if (!basePanel.getSelectedEntries().isEmpty()) { basePanel.output(Localization.lang("Looking for full text document...")); } else { LOGGER.debug("No entry selected for fulltext download."); } if (basePanel.getSelectedEntries().size() >= WARNING_LIMIT) { boolean confirmDownload = dialogService.showConfirmationDialogAndWait( Localization.lang("Look up full text documents"), Localization.lang( "You are about to look up full text documents for %0 entries.", String.valueOf(basePanel.getSelectedEntries().size())) + "\n" + Localization.lang("JabRef will send at least one request per entry to a publisher.") + "\n" + Localization.lang("Do you still want to continue?"), Localization.lang("Look up full text documents"), Localization.lang("Cancel")); if (!confirmDownload) { basePanel.output(Localization.lang("Operation canceled.")); return; } } Task<Map<BibEntry, Optional<URL>>> findFullTextsTask = new Task<Map<BibEntry, Optional<URL>>>() { @Override protected Map<BibEntry, Optional<URL>> call() { Map<BibEntry, Optional<URL>> downloads = new ConcurrentHashMap<>(); int count = 0; AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(basePanel.getBibDatabaseContext(), Globals.prefs.getFilePreferences(), Globals.prefs.getAutoLinkPreferences(), ExternalFileTypes.getInstance()); List<BibEntry> changed = util.linkAssociatedFiles(basePanel.getSelectedEntries(), new NamedCompound("")); <START> for (BibEntry entry : changed) { <END> if (entry.getFiles().isEmpty()) { downloads.put(entry, fetchers.findFullTextPDF(entry)); } else { downloads.put(entry, Optional.empty()); } updateProgress(++count, basePanel.getSelectedEntries().size()); } return downloads; } }; findFullTextsTask.setOnSucceeded(value -> downloadFullTexts(findFullTextsTask.getValue())); dialogService.showProgressDialogAndWait( Localization.lang("Look up full text documents"), Localization.lang("Looking for full text document..."), findFullTextsTask); Globals.TASK_EXECUTOR.execute(findFullTextsTask); }</code><technical_language>do run changed entries</technical_language>

Target:
public void execute() { if (!basePanel.getSelectedEntries().isEmpty()) { basePanel.output(Localization.lang("Looking for full text document...")); } else { LOGGER.debug("No entry selected for fulltext download."); } if (basePanel.getSelectedEntries().size() >= WARNING_LIMIT) { boolean confirmDownload = dialogService.showConfirmationDialogAndWait( Localization.lang("Look up full text documents"), Localization.lang("You are about to look up full text documents for %0 entries.", String.valueOf(basePanel.getSelectedEntries().size())) + "\n" + Localization.lang("JabRef will send at least one request per entry to a publisher.") + "\n" + Localization.lang("Do you still want to continue?"), Localization.lang("Look up full text documents"), Localization.lang("Cancel")); if (!confirmDownload) { basePanel.output(Localization.lang("Operation canceled.")); return; } } lookupFullText(); }
Source:
<code>public void onHideCompletedJobs() { boolean newValue = !uiPrefs_.hideCompletedJobs().getValue(); uiPrefs_.hideCompletedJobs().setGlobalValue(newValue); <START> commands_.hideCompletedJobs().setChecked(newValue); <END> uiPrefs_.writeUIPrefs(); }</code><technical_language>Do need this line? (looks command get checked state automatically updated UI pref update handler)</technical_language>

Target:
public void onHideCompletedJobs() { boolean newValue = !uiPrefs_.hideCompletedJobs().getValue(); uiPrefs_.hideCompletedJobs().setGlobalValue(newValue); uiPrefs_.writeUIPrefs(); }
Source:
<code>public JexlEvaluateFunctions(JexlContext context, JexlEngine jexl){ <START> Preconditions.checkNotNull(context, "JexlContext context"); <END> Preconditions.checkNotNull(jexl, "JexlEngine jexl"); m_context= context; m_jexl = jexl; }</code><technical_language>a note, checkNotNull returns value, do m_context = Preconditions.checkNotNull(context, ...) instead of this lines</technical_language>

Target:
public JexlEvaluateFunctions(JexlContext context, JexlEngine jexl){ m_context = Preconditions.checkNotNull(context, "JexlContext context"); m_jexl = Preconditions.checkNotNull(jexl, "JexlEngine jexl"); }
Source:
<code>public void testHeadings() { builder.beginDocument(); builder.beginHeading(1, new Attributes()); builder.characters("This is an H1"); builder.endHeading(); builder.beginHeading(2, new Attributes()); builder.characters("This is an H2"); builder.endHeading(); builder.beginHeading(6, new Attributes()); builder.characters("This is an H6"); builder.endHeading(); builder.endDocument(); String markup = out.toString(); TestUtil.println(markup); <START> assertEquals("# This is an H1\n\n## This is an H2\n\n###### This is an H6\n\n", markup); <END> }</code><technical_language>good survey world if a more popular heading style (since four: setext-style hyphen underline, setext-style equals underline, atx-style, closed atx-style)</technical_language>

Target:
public void testHeadings() { builder.beginDocument(); builder.beginHeading(1, new Attributes()); builder.characters("This is an H1"); builder.endHeading(); builder.beginHeading(2, new Attributes()); builder.characters("This is an H2"); builder.endHeading(); builder.beginHeading(6, new Attributes()); builder.characters("This is an H6"); builder.endHeading(); builder.endDocument(); assertMarkup("# This is an H1\n\n## This is an H2\n\n###### This is an H6\n\n"); }
Source:
<code>protected void buildClientsForServer(ServerTemplate serverTemplate) { KieServicesClient kieServicesClient = createClientForTemplate(serverTemplate, null, getCredentialsProvider()); if (kieServicesClient != null) { serverTemplatesClients.computeIfAbsent(serverTemplate.getId(), (k) -> new ConcurrentHashMap<String, KieServicesClient>()); serverTemplatesClients.get(serverTemplate.getId()).put("", kieServicesClient); } if (serverTemplate.getContainersSpec() != null) { for (ContainerSpec containerSpec : serverTemplate.getContainersSpec()) { try { if (serverTemplatesClients.get(serverTemplate.getId()).containsKey(containerSpec.getId())) { logger.debug("KieServerClient for is already created", containerSpec.getId()); continue; } KieContainer kieContainer = kieServices.newKieContainer(containerSpec.getReleasedId()); KieServicesClient kieServicesClientForContainer = createClientForTemplate(serverTemplate, kieContainer.getClassLoader(), getCredentialsProvider()); if (kieServicesClient != null) { <START> serverTemplatesClients.get(serverTemplate.getId()).put(containerSpec.getId(), kieServicesClientForContainer); <END> } } catch (Exception e) { e.printStackTrace(); logger.warn("Failed ot create kie server client for container due to {}", containerSpec.getId(), e.getMessage()); } } } KieServicesClient adminKieServicesClient = createClientForTemplate(serverTemplate, null, getAdminCredentialsProvider()); if (adminKieServicesClient != null) { adminClients.put(serverTemplate.getId(), adminKieServicesClient); } }</code><technical_language>a couple of places, this one, broke consistency of waterfall argument list</technical_language>

Target:
protected void buildClientsForServer(ServerTemplate serverTemplate) { KieServicesClient kieServicesClient = createClientForTemplate(serverTemplate, null, getCredentialsProvider()); if (kieServicesClient != null) { serverTemplatesClients.computeIfAbsent(serverTemplate.getId(), (k) -> new ConcurrentHashMap<String, KieServicesClient>()); serverTemplatesClients.get(serverTemplate.getId()).put(SERVER_TEMPLATE_KEY, kieServicesClient); } if (serverTemplate.getContainersSpec() != null) { for (ContainerSpec containerSpec : serverTemplate.getContainersSpec()) { try { if (serverTemplatesClients.get(serverTemplate.getId()).containsKey(containerSpec.getId())) { logger.debug("KieServerClient for is already created", containerSpec.getId()); continue; } KieContainer kieContainer = kieServices.newKieContainer(containerSpec.getReleasedId()); KieServicesClient kieServicesClientForContainer = createClientForTemplate(serverTemplate, kieContainer.getClassLoader(), getCredentialsProvider()); if (kieServicesClient != null) { serverTemplatesClients.get(serverTemplate.getId()).put(containerSpec.getId(), kieServicesClientForContainer); } } catch (Exception e) { logger.warn("Failed ot create kie server client for container due to {}", containerSpec.getId(), e.getMessage()); } } } KieServicesClient adminKieServicesClient = createClientForTemplate(serverTemplate, null, getAdminCredentialsProvider()); if (adminKieServicesClient != null) { adminClients.put(serverTemplate.getId(), adminKieServicesClient); } }
Source:
<code>public Response<String> apply(IdentifiedUser user, Input input) throws MethodNotAllowedException, ResourceNotFoundException, OrmException { if (input == null) { input = new Input(); } ReviewDb db = dbProvider.get(); Account a = db.accounts().get(user.getAccountId()); if (a == null) { throw new ResourceNotFoundException("account not found"); } <START> if (!realm.allowsEdit(FieldName.FULL_NAME)) { if (realm instanceof LdapRealm && db.accountExternalIds().get( new AccountExternalId.Key(SCHEME_GERRIT, a.getUserName())) == null) { } else { throw new MethodNotAllowedException("realm does not allow editing name"); } } <END> a.setFullName(input.name); dbProvider.get().accounts().update(Collections.singleton(a)); byIdCache.evict(a.getId()); return Strings.isNullOrEmpty(a.getFullName()) ? Response.<String> none() : Response.ok(a.getFullName()); }</code><technical_language>write this a single if-statement</technical_language>

Target:
public Response<String> apply(IdentifiedUser user, Input input) throws MethodNotAllowedException, ResourceNotFoundException, OrmException { if (input == null) { input = new Input(); } ReviewDb db = dbProvider.get(); Account a = db.accounts().get(user.getAccountId()); if (a == null) { throw new ResourceNotFoundException("account not found"); } if (realm instanceof LdapRealm && db.accountExternalIds().get( new AccountExternalId.Key(SCHEME_GERRIT, a.getUserName())) == null) { } else if (!realm.allowsEdit(FieldName.FULL_NAME)) { throw new MethodNotAllowedException("realm does not allow editing name"); } a.setFullName(input.name); dbProvider.get().accounts().update(Collections.singleton(a)); byIdCache.evict(a.getId()); return Strings.isNullOrEmpty(a.getFullName()) ? Response.<String> none() : Response.ok(a.getFullName()); }
Source:
<code>public ScriptEngineShellTable(ScriptEngineManager scriptEngineManager, String engine) { <START> this.scriptEngine = scriptEngineManager.getEngineByName(engine); <END> }</code><technical_language>fail instead of silently returning null</technical_language>

Target:
public ScriptEngineShellTable(ScriptEngineManager scriptEngineManager, String engine) { this.scriptEngine = scriptEngineManager.getEngineByName(engine); if (scriptEngine == null) { throw new IllegalStateException("Unable to load script engine " + engine); } }
Source:
<code>public RSocketException(String message, @Nullable Throwable cause) { <START> super(0x00000201, message, cause); <END> }</code><technical_language>ErrorType.APPLICATION_ERROR here. In case, ref ErrorType suggestion super(ErrorType.APPLICATION_ERROR, message, cause);</technical_language>

Target:
public RSocketException(String message, @Nullable Throwable cause) { super(ErrorFrameFlyweight.APPLICATION_ERROR, message, cause); }
Source:
<code>public void onStart(){ <START> if(!DashboardActivity.dashboardActivity.isPreLoadSurveyOpenning()) { <END> SurveyDB.removeInProgress(); } }</code><technical_language>Please intent static methods for avoid memory leaks</technical_language>

Target:
public void onStart(){ SurveyDB.removeInProgress(); }
Source:
<code>public Value deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); if (node.get("distributionValue") != null) { <START> byte[] bytes = node.get("distributionValue").binaryValue(); ByteString byteString = ByteString.copyFrom(bytes); return Value.DistributionValue.create(byteString); <END> } if (node.get("doubleValue") != null) { double val = node.get("doubleValue").asDouble(); return Value.DoubleValue.create(val); } throw new RuntimeException("Unrecognized value type"); }</code><technical_language>if combine calls 1 line, JVM JIT able perform [return optimization](<LINK_0></technical_language>

Target:
public Value deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); if (node.get("distributionValue") != null) { byte[] bytes = node.get("distributionValue").binaryValue(); return Value.DistributionValue.create(ByteString.copyFrom(bytes)); } if (node.get("doubleValue") != null) { double val = node.get("doubleValue").asDouble(); return Value.DoubleValue.create(val); } throw new RuntimeException("Unrecognized value type"); }
Source:
<code>public int deleteScheduledExecutions(int maxRetainSecs) { if (maxRetainSecs < 0) { LOG.debug("scheduled executions retention is disabled"); return 0; } boolean committed = false; try (Query q = pm.newQuery(MScheduledExecution.class)) { openTransaction(); int maxCreateTime = (int) (System.currentTimeMillis() / 1000) - maxRetainSecs; q.setFilter("startTime <= maxCreateTime"); q.declareParameters("int maxCreateTime"); long deleted = q.deletePersistentAll(maxCreateTime); committed = commitTransaction(); return (int) deleted; <START> } catch (Exception e) { <END> throw new RuntimeException(e); } finally { if (!committed) { rollbackTransaction(); } } }</code><technical_language>is this catch needed</technical_language>

Target:
public int deleteScheduledExecutions(int maxRetainSecs) { if (maxRetainSecs < 0) { LOG.debug("scheduled executions retention is disabled"); return 0; } boolean committed = false; Query q = null; try { openTransaction(); int maxCreateTime = (int) (System.currentTimeMillis() / 1000) - maxRetainSecs; q = pm.newQuery(MScheduledExecution.class); q.setFilter("startTime <= maxCreateTime"); q.declareParameters("int maxCreateTime"); long deleted = q.deletePersistentAll(maxCreateTime); committed = commitTransaction(); return (int) deleted; } finally { rollbackAndCleanup(committed, q); } }
Source:
<code>public String getContinuationToken() { <START> return nextLink; <END> }</code><technical_language>Change this continuationToken</technical_language>

Target:
public String getContinuationToken() { return continuationToken; }
Source:
<code>void performCustomMigrationForMultiple() { ProjectId id1 = createId(1); ProjectId id2 = createId(2); ProjectId id3 = createId(3); TestProcessManagerRepository repository = repository(); TestProcessManager pm1 = new TestProcessManager(id1); TestProcessManager pm2 = new TestProcessManager(id2); TestProcessManager pm3 = new TestProcessManager(id3); repository.store(pm1); repository.store(pm2); repository.store(pm3); TargetFilters filters = targetFilters(Project.Column.name(), SetTestProcessName.NEW_NAME); Iterator<TestProcessManager> found = repository.find(filters, ResponseFormat.getDefaultInstance()); assertThat(found.hasNext()).isFalse(); repository.applyMigration(ImmutableSet.of(id1, id2), new SetTestProcessName()); Iterator<TestProcessManager> foundAfterMigration = repository.find(filters, ResponseFormat.getDefaultInstance()); ImmutableList<TestProcessManager> results = ImmutableList.copyOf(foundAfterMigration); assertThat(results).hasSize(2); assertThat(results) .comparingElementsUsing(stateWithPropagatedName()) <START> .containsExactly(pm1, pm2); <END> }</code><technical_language>migration nothing? comparing results PMs manually stored</technical_language>

Target:
void performCustomMigrationForMultiple() { ProjectId id1 = createId(1); ProjectId id2 = createId(2); ProjectId id3 = createId(3); TestProcessManagerRepository repository = repository(); TestProcessManager pm1 = new TestProcessManager(id1); TestProcessManager pm2 = new TestProcessManager(id2); TestProcessManager pm3 = new TestProcessManager(id3); repository.store(pm1); repository.store(pm2); repository.store(pm3); TargetFilters filters = targetFilters(Project.Column.name(), SetTestProcessName.NEW_NAME); Iterator<TestProcessManager> found = repository.find(filters, ResponseFormat.getDefaultInstance()); assertThat(found.hasNext()).isFalse(); repository.applyMigration(ImmutableSet.of(id1, id2), new SetTestProcessName()); Iterator<TestProcessManager> foundAfterMigration = repository.find(filters, ResponseFormat.getDefaultInstance()); ImmutableList<TestProcessManager> results = ImmutableList.copyOf(foundAfterMigration); Project expectedState1 = pm1 .state() .toBuilder() .setName(SetTestProcessName.NEW_NAME) .setIdString(pm1.getIdString()) .build(); Project expectedState2 = pm2 .state() .toBuilder() .setName(SetTestProcessName.NEW_NAME) .setIdString(pm2.getIdString()) .build(); assertThat(results).hasSize(2); assertThat(results) .comparingElementsUsing(entityState()) .containsExactly(expectedState1, expectedState2); }
Source:
<code><START> protected Map<String, Object> getStats(Protocol protocol){ <END> return stack.dumpStats(); }</code><technical_language>this need override</technical_language>

Target:
protected Map<String, Object> getStats(Protocol protocol){ return stack.dumpStats(protocol.getName(), null); }
Source:
<code>protected boolean authenticate(ContainerRequestContext requestContext, C credentials, String scheme) { try { if (credentials == null) { return false; } final Optional<P> principal = authenticator.authenticate(credentials); if (!principal.isPresent()) { return false; } <START> boolean secure = requestContext.getSecurityContext().isSecure(); <END> requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return principal.get(); } @Override public boolean isUserInRole(String role) { return authorizer.authorize(principal.get(), role); } @Override public boolean isSecure() { return secure; } @Override public String getAuthenticationScheme() { return scheme; } }); return true; } catch (AuthenticationException e) { logger.warn("Error authenticating credentials", e); throw new InternalServerErrorException(); } }</code><technical_language>this final</technical_language>

Target:
protected boolean authenticate(ContainerRequestContext requestContext, C credentials, String scheme) { try { if (credentials == null) { return false; } final Optional<P> principal = authenticator.authenticate(credentials); if (!principal.isPresent()) { return false; } final SecurityContext securityContext = requestContext.getSecurityContext(); final boolean secure = securityContext != null && securityContext.isSecure(); requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return principal.get(); } @Override public boolean isUserInRole(String role) { return authorizer.authorize(principal.get(), role); } @Override public boolean isSecure() { return secure; } @Override public String getAuthenticationScheme() { return scheme; } }); return true; } catch (AuthenticationException e) { logger.warn("Error authenticating credentials", e); throw new InternalServerErrorException(); } }
Source:
<code>int getNumHiddenSelected() { int numHidden = 0; for (Integer i: mSelectedPositions) { <START> if (i < mSites.size() && mSites.get(i).isHidden) { <END> numHidden++; } } return numHidden; }</code><technical_language>isValidPosition() instead</technical_language>

Target:
int getNumHiddenSelected() { int numHidden = 0; for (Integer i: mSelectedPositions) { if (isValidPosition(i) && mSites.get(i).isHidden) { numHidden++; } } return numHidden; }
Source:
<code>public void setUp() { manager = SerializableTransactionManager.create( mockKvs, mockTimelockService, null, null, () -> null, null, null, mockCleaner, mockInitializer, false, () -> 1L, <START> 8, END> 2, true); when(mockKvs.isInitialized()).thenReturn(true); when(mockTimelockService.isInitialized()).thenReturn(true); when(mockCleaner.isInitialized()).thenReturn(true); when(mockInitializer.isInitialized()).thenReturn(true); }</code><technical_language>some constants instead of repeated magic numbers</technical_language>

Target:
public void setUp() { manager = SerializableTransactionManager.create( mockKvs, mockTimelockService, null, null, () -> null, null, null, mockCleaner, mockInitializer, false, () -> 1L, TransactionTestConstants.GET_RANGES_THREAD_POOL_SIZE, TransactionTestConstants.DEFAULT_GET_RANGES_CONCURRENCY, true); when(mockKvs.isInitialized()).thenReturn(true); when(mockTimelockService.isInitialized()).thenReturn(true); when(mockCleaner.isInitialized()).thenReturn(true); when(mockInitializer.isInitialized()).thenReturn(true); }
Source:
<code>private PreambleHandler(Context context, FlowParameters parameters, @StringRes int buttonText) { mContext = context; mFlowParameters = parameters; mButtonText = buttonText; mLinkSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.fui_linkColor)); <START> setupCreateAccountPreamble(); <END> }</code><technical_language>move this call out of constructor static setup method well</technical_language>

Target:
private PreambleHandler(Context context, FlowParameters parameters, @StringRes int buttonText) { mContext = context; mFlowParameters = parameters; mButtonText = buttonText; mLinkSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.fui_linkColor)); }
Source:
<code>public static BingTile fromQuadKey(String quadKey) { int zoomLevel = quadKey.length(); int tileX = 0; int tileY = 0; for (int i = zoomLevel; i > 0; i--) { int mask = 1 << (i - 1); switch (quadKey.charAt(zoomLevel - i)) { case '0': break; <START> <END> case '1': tileX |= mask; break; case '2': tileY |= mask; break; case '3': tileX |= mask; tileY |= mask; break; default: throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid QuadKey digit sequence."); } } return new BingTile(tileX, tileY, zoomLevel); }</code><technical_language>Remove blank lines. "break" statement provides ample vertical space for readability</technical_language>

Target:
public static BingTile fromQuadKey(String quadKey) { int zoomLevel = quadKey.length(); checkArgument(zoomLevel <= MAX_ZOOM_LEVEL); int tileX = 0; int tileY = 0; for (int i = zoomLevel; i > 0; i--) { int mask = 1 << (i - 1); switch (quadKey.charAt(zoomLevel - i)) { case '0': break; case '1': tileX |= mask; break; case '2': tileY |= mask; break; case '3': tileX |= mask; tileY |= mask; break; default: throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid QuadKey digit sequence: " + quadKey); } } return new BingTile(tileX, tileY, zoomLevel); }
Source:
<code><START> public Response<Integer> breakLease() { <END> return this.breakLease(null, null, null); }</code><technical_language>this represented a Duration</technical_language>

Target:
public Response<Duration> breakLease() { return this.breakLease(null, null, null); }
Source:
<code>public Class<?> createFactory(Class<?> cls) { String newClassName = cls.getName() + "Factory"; try { return ClassLoaderUtils.loadClass(newClassName, FactoryClassLoader.class); <START> } catch (ClassNotFoundException e) { <END> } return null; }</code><technical_language>log exception (debug trace), troubleshooting</technical_language>

Target:
public Class<?> createFactory(Class<?> cls) { String newClassName = cls.getName() + "Factory"; return findClass(newClassName, cls); }