auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void doStart() { try { this.server.start(); } catch (Throwable exc) { LOG.error("Got unexpected exception while starting BookieServer", exc); if (uncaughtExceptionHandler != null) { <START> LOG.error("Calling uncaughtExceptionHandler"); <END> uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), exc); } else { throw new RuntimeException("Failed to start bookie server", exc); } } }</code><technical_language>nit: add more details this log line</technical_language>

Target:
protected void doStart() { try { this.server.start(); } catch (InterruptedException exc) { throw new RuntimeException("Failed to start bookie server", exc); } }
Source:
<code>public CacheHandler createCache() { ConcurrentMap<String, String> cache; String mapDbKey; while (true) { <START> mapDbKey = mapDbKeyCounter.getAndIncrement() + ""; <END> try { HTreeMap<String, String> hTreeMap = mmapDB.createHashMap(mapDbKey).make(); cache = new CacheProxy(hTreeMap); cacheCount.incrementAndGet(); break; } catch (IllegalArgumentException e) { } } MapDbCacheDisposer cacheDisposer = new MapDbCacheDisposer(mapDbKey); Cleaner cleaner = Cleaner.create(cache, cacheDisposer); MapDbCacheDisposerAndCleaner disposerAndCleaner = new MapDbCacheDisposerAndCleaner( cacheDisposer, cleaner ); return new CacheHandler(this, cache, disposerAndCleaner); }</code><technical_language>suggest Long.toString(mapDbKeyCounter.getAndIncrement())</technical_language>

Target:
public CacheHandler createCache() { ConcurrentMap<String, String> cache; String mapDbKey; while (true) { mapDbKey = Long.toString(mapDbKeyCounter.getAndIncrement()); try { HTreeMap<String, String> hTreeMap = mmapDB.createHashMap(mapDbKey).make(); cache = new CacheProxy(hTreeMap); cacheCount.incrementAndGet(); break; } catch (IllegalArgumentException e) { } } MapDbCacheDisposer cacheDisposer = new MapDbCacheDisposer(mapDbKey); Cleaner cleaner = Cleaner.create(cache, cacheDisposer); MapDbCacheDisposerAndCleaner disposerAndCleaner = new MapDbCacheDisposerAndCleaner( cacheDisposer, cleaner ); return new CacheHandler(this, cache, disposerAndCleaner); }
Source:
<code>public Image getIcon() { <START> return Pics.getImage("page.png", UIDesignerPlugin.getDefault()); <END> }</code><technical_language>a constants in PicsConstants for page.png</technical_language>

Target:
public Image getIcon() { return Pics.getImage(PAGE_ICON_PATH, UIDesignerPlugin.getDefault()); }
Source:
<code><START> public PrologEnvironment newPrologEnvironment() throws CompileException, IOException{ <END> PrologEnvironment env = envFactory.create(getClass().getClassLoader()); ObjectStream ruleStream; ruleStream = getPrologRules(); if (ruleStream != null) { try { PushbackReader in = new PushbackReader(new InputStreamReader(ruleStream, Charset.forName("UTF-8")), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.makeSymbol("rules.pl"), streamObject)) { throw new CompileException("Cannot consult " + getProject().getName() + " " + getConfig().getRevision()); } } finally { ruleStream.close(); } } else { VariableTerm var = new VariableTerm(); StructureTerm head = new StructureTerm("submit_rule", var); StructureTerm defaultRule = new StructureTerm(":", SymbolTerm.makeSymbol("com.google.gerrit.rules.common"), new StructureTerm("default_submit", var)); StructureTerm clause = new StructureTerm(":-", head, defaultRule); env.execute(Prolog.BUILTIN, "assertz", clause); } return env; }</code><technical_language>Instead of exporting IOException, lets wrap of a CompileException caller handle a ton of exception types</technical_language>

Target:
public PrologEnvironment newPrologEnvironment() throws CompileException { PrologEnvironment env = envFactory.create(getClass().getClassLoader()); String rules; try { rules = getPrologRules(); } catch (RepositoryNotFoundException err) { throw new CompileException("Local repository does not exist ", err); } if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.makeSymbol("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }
Source:
<code>private static void testDownloadLatestDbBackup() throws MambuApiException, IOException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); DatabaseService databaseService = MambuAPIFactory.getDatabaseService(); DatabaseBackup response = databaseService.downloadLatestDbBackup(); System.out.println("Backup was successfuly downloaded = " + (response.getContent().toByteArray() != null)); <START> <END> }</code><technical_language>Nice! optionally try/catch (and log) IO exceptions in this method</technical_language>

Target:
private static void testDownloadLatestDbBackup() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); DatabaseService databaseService = MambuAPIFactory.getDatabaseService(); DatabaseBackup response = databaseService.downloadLatestDbBackup(); System.out.println("Backup was successfuly downloaded = " + (response.getContent().toByteArray() != null)); }
Source:
<code>private void proceedGuaranteedMemoryCheck() { for (VmInternalData vmInternalData : _runningVms.values()) { VM savedVm = _vmDict.get(vmInternalData.getVmDynamic().getId()); if (vmInternalData.getVmStatistics().getCurrentMemory() != null && savedVm.getMinAllocatedMem() > vmInternalData.getVmStatistics().getCurrentMemory()) { AuditLogableBase auditLogable = new AuditLogableBase(); <START> auditLogable.setVmId(savedVm.getId()); <END> AuditLogDirector.log(auditLogable, AuditLogType.VM_MEMORY_UNDER_GUARANTEED_VALUE); } } }</code><technical_language>Please add current memory amount. Also, checking '>' please check getCurrentMemory is zero null</technical_language>

Target:
private void proceedGuaranteedMemoryCheck() { for (VmInternalData vmInternalData : _runningVms.values()) { VM savedVm = _vmDict.get(vmInternalData.getVmDynamic().getId()); VmStatistics vmStatistics = vmInternalData.getVmStatistics(); if (vmStatistics.getCurrentMemory() != null && savedVm.getMinAllocatedMem() > vmStatistics.getCurrentMemory()) { AuditLogableBase auditLogable = new AuditLogableBase(); auditLogable.addCustomValue("VmName", savedVm.getName()); auditLogable.addCustomValue("VdsName", this._vds.getName()); auditLogable.addCustomValue("MemGuaranteed", String.valueOf(savedVm.getMinAllocatedMem())); auditLogable.addCustomValue("MemActual", vmStatistics.getCurrentMemory().toString()); auditLog(auditLogable, AuditLogType.VM_MEMORY_UNDER_GUARANTEED_VALUE); } } }
Source:
<code>private void createTextMenu() { final MenuManager popupManager = new MenuManager(); textWidget.setMenu(popupManager.createContextMenu(textWidget)); <START> textWidget.addDisposeListener(e -> { <END> popupManager.dispose(); }); }</code><technical_language>{} ommited for single statement</technical_language>

Target:
private void createTextMenu() { final MenuManager popupManager = new MenuManager(); textWidget.setMenu(popupManager.createContextMenu(textWidget)); textWidget.addDisposeListener(e -> popupManager.dispose()); }
Source:
<code>protected void logToAudit(){ <START> super.logToAudit(); <END> if (isPolicyResetMessage(getReturnStatus().message)) { return; } AuditLogableBase auditLogableBase = new AuditLogableBase(vds.getId()); auditLogableBase.setVds(vds); auditLogableBase.addCustomValue("message", getReturnStatus().message); auditLogDirector.log(auditLogableBase, AuditLogType.VDS_BROKER_COMMAND_FAILURE); }</code><technical_language>This do think. base class a sholdLog() method, caller implement protected final void logToAudit() { if (shouldLog()) { realLogToAudit()); } }</technical_language>

Target:
protected void logToAudit(){ if (isPolicyResetMessage(getReturnStatus().message)) { return; } AuditLogableBase auditLogableBase = new AuditLogableBase(vds.getId()); auditLogableBase.setVds(vds); auditLogableBase.addCustomValue("message", getReturnStatus().message); auditLogDirector.log(auditLogableBase, AuditLogType.VDS_BROKER_COMMAND_FAILURE); }
Source:
<code>public Map<String, InputStream> getDomainFilesData( final String domainId ) { lock.readLock().lock(); try { if ( !metadataMapping.getDomainIds().contains( domainId ) ) { return emptyMap(); } Map<String, InputStream> localeFiles = ofNullable( metadataMapping.getLocaleFiles( domainId ) ).orElse( emptyMap() ).entrySet().stream() .collect( toMap( entry -> "messages_" + entry.getKey() + ".properties", item -> getRepositoryFileInputStream( item.getValue() ) ) ); <START> return ImmutableMap.<String, InputStream>builder() <END> .putAll( localeFiles ) .put( domainId, getRepositoryFileInputStream( metadataMapping.getDomainFile( domainId ) ) ) .build(); } finally { lock.readLock().unlock(); } }</code><technical_language>lost this part of logic related domainId in .xmi. do need it</technical_language>

Target:
public Map<String, InputStream> getDomainFilesData( final String domainId ) { lock.readLock().lock(); try { if ( !metadataMapping.getDomainIds().contains( domainId ) ) { return emptyMap(); } Map<String, InputStream> localeFiles = ofNullable( metadataMapping.getLocaleFiles( domainId ) ).orElse( emptyMap() ).entrySet().stream() .collect( toMap( entry -> "messages_" + entry.getKey() + ".properties", item -> getRepositoryFileInputStream( item.getValue() ) ) ); return ImmutableMap.<String, InputStream>builder() .putAll( localeFiles ) .put( getXmiFilename( domainId ), getRepositoryFileInputStream( metadataMapping.getDomainFile( domainId ) ) ) .build(); } finally { lock.readLock().unlock(); } }
Source:
<code>public final void updateMetadata(Path outputFile) { try { String location = outputFile.toAbsolutePath().toString(); NetcdfFileWriter nc = NetcdfFileWriter.openExisting(location); GridDataset gridDs = GridDataset.open(location); nc.setRedefineMode(true); <START> for (Attribute newAttr : getGlobalAttributesToUpdate(nc.getNetcdfFile())) { <END> nc.addGroupAttribute(null, newAttr); } nc.setRedefineMode(false); nc.close(); } catch (IOException e) { throw new GoGoDuckException(String.format("Failed updating metadata for file '%s': '%s'", outputFile, e.getMessage())); } }</code><technical_language>Need cater for collection specific metadata update currently performed for SRS</technical_language>

Target:
public final void updateMetadata(Path outputFile) throws Exception { NetcdfFileWriter nc = null; try { String location = outputFile.toAbsolutePath().toString(); nc = NetcdfFileWriter.openExisting(location); nc.setRedefineMode(true); for (Attribute newAttr : getGlobalAttributesToUpdate(nc.getNetcdfFile())) { nc.addGroupAttribute(null, newAttr); } nc.setRedefineMode(false); } catch (IOException e) { throw new GoGoDuckException(String.format("Failed updating metadata for file '%s': '%s'", outputFile, e.getMessage())); } finally { close(nc, NetcdfFileWriter.class); } }
Source:
<code>private void handleReviewResultErrors(final ReviewResult result) { for (ReviewResult.Error resultError : result.getErrors()) { String errMsg = "error: (change " + result.getChangeId() + ") "; switch (resultError.getType()) { case ABANDON_NOT_PERMITTED: errMsg += "not permitted to abandon change"; break; case RESTORE_NOT_PERMITTED: errMsg += "not permitted to restore change"; break; case SUBMIT_NOT_PERMITTED: errMsg += "not permitted to submit change"; break; case SUBMIT_NOT_READY: errMsg += "approvals or dependencies lacking"; break; case CHANGE_IS_CLOSED: errMsg += "change is closed"; break; case PUBLISH_NOT_PERMITTED: errMsg += "not permitted to publish change"; break; case DELETE_NOT_PERMITTED: <START> errMsg += "not permitted to delete change"; <END> break; case RULE_ERROR: errMsg += "rule error"; break; case GIT_ERROR: errMsg += "error writing change to git repository"; break; default: errMsg += "failure in review"; } if (resultError.getMessage() != null) { errMsg += ": " + resultError.getMessage(); } writeError(errMsg); } }</code><technical_language>[optional] this error occur a patch set deleted change message permitted delete change/patch set</technical_language>

Target:
private void handleReviewResultErrors(final ReviewResult result) { for (ReviewResult.Error resultError : result.getErrors()) { String errMsg = "error: (change " + result.getChangeId() + ") "; switch (resultError.getType()) { case ABANDON_NOT_PERMITTED: errMsg += "not permitted to abandon change"; break; case RESTORE_NOT_PERMITTED: errMsg += "not permitted to restore change"; break; case SUBMIT_NOT_PERMITTED: errMsg += "not permitted to submit change"; break; case SUBMIT_NOT_READY: errMsg += "approvals or dependencies lacking"; break; case CHANGE_IS_CLOSED: errMsg += "change is closed"; break; case PUBLISH_NOT_PERMITTED: errMsg += "not permitted to publish change"; break; case DELETE_NOT_PERMITTED: errMsg += "not permitted to delete change/patch set"; break; case RULE_ERROR: errMsg += "rule error"; break; case GIT_ERROR: errMsg += "error writing change to git repository"; break; default: errMsg += "failure in review"; } if (resultError.getMessage() != null) { errMsg += ": " + resultError.getMessage(); } writeError(errMsg); } }
Source:
<code>static String detail(Throwable t) { String detail = null; if (log.isDebugEnabled()) { StringWriter sw = new StringWriter(); detail = sw.toString(); <START> log.debug("", t); <END> } else { detail = t.getMessage(); } return detail; }</code><technical_language>This detail client</technical_language>

Target:
static String detail(Throwable t) { String detail = null; if (log.isDebugEnabled()) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw, true)); detail = sw.toString(); } else { detail = t.getMessage(); } return detail; }
Source:
<code>public void unbindWhenUnsubscribed() { Merlin merlin = mock(Merlin.class); Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); <START> verify(merlin, times(1)).unbind(); <END> }</code><technical_language>times(1) is necessary</technical_language>

Target:
public void unbindWhenUnsubscribed() { Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); verify(merlin).unbind(); }
Source:
<code>public Gml3ToWktImpl(Configuration gmlConfiguration) { parser = <START> ThreadLocal.withInitial( <END> () -> { Parser parser = new Parser(gmlConfiguration); parser.setStrict(false); return parser; }); }</code><technical_language>downside is of parser end existing in thread. Depending memory is retained parser loads configuration, issue (I know). Right do 2 instances of means 2 instances of parser thread</technical_language>

Target:
public Gml3ToWktImpl(Configuration gmlConfiguration) { parser = ThreadLocal.withInitial( () -> { Parser gmlParser = new Parser(gmlConfiguration); gmlParser.setStrict(false); return gmlParser; }); }
Source:
<code>public static VdcParameter deserialize(String key) { Map<String, String> map = new HashMap<String, String>(); for (String token : key.split(";")) { String[] keyVal = token.split("="); map.put(keyVal[0], keyVal[1]); } switch (Integer.parseInt(map.get(VERSION_KEY))) { case 0: synchronized (parametersMap) { <START> return parametersMap.get(new Guid(map.get(GUID_KEY))); <END> } default: throw new InvalidParameterKeyException(key); } }</code><technical_language>exception if available</technical_language>

Target:
public static VdcParameter deserialize(String key) { Map<String, String> map = new HashMap<String, String>(); for (String token : key.split(";")) { String[] keyVal = token.split("="); map.put(keyVal[0], keyVal[1]); } switch (Integer.parseInt(map.get(VERSION_KEY))) { case 0: synchronized (parametersMap) { Guid guid = new Guid(map.get(GUID_KEY)); if (!parametersMap.containsKey(guid)) { throw new InvalidParameterKeyException("VdcParameter with guid not found "+ guid.toString()); } return parametersMap.get(guid); } default: throw new InvalidParameterKeyException("Error deserializing VdcParameter from key " + key); } }
Source:
<code>public List<JavaFileScannerContext.Location> flow(int parameterIndex) { if(node == null || behavior == null) { return Lists.newArrayList(); } <START> return FlowComputation.flow(node, behavior.parameters().get(parameterIndex)); <END> }</code><technical_language>I expect this fail badly if try track return of method, part of parameters. (indexOutOfBound?) need get adequate symbolic in case (No failing test?! :-1: for me)</technical_language>

Target:
public List<JavaFileScannerContext.Location> flow(int parameterIndex) { if(node == null || behavior == null) { return Lists.newArrayList(); } if(parameterIndex < 0) { return FlowComputation.flow(node, node.programState.exitValue()); } return FlowComputation.flow(node, behavior.parameters().get(parameterIndex)); }
Source:
<code>private PRPAIN201306UV02 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) throws PatientDiscoveryException { AdapterPatientDiscoveryProxy proxy = adapterFactory.create(); <START> return proxy.respondingGatewayPRPAIN201305UV02(request, assertion); <END> }</code><technical_language>Simplify this line</technical_language>

Target:
private PRPAIN201306UV02 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) throws PatientDiscoveryException { return adapterFactory.create().respondingGatewayPRPAIN201305UV02(request, assertion); }
Source:
<code>protected Rectangle getBox() { PrecisionRectangle rBox = null; <START> if ((getOwner().getChildren().get(0)) instanceof IRoundedRectangleFigure) { <END> rBox = new PrecisionRectangle(((IRoundedRectangleFigure) ((IFigure) getOwner().getChildren().get(0))).getRoundedRectangleBounds()); } else if ((getOwner().getChildren().get(0)) instanceof IFigure) { rBox = new PrecisionRectangle(((IFigure) getOwner()).getBounds()); } ((IFigure) getOwner().getChildren().get(0)).translateToAbsolute(rBox); return rBox.expand(offset.width, offset.height); }</code><technical_language>a local variable firstFigure</technical_language>

Target:
protected Rectangle getBox() { PrecisionRectangle rBox = null; Object figure = getFigure(); if (figure instanceof IRoundedRectangleFigure) { rBox = new PrecisionRectangle(((IRoundedRectangleFigure) ((IFigure) figure)).getRoundedRectangleBounds()); } else if (figure instanceof IFigure) { rBox = new PrecisionRectangle(((IFigure) getOwner()).getBounds()); } ((IFigure) figure).translateToAbsolute(rBox); return rBox.expand(offset.width, offset.height); }
Source:
<code>private void insertMetricsInBatch(Multimap<Locator, IMetric> map, Granularity granularity) { BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED); for (Locator locator : map.keySet()) { <START> for (IMetric metric : map.get(locator)) { <END> RollupType rollupType = metric.getRollupType(); DAbstractMetricIO io = rollupTypeToIO.get(rollupType); BoundStatement boundStatement = io.getBoundStatementForMetric(metric, granularity); batch.add(boundStatement); if( !LocatorCache.getInstance().isLocatorCurrentInBatchLayer(locator) ) { LocatorCache.getInstance().setLocatorCurrentInBatchLayer(locator); batch.add(locatorIO.getBoundStatementForLocator( locator )); } if ( isRecordingDelayedMetrics ) { BoundStatement bs = getBoundStatementForMetricIfDelayed(metric); if ( bs != null ) { batch.add(bs); } } } } LOG.trace(String.format("insert preaggregated batch statement size=%d", batch.size())); try { DatastaxIO.getSession().execute(batch); } catch ( Exception ex ) { Instrumentation.markWriteError(); LOG.error(String.format("error writing batch of %d preaggregated metrics", batch.size()), ex ); } }</code><technical_language>Instrumentation call here</technical_language>

Target:
private void insertMetricsInBatch(Multimap<Locator, IMetric> map, Granularity granularity) { BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED); for (Locator locator : map.keySet()) { for (IMetric metric : map.get(locator)) { RollupType rollupType = metric.getRollupType(); DAbstractMetricIO io = rollupTypeToIO.get(rollupType); BoundStatement boundStatement = io.getBoundStatementForMetric(metric, granularity); batch.add(boundStatement); if (granularity == Granularity.FULL) { Instrumentation.markFullResPreaggregatedMetricWritten(); } if( !LocatorCache.getInstance().isLocatorCurrentInBatchLayer(locator) ) { LocatorCache.getInstance().setLocatorCurrentInBatchLayer(locator); batch.add(locatorIO.getBoundStatementForLocator( locator )); } if ( isRecordingDelayedMetrics ) { BoundStatement bs = getBoundStatementForMetricIfDelayed(metric); if ( bs != null ) { batch.add(bs); } } } } LOG.trace(String.format("insert preaggregated batch statement size=%d", batch.size())); try { DatastaxIO.getSession().execute(batch); } catch ( Exception ex ) { Instrumentation.markWriteError(); LOG.error(String.format("error writing batch of %d preaggregated metrics", batch.size()), ex ); } }
Source:
<code>public void run(CombinedTimeLockServerConfiguration configuration, Environment environment) throws JsonProcessingException { environment.getObjectMapper() .registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()); environment.jersey().register(ConjureJerseyFeature.INSTANCE); environment.jersey().register(new EmptyOptionalTo204ExceptionMapper()); MetricsManager metricsManager = MetricsManagers.of(environment.metrics(), taggedMetricRegistry); Consumer<Object> registrar = component -> environment.jersey().register(component); log.error("Paxos configuration\n{}", environment.getObjectMapper() .writerWithDefaultPrettyPrinter() <START> .writeValueAsString(configuration.install().paxos())); <END> TimeLockAgent timeLockAgent = TimeLockAgent.create( metricsManager, configuration.install(), configuration::runtime, USER_AGENT, CombinedTimeLockServerConfiguration.threadPoolSize(), CombinedTimeLockServerConfiguration.blockingTimeoutMs(), registrar); environment.lifecycle().manage(new Managed() { @Override public void start() { } @Override public void stop() { timeLockAgent.shutdown(); } }); }</code><technical_language>I guess this is fine this is in testing, is this intentional? if want this ERROR is pretty harsh</technical_language>

Target:
public void run(CombinedTimeLockServerConfiguration configuration, Environment environment) throws JsonProcessingException { environment.getObjectMapper() .registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()); environment.jersey().register(ConjureJerseyFeature.INSTANCE); environment.jersey().register(new EmptyOptionalTo204ExceptionMapper()); MetricsManager metricsManager = MetricsManagers.of(environment.metrics(), taggedMetricRegistry); Consumer<Object> registrar = component -> environment.jersey().register(component); log.info("Paxos configuration\n{}", environment.getObjectMapper() .writerWithDefaultPrettyPrinter() .writeValueAsString(configuration.install().paxos())); TimeLockAgent timeLockAgent = TimeLockAgent.create( metricsManager, configuration.install(), configuration::runtime, USER_AGENT, CombinedTimeLockServerConfiguration.threadPoolSize(), CombinedTimeLockServerConfiguration.blockingTimeoutMs(), registrar); environment.lifecycle().manage(new Managed() { @Override public void start() { } @Override public void stop() { timeLockAgent.shutdown(); } }); }
Source:
<code>public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { String id = (String) attribute.getValue(); if (id == null) { <START> throw new WrongAttributeValueException(attribute, resource, "Attribute can't be empty."); <END> } Matcher match = pattern.matcher(id); if (!match.matches()) { throw new WrongAttributeValueException(attribute, resource, "Bad format of attribute redmineProjectID. It can start with a-z and then a-z, 0-9, _ or -"); } }</code><technical_language>Please add suggestion attribute is correct error message. line is suitable</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { String id = (String) attribute.getValue(); if (id == null) { throw new WrongAttributeValueException(attribute, resource, "Attribute can't be empty. It can start with a-z and then a-z, 0-9, _ or -"); } Matcher match = pattern.matcher(id); if (!match.matches()) { throw new WrongAttributeValueException(attribute, resource, "Bad format of attribute redmineProjectID. It can start with a-z and then a-z, 0-9, _ or -"); } }
Source:
<code>String getLabel() { <START> return "Staged"; END> }</code><technical_language>label externalized</technical_language>

Target:
String getLabel() { return UIText.StagedNode_Label; }
Source:
<code>public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { String path = request.getPathInfo(); <START> String fullPath = getFullPath(brandingManager.getBrandingRootPath().getAbsolutePath(), path); <END> if (fullPath != null) { File file = new File(fullPath); if (!file.exists() || !file.canRead() || file.isDirectory()) { log.error("Unable to retrieve file: " + file.getAbsolutePath() + ", will send a 404 error response."); response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { String etag = generateEtag(file); if (etag.equals(request.getHeader(GwtDynamicHostPageServlet. IF_NONE_MATCH_HEADER))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { String mime = ServletUtils.getMimeMap(). getContentType(file); response.addHeader(GwtDynamicHostPageServlet.ETAG_HEADER, etag); ServletUtils.sendFile(request, response, file, mime); } } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } }</code><technical_language>I Path File is strings</technical_language>

Target:
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { String path = request.getPathInfo(); String fullPath = getFullPath(brandingManager.getBrandingRootPath(), path); if (fullPath != null) { File file = new File(fullPath); if (!file.exists() || !file.canRead() || file.isDirectory()) { log.error("Unable to retrieve file: " + file.getAbsolutePath() + ", will send a 404 error response."); response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { String etag = generateEtag(file); if (etag.equals(request.getHeader(GwtDynamicHostPageServlet. IF_NONE_MATCH_HEADER))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { String mime = ServletUtils.getMimeMap(). getContentType(file); response.addHeader(GwtDynamicHostPageServlet.ETAG_HEADER, etag); ServletUtils.sendFile(request, response, file, mime); } } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Source:
<code>public Response doExport(Action action) { validateParameters(action, "storageDomain.id|name"); try { ExportRepoImageParameters exportParameters = DiskHelper.getExportRepoImageParameters(getDisk(), getStorageDomainId(action)); return doAction(VdcActionType.ExportRepoImage, exportParameters, action); } catch (Exception e) { return handleError(e, action); <START> } <END> }</code><technical_language>need for failover treatment, this is done infra, return doAction()</technical_language>

Target:
public Response doExport(Action action) { validateParameters(action, "storageDomain.id|name"); Disk disk = getDisk(); Guid sourceStorageDomainId = new Guid(disk.getStorageDomains().getStorageDomains().get(0).getId()); Guid sourceStoragePoolId = StorageDomainHelper.getStoragePoolIdForDomain(this, sourceStorageDomainId); ExportRepoImageParameters exportParameters = new ExportRepoImageParameters(new Guid(disk.getImageId())); exportParameters.setStoragePoolId(sourceStoragePoolId); exportParameters.setStorageDomainId(sourceStorageDomainId); exportParameters.setImageGroupID(new Guid(disk.getId())); exportParameters.setDestinationDomainId(getStorageDomainId(action)); return doAction(VdcActionType.ExportRepoImage, exportParameters, action); }
Source:
<code>protected void processFiltered(File file, FileText fileText) throws CheckstyleException { if (CommonUtils.matchesFileExtension(file, getFileExtensions())) { final String msg = "%s occurred during the analysis of file %s."; final String fileName = file.getPath(); final FileContents contents = new FileContents(fileText); try { if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) { final DetailAST rootAST = parse(contents); if (!ordinaryChecks.isEmpty()) { <START> walk(rootAST, contents, AstState.ORDINARY); <END> } if (!commentChecks.isEmpty()) { final DetailAST astWithComments = appendHiddenCommentNodes(rootAST); walk(astWithComments, contents, AstState.WITH_COMMENTS); } } final SortedSet<LocalizedMessage> filteredMessages = getFilteredMessages(fileName, contents); addMessages(filteredMessages); messages.clear(); } catch (final TokenStreamRecognitionException tre) { final String exceptionMsg = String.format(Locale.ROOT, msg, "TokenStreamRecognitionException", fileName); throw new CheckstyleException(exceptionMsg, tre); } catch (RecognitionException | TokenStreamException ex) { final String exceptionMsg = String.format(Locale.ROOT, msg, ex.getClass().getSimpleName(), fileName); throw new CheckstyleException(exceptionMsg, ex); } } }</code><technical_language>@timurt So, FileContext holder position restored. closer usage</technical_language>

Target:
protected void processFiltered(File file, FileText fileText) throws CheckstyleException { if (CommonUtils.matchesFileExtension(file, getFileExtensions())) { final String msg = "%s occurred during the analysis of file %s."; final String fileName = file.getPath(); try { if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) { final FileContents contents = new FileContents(fileText); final DetailAST rootAST = parse(contents); if (!ordinaryChecks.isEmpty()) { walk(rootAST, contents, AstState.ORDINARY); } if (!commentChecks.isEmpty()) { final DetailAST astWithComments = appendHiddenCommentNodes(rootAST); walk(astWithComments, contents, AstState.WITH_COMMENTS); } final SortedSet<LocalizedMessage> filteredMessages = getFilteredMessages(fileName, contents); addMessages(filteredMessages); messages.clear(); } } catch (final TokenStreamRecognitionException tre) { final String exceptionMsg = String.format(Locale.ROOT, msg, "TokenStreamRecognitionException", fileName); throw new CheckstyleException(exceptionMsg, tre); } catch (RecognitionException | TokenStreamException ex) { final String exceptionMsg = String.format(Locale.ROOT, msg, ex.getClass().getSimpleName(), fileName); throw new CheckstyleException(exceptionMsg, ex); } } }
Source:
<code>private static List<String> templateClasspathFor(File projectDir) { ProjectConnection connection = null; try { connection = GradleConnector.newConnector() .forProjectDirectory(projectDir) <START> .useDistribution(new URI("<LINK_0>")) <END> .connect(); KotlinBuildScriptModel model = connection.getModel(KotlinBuildScriptModel.class); List<String> classpath = Lists.newArrayList(); for (File entry : model.getClassPath()) { if (!entry.getName().startsWith("groovy")) { classpath.add(entry.getAbsolutePath()); } } return classpath; } catch (Exception e) { throw new RuntimeException(e); } finally { if (connection != null) { connection.close(); } } }</code><technical_language>Do need a special distribution Kotlin? I thought this worked standard Gradle distros? is in project settings</technical_language>

Target:
private static List<String> templateClasspathFor(File projectDir) { WorkspaceConfiguration config = CorePlugin.workspaceConfigurationManager().loadWorkspaceConfiguration(); KotlinBuildScriptModel model = KotlinModelQuery.execute(projectDir, GradleDistributionSerializer.INSTANCE.serializeToString(GradleDistribution.fromBuild()), config.getGradleUserHome(), config.isOffline()); List<String> classpath = Lists.newArrayList(); for (File entry : model.getClassPath()) { if (!entry.getName().startsWith("groovy")) { classpath.add(entry.getAbsolutePath()); } } return classpath; }
Source:
<code>public Object loadObject(EntityProjection projection, Serializable id, RequestScope scope) { Class<?> entityClass = projection.getType(); FilterExpression filterExpression = projection.getFilterExpression(); try { EntityDictionary dictionary = scope.getDictionary(); Class<?> idType = dictionary.getIdType(entityClass); String idField = dictionary.getIdFieldName(entityClass); FilterPredicate idExpression; Path.PathElement idPath = new Path.PathElement(entityClass, idType, idField); if (id != null) { idExpression = new FilterPredicate(idPath, Operator.IN, Collections.singletonList(id)); } else { idExpression = new FilterPredicate(idPath, Operator.FALSE, Collections.emptyList()); } FilterExpression joinedExpression = (filterExpression != null) ? new AndFilterExpression(filterExpression, idExpression) : idExpression; projection = projection .copyOf() .filterExpression(joinedExpression) .build(); QueryWrapper query = (QueryWrapper) new RootCollectionFetchQueryBuilder(projection, dictionary, emWrapper) .build(); EntityGraph entityGraph = createEntityGraph(scope, projection); if (scope.getElideSettings() != null && scope.getElideSettings().isEnableJPAFetchToManyRelationship() <START> && entityGraph != null) { <END> return query.getQuery() .setHint("javax.persistence.loadgraph", entityGraph) .getSingleResult(); } else { return query.getQuery() .getSingleResult(); } } catch (NoResultException e) { return null; } }</code><technical_language>Move construction of graph this if block</technical_language>

Target:
public Object loadObject(EntityProjection projection, Serializable id, RequestScope scope) { Class<?> entityClass = projection.getType(); FilterExpression filterExpression = projection.getFilterExpression(); try { EntityDictionary dictionary = scope.getDictionary(); Class<?> idType = dictionary.getIdType(entityClass); String idField = dictionary.getIdFieldName(entityClass); FilterPredicate idExpression; Path.PathElement idPath = new Path.PathElement(entityClass, idType, idField); if (id != null) { idExpression = new FilterPredicate(idPath, Operator.IN, Collections.singletonList(id)); } else { idExpression = new FilterPredicate(idPath, Operator.FALSE, Collections.emptyList()); } FilterExpression joinedExpression = (filterExpression != null) ? new AndFilterExpression(filterExpression, idExpression) : idExpression; projection = projection .copyOf() .filterExpression(joinedExpression) .build(); QueryWrapper query = (QueryWrapper) new RootCollectionFetchQueryBuilder(projection, dictionary, emWrapper) .build(); if (scope.getElideSettings() != null && scope.getElideSettings().isUseJpaEntityGraphHint()) { return query.getQuery() .setHint("javax.persistence.loadgraph", createEntityGraph(scope, projection)) .getSingleResult(); } else { return query.getQuery() .getSingleResult(); } } catch (NoResultException e) { return null; } }
Source:
<code>public FeedbackSessionAttributes getCopy() { <START> return builder(feedbackSessionName, courseId, creatorEmail) <END> .withInstructions(instructions) .withCreatedTime(createdTime) .withStartTime(startTime) .withEndTime(endTime) .withSessionVisibleFromTime(sessionVisibleFromTime) .withResultsVisibleFromTime(resultsVisibleFromTime) .withTimeZone(timeZone) .withGracePeriod(gracePeriod) .withFeedbackSessionType(feedbackSessionType) .withSentOpenEmail(sentOpenEmail) .withSentClosingEmail(sentClosingEmail) .withSentClosedEmail(sentClosedEmail) .withSentPublishedEmail(sentPublishedEmail) .withOpeningEmailEnabled(isOpeningEmailEnabled) .withPublishedEmailEnabled(isPublishedEmailEnabled) .withRespondingInstructorList(respondingInstructorList) .withRespondingStudentList(respondingStudentList) .withClosingEmailEnabled(isClosingEmailEnabled) .build(); }</code><technical_language>this(toEntity()) (essentially convert entity attributes) work? If works, significantly reduces repetition</technical_language>

Target:
public FeedbackSessionAttributes getCopy() { return valueOf(toEntity()); }
Source:
<code>public void performSearchNoDoiCitingMode() throws FetcherException { <START> assertThrows(FetcherException.class, () -> openCitationFetcher.searchCiting(new BibEntry())); <END> }</code><technical_language>throw exception here, instead of simply returning empty</technical_language>

Target:
public void performSearchNoDoiCitingMode() throws FetcherException { assertEquals(Collections.emptyList(), openCitationFetcher.searchCiting(new BibEntry())); }
Source:
<code>public void testMac_correctAlias() throws Exception { Provider androidOpenSSLProvider = Security.getProvider("AndroidOpenSSL"); <START> assertFalse("HmacSHA256".equals( <END> androidOpenSSLProvider.get("Alg.Alias.Mac.1.2.840.113549.2.9"))); assertEquals("HmacSHA256", androidOpenSSLProvider.get("Alg.Alias.Mac.1.2.840.113549.2.8")); }</code><technical_language>this assertTrue</technical_language>

Target:
public void testMac_correctAlias() throws Exception { Provider androidOpenSSLProvider = Security.getProvider("AndroidOpenSSL"); assertFalse("HmacSHA224".equals( androidOpenSSLProvider.get("Alg.Alias.Mac.1.2.840.113549.2.9"))); assertEquals("HmacSHA224", androidOpenSSLProvider.get("Alg.Alias.Mac.1.2.840.113549.2.8")); }
Source:
<code>public static Boolean equals( @OperatorDependency(operator = EQUAL, returnType = StandardTypes.BOOLEAN, argumentTypes = {"E", "E"}) MethodHandle equalsFunction, @TypeParameter("E") Type type, @SqlType("array(E)") Block leftArray, @SqlType("array(E)") Block rightArray) { if (leftArray.getPositionCount() != rightArray.getPositionCount()) { return false; } <START> boolean foundNull = false; <END> for (int i = 0; i < leftArray.getPositionCount(); i++) { if (leftArray.isNull(i) || rightArray.isNull(i)) { foundNull = true; continue; } Object leftElement = readNativeValue(type, leftArray, i); Object rightElement = readNativeValue(type, rightArray, i); try { Boolean result = (Boolean) equalsFunction.invoke(leftElement, rightElement); if (result == null) { foundNull = true; } else if (!result) { return false; } } catch (Throwable t) { throw internalError(t); } } if (foundNull) { return null; } return true; }</code><technical_language>Call this indeterminate maybe? foundNull is a misleading lines 59-62</technical_language>

Target:
public static Boolean equals( @OperatorDependency(operator = EQUAL, returnType = StandardTypes.BOOLEAN, argumentTypes = {"E", "E"}) MethodHandle equalsFunction, @TypeParameter("E") Type type, @SqlType("array(E)") Block leftArray, @SqlType("array(E)") Block rightArray) { if (leftArray.getPositionCount() != rightArray.getPositionCount()) { return false; } boolean indeterminate = false; for (int i = 0; i < leftArray.getPositionCount(); i++) { if (leftArray.isNull(i) || rightArray.isNull(i)) { indeterminate = true; continue; } Object leftElement = readNativeValue(type, leftArray, i); Object rightElement = readNativeValue(type, rightArray, i); try { Boolean result = (Boolean) equalsFunction.invoke(leftElement, rightElement); if (result == null) { indeterminate = true; } else if (!result) { return false; } } catch (Throwable t) { throw internalError(t); } } if (indeterminate) { return null; } return true; }
Source:
<code>public void cleanup() throws InterruptedException, IOException, StoreException { state.destroy(); assertTrue(tempDir.getAbsolutePath() + " could not be deleted", StoreTestUtils.cleanDirectory(tempDir, true)); <START> indexScannerScheduler.shutdown(); <END> if (!indexScannerScheduler.awaitTermination(1000, TimeUnit.MILLISECONDS)) { fail("Could not terminate index scanner task after BlobStoreStats shutdown"); } queueProcessorScheduler.shutdown(); if (!queueProcessorScheduler.awaitTermination(1000, TimeUnit.MILLISECONDS)) { fail("Could not terminate queue processor task after BlobStoreStats shutdown"); } }</code><technical_language>shutdown schedulers cleanup directory</technical_language>

Target:
public void cleanup() throws InterruptedException, IOException, StoreException { indexScannerScheduler.shutdown(); if (!indexScannerScheduler.awaitTermination(1000, TimeUnit.MILLISECONDS)) { fail("Could not terminate index scanner task after BlobStoreStats shutdown"); } queueProcessorScheduler.shutdown(); if (!queueProcessorScheduler.awaitTermination(1000, TimeUnit.MILLISECONDS)) { fail("Could not terminate queue processor task after BlobStoreStats shutdown"); } state.destroy(); assertTrue(tempDir.getAbsolutePath() + " could not be deleted", StoreTestUtils.cleanDirectory(tempDir, true)); }
Source:
<code>public List<RepositoryView> getAllRepositories() { final List<MavenPomElementView> list = resolveXPathToAggregatedElementViewList( "/project final List<RepositoryView> result = new ArrayList<RepositoryView>( list.size() ); for ( final MavenPomElementView node : list ) { if ( node == null ) { continue; } <START> RepositoryView repoDeclaration = <END> new RepositoryView( node.getPomView(), node.getElement(), node.getOriginInfo() ); if ( repoDeclaration.getProfileId() != null ) { continue; } result.add( repoDeclaration ); } return result; }</code><technical_language>Actually, put this in a new method, called like: public List<RepositoryView> getNonProfileRepositories() getAllRepositories implies return repo declaration in pom.xml...and this change alters logic</technical_language>

Target:
public List<RepositoryView> getAllRepositories() { final List<MavenPomElementView> list = resolveXPathToAggregatedElementViewList( "/project final List<RepositoryView> result = new ArrayList<RepositoryView>( list.size() ); for ( final MavenPomElementView node : list ) { if ( node == null ) { continue; } result.add( new RepositoryView( node.getPomView(), node.getElement(), node.getOriginInfo() ) ); } return result; }
Source:
<code>public String toString() { return "GlobalConfigurationBuilder{" + "evictionExecutorThreadPool=" + evictionThreadPool + <START> "listenerExecutorThreadPool=" + listenerThreadPool + <END> ", cl=" + cl + ", transport=" + transport + ", globalJmxStatistics=" + globalJmxStatistics + ", serialization=" + serialization + ", replicationQueueThreadPool=" + replicationQueueThreadPool + ", persistenceThreadPool=" + persistenceThreadPool + ", security=" + security + ", shutdown=" + shutdown + ", site=" + site + '}'; }</code><technical_language>, is missing :)</technical_language>

Target:
public String toString() { return "GlobalConfigurationBuilder{" + "evictionExecutorThreadPool=" + evictionThreadPool + ", listenerExecutorThreadPool=" + listenerThreadPool + ", cl=" + cl + ", transport=" + transport + ", globalJmxStatistics=" + globalJmxStatistics + ", serialization=" + serialization + ", replicationQueueThreadPool=" + replicationQueueThreadPool + ", persistenceThreadPool=" + persistenceThreadPool + ", security=" + security + ", shutdown=" + shutdown + ", site=" + site + '}'; }
Source:
<code>public SaveParticipantPlugin() { <START> super(); <END> deltaVerifier = new ResourceDeltaVerifier(); }</code><technical_language>This change is removing org.eclipse.core.runtime.compatibility* bundles</technical_language>

Target:
public SaveParticipantPlugin() { deltaVerifier = new ResourceDeltaVerifier(); }
Source:
<code>public void update(CruiseConfig modifiedConfig) throws Exception { PipelineTemplateConfig existingTemplateConfig = findAddedTemplate(modifiedConfig); TemplatesConfig templatesConfig = modifiedConfig.getTemplates(); existingTemplateConfig.setAuthorization(templateConfig.getAuthorization()); <START> modifiedConfig.setTemplates(templatesConfig); <END> }</code><technical_language>I understand need get templates config set again, is this required</technical_language>

Target:
public void update(CruiseConfig modifiedConfig) throws Exception { PipelineTemplateConfig existingTemplateConfig = findAddedTemplate(modifiedConfig); existingTemplateConfig.setAuthorization(authorization); }
Source:
<code>public void setScore(int score) { this.score = score; update(); <START> revalidate(); <END> }</code><technical_language>Move update please. < layout</technical_language>

Target:
public void setScore(int score) { this.score = score; update(); }
Source:
<code>public void testListScheduledMessages() throws Exception { Map<String, Object> filters = new LinkedHashMap<>(); filters.put("status", "scheduled"); <START> final MessageList list = messageBirdClient.listMessagesFiltered(null, null, filters); <END> assertNotNull(list.getOffset()); assertNotNull(list.getLinks()); assertNotNull(list.getTotalCount()); assertNotNull(list.getLinks()); }</code><technical_language>create example test list assert values testListNumbersForPurchase, testListWebhooks etc</technical_language>

Target:
public void testListScheduledMessages() throws Exception { final MessageList mockedResponse = new MessageList(); MessageBirdService messageBirdServiceMock = mock(MessageBirdService.class); MessageBirdClient messageBirdClientMock = new MessageBirdClient(messageBirdServiceMock); Map<String, Object> filters = new LinkedHashMap<>(); filters.put("status", "scheduled"); when(messageBirdServiceMock.requestList("/messages", filters, null, null, MessageList.class)) .thenReturn(mockedResponse); final MessageList response = messageBirdClientMock.listMessagesFiltered(null, null, filters); assertNotNull(response); assertEquals(response, mockedResponse); }
Source:
<code>public T decode(Object input) { if (input == null) { return null; } ValueWrapper data = (ValueWrapper) input; ByteArrayInputStream bais = new ByteArrayInputStream(data.getValue()); try { try (ObjectInputStream ois = (whiteListedClasses != null) ? new WhiteListObjectInputStream(bais, whiteListedClasses) : new ObjectInputStream(bais)) { @SuppressWarnings("unchecked") T result = (T) ois.readObject(); return result; } catch (InvalidClassException e) { <START> throw new RuntimeException(e.getMessage()); <END> } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load class", e); } } catch(IOException e) { } throw new AssertionError("Cannot reach here!"); }</code><technical_language>obscuring stacktrace? wrap exception</technical_language>

Target:
public T decode(Object input) { if (input == null) { return null; } ValueWrapper data = (ValueWrapper) input; ByteArrayInputStream bais = new ByteArrayInputStream(data.getValue()); try (ObjectInputStream ois = new FilteredObjectInputStream(bais, isClassPermitted, classLoader)) { @SuppressWarnings("unchecked") T result = (T) ois.readObject(); return result; } catch (ClassNotFoundException | IOException e) { throw new RuntimeException("Could not load class", e); } }
Source:
<code>public HelloWorldElement() { super(ElementFactory.createDiv()); UI.getCurrent().getPage().addHtmlImport( "frontend://bower_components/paper-input/paper-input.html"); Element input = new Element("paper-input"); Element greeting = ElementFactory.createDiv(); updateGreeting(input, greeting); input.synchronizeProperty("value", "value-changed"); input.addPropertyChangeListener("value", event -> updateGreeting(input, greeting)); input.setAttribute("id", "inputId"); greeting.setAttribute("id", "elementsGreeting"); <START> getElement().appendChild(input, greeting); <END> }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Remove this call a constructor overridable "getElement" method. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public HelloWorldElement() { super(ElementFactory.createDiv()); UI.getCurrent().getPage().addHtmlImport( "frontend://bower_components/paper-input/paper-input.html"); Element input = new Element("paper-input"); Element greeting = ElementFactory.createDiv(); updateGreeting(input, greeting); input.synchronizeProperty(VALUE_PROPERTY, "value-changed"); input.addPropertyChangeListener(VALUE_PROPERTY, event -> updateGreeting(input, greeting)); input.setAttribute("id", "inputId"); greeting.setAttribute("id", "elementsGreeting"); getElement().appendChild(input, greeting); }
Source:
<code><START> boolean isUriValid(String uri) { <END> String URL_PATTERN = "^/?(.*/)?(ac/|cas/)([a-f0-9]{64})$"; Matcher matcher = Pattern.compile(URL_PATTERN).matcher(uri); return matcher.matches(); }</code><technical_language>static</technical_language>

Target:
static boolean isUriValid(String uri) { Matcher matcher = URI_PATTERN.matcher(uri); return matcher.matches(); }