auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Set<AccountGroup.Id> groupsFor( SchemaFactory<ReviewDb> dbfactory, String[] groupNames, Logger log, String groupNotFoundWarning) { final Set<AccountGroup.Id> result = new HashSet<AccountGroup.Id>(); try { final ReviewDb db = dbfactory.open(); try { for (String name : groupNames) { AccountGroupName group = db.accountGroupNames().get(new AccountGroup.NameKey(name)); if (group == null) { log.warn(MessageFormat.format(groupNotFoundWarning, name)); } else { result.add(group.getId()); } } } finally { db.close(); } } catch (OrmException e) { <START> log.error("Database error: " + e); <END> } return result; }</code><technical_language>log.error("Database error, load groups", e); prevent losing stack trace root e. source location of this in PushReplication is wrong, a bug here, fix refactoring</technical_language>

Target:
public static Set<AccountGroup.Id> groupsFor( SchemaFactory<ReviewDb> dbfactory, String[] groupNames, Logger log, String groupNotFoundWarning) { final Set<AccountGroup.Id> result = new HashSet<AccountGroup.Id>(); try { final ReviewDb db = dbfactory.open(); try { for (String name : groupNames) { AccountGroupName group = db.accountGroupNames().get(new AccountGroup.NameKey(name)); if (group == null) { log.warn(MessageFormat.format(groupNotFoundWarning, name)); } else { result.add(group.getId()); } } } finally { db.close(); } } catch (OrmException e) { log.error("Database error, cannot load groups", e); } return result; }
Source:
<code>public static String getTokenToUse(String credentialId, Item item, String token) { if (StringUtils.isEmpty(credentialId)) { return token; } StringCredentials credentials = lookupCredentials(StringUtils.trim(credentialId), item); final String response; if (credentials != null) { response = credentials.getSecret().getPlainText(); } else { <START> response = token; <END> } return response; }</code><technical_language>this throw exception if token is null please? get lots of issues falling bottom token credential null line 29</technical_language>

Target:
public static String getTokenToUse(String credentialId, Item item, String token) { String response; if (StringUtils.isEmpty(credentialId)) { response = token; } else { StringCredentials credentials = lookupCredentials(StringUtils.trim(credentialId), item); if (credentials != null) { response = credentials.getSecret().getPlainText(); } else { response = token; } } if (StringUtils.isEmpty(response)) { throw new IllegalArgumentException("the token with the provided ID could not be found and no token was specified"); } return response; }
Source:
<code>private void handleProgressNotification(ProgressReportDto progress) { if (isNullOrEmpty(progress.getId())) { return; } String taskId = progress.getId(); if (taskFinished(progress)) { progresses.remove(taskId); progressResolver.updateProgressBar(progress); progressResolver.removeProgress(progress); updateCurrentTask(); return; } if (progress.isComplete()) { return; } if (progresses.isEmpty()) { addFirstProgress(progress); } progresses.put(taskId, Pair.of(progress, currentTimeMillis())); progressResolver.addProgress(progress); String currentTaskId = currentProgress.getId(); if (taskId.equals(currentTaskId)) { <START> currentProgress = progress; <END> progressResolver.updateProgressBar(currentProgress); } progressResolver.show(); }</code><technical_language>Check if currentProgress is null</technical_language>

Target:
private void handleProgressNotification(ProgressReportDto progress) { if (isNullOrEmpty(progress.getId())) { return; } String progressId = progress.getId(); if (progressFinished(progress)) { progresses.remove(progressId); backgroundLoader.updateProgressBar(progress); backgroundLoader.removeProgress(progress); updateCurrentProgress(); return; } if (progress.isComplete()) { return; } if (progresses.isEmpty()) { addFirstProgress(progress); } progresses.put(progressId, Pair.of(progress, currentTimeMillis())); backgroundLoader.addProgress(progress); if (currentProgress == null) { currentProgress = progress; } String currentTaskId = currentProgress.getId(); if (progressId.equals(currentTaskId)) { currentProgress = progress; backgroundLoader.updateProgressBar(currentProgress); } backgroundLoader.show(); }
Source:
<code>ServerToServerWithExternalIp(DimensionDataCloudControlApi api) { <START> this.api = checkNotNull(api, "api"); <END> }</code><technical_language>Remove redundant null check. Injection enforces it</technical_language>

Target:
ServerToServerWithExternalIp(DimensionDataCloudControlApi api) { this.api = api; }
Source:
<code>public Operation defaultResponse(Response response) { <START> this.addResponse("default",response); <END> this.addResponseObject("default",response); return this; }</code><technical_language>add responseObject</technical_language>

Target:
public Operation defaultResponse(Response response) { this.addResponseObject("default",response); return this; }
Source:
<code>public static File getHadoopTokens(HadoopSecurityManager hadoopSecurityManager, Props props, Logger log) throws HadoopSecurityManagerException { File tokenFile = null; try { tokenFile = File.createTempFile("mr-azkaban", ".token"); } catch (Exception e) { <START> e.printStackTrace(); <END> throw new HadoopSecurityManagerException("Failed to create the token file.", e); } hadoopSecurityManager.prefetchToken(tokenFile, props, log); return tokenFile; }</code><technical_language>printing out stack trace is needed</technical_language>

Target:
public static File getHadoopTokens(HadoopSecurityManager hadoopSecurityManager, Props props, Logger log) throws HadoopSecurityManagerException { File tokenFile = null; try { tokenFile = File.createTempFile("mr-azkaban", ".token"); } catch (Exception e) { throw new HadoopSecurityManagerException("Failed to create the token file.", e); } hadoopSecurityManager.prefetchToken(tokenFile, props, log); return tokenFile; }
Source:
<code>public static void testIntervalForAttributes(ITmfStateSystem ss, List<ITmfStateInterval> expected, String... path) { try { int quark = ss.getQuarkAbsolute(path); List<ITmfStateInterval> actual = StateSystemUtils.queryHistoryRange(ss, quark, ss.getStartTime(), ss.getCurrentEndTime()); for (int i = 0; i < expected.size(); i++) { if (i >= actual.size()) { fail(Arrays.deepToString(path) + ": Missing interval " + (i + 1)); } ITmfStateInterval act = actual.get(i); ITmfStateInterval exp = expected.get(i); if (!compareIntervalContent(exp, act)) { fail(Arrays.deepToString(path) + ":Interval at position " + (i <START> + 1) + <END> ": expected: " + displayInterval(exp) + " actual: " + displayInterval(act)); } } assertEquals(Arrays.deepToString(path) + ":Number of intervals", expected.size(), actual.size()); } catch (AttributeNotFoundException e) { fail("Attribute " + Arrays.deepToString(path) + " does not exist"); } catch (StateSystemDisposedException e) { fail("State system was disposed"); } }</code><technical_language>question: +1</technical_language>

Target:
public static void testIntervalForAttributes(ITmfStateSystem ss, List<ITmfStateInterval> expected, String... path) { try { int quark = ss.getQuarkAbsolute(path); List<ITmfStateInterval> actual = StateSystemUtils.queryHistoryRange(ss, quark, ss.getStartTime(), ss.getCurrentEndTime()); for (int i = 0; i < expected.size(); i++) { if (i >= actual.size()) { fail(Arrays.deepToString(path) + ": Missing interval " + i); } ITmfStateInterval act = actual.get(i); ITmfStateInterval exp = expected.get(i); if (!compareIntervalContent(exp, act)) { fail(Arrays.deepToString(path) + ":Interval at position " + i + ": expected: " + displayInterval(exp) + " actual: " + displayInterval(act)); } } assertEquals(Arrays.deepToString(path) + ":Number of intervals", expected.size(), actual.size()); } catch (AttributeNotFoundException e) { fail("Attribute " + Arrays.deepToString(path) + " does not exist"); } catch (StateSystemDisposedException e) { fail("State system was disposed"); } }
Source:
<code>public void buildSimpleContext() { <START> MDC.clear(); <END> MDCBuilder.buildMdcContextFromCrn(null); assertNull(MDC.get(LoggerContextKey.TENANT.toString())); assertNull(MDC.get(LoggerContextKey.USER_CRN.toString())); }</code><technical_language>changes unrelated ticket. Please write details commit message needed. Also, moved a @Before method</technical_language>

Target:
public void buildSimpleContext() { MDCBuilder.buildMdcContextFromCrn(null); assertNull(MDC.get(LoggerContextKey.TENANT.toString())); assertNull(MDC.get(LoggerContextKey.USER_CRN.toString())); }
Source:
<code>public void start(LeaderRetrievalListener listener) throws Exception { Preconditions.checkNotNull(listener, "Listener must not be null."); Preconditions.checkState(leaderListener == null, "DefaultLeaderRetrievalService can " + "only be started once."); LOG.info("Starting DefaultLeaderRetrievalService with {}.", leaderRetrievalDriver); synchronized (lock) { leaderListener = listener; <START> leaderRetrievalDriver.start(leaderRetrievalStateHandler); <END> running = true; } }</code><technical_language>here, pass a LeaderRetrievalDriverFactory this class pass in leaderRetrievalStateHandler create actual leaderRetrievalDriver</technical_language>

Target:
public void start(LeaderRetrievalListener listener) throws Exception { checkNotNull(listener, "Listener must not be null."); Preconditions.checkState(leaderListener == null, "DefaultLeaderRetrievalService can " + "only be started once."); synchronized (lock) { leaderListener = listener; leaderRetrievalDriver = leaderRetrievalDriverFactory.createLeaderRetrievalDriver( this, new LeaderRetrievalFatalErrorHandler()); LOG.info("Starting DefaultLeaderRetrievalService with {}.", leaderRetrievalDriver); running = true; } }
Source:
<code>public static String lowerCaseFirstChar(String s) { <START> if (s.isEmpty()) { <END> return s; } return Character.toLowerCase(s.charAt(0)) + s.substring(1); }</code><technical_language>test char for empty letter reuse s if possible</technical_language>

Target:
public static String lowerCaseFirstChar(String s) { if (s.isEmpty()) { return s; } char first = s.charAt(0); if (isLowerCase(first)) { return s; } return toLowerCase(first) + s.substring(1); }
Source:
<code><START> private void assertCorrectGetManagedInterfaceForVdsResult(VdsNetworkInterface result) { <END> assertNotNull(result); assertTrue(result.getIsManagement()); }</code><technical_language>this method private</technical_language>

Target:
static private void assertCorrectGetManagedInterfaceForVdsResult(VdsNetworkInterface result) { assertNotNull(result); assertTrue(result.getIsManagement()); }
Source:
<code>public int read(byte b, int offset, int readSize) { int len = 0; while (len < 1) { try { len = m_in.read(b, offset, readSize); } catch (IOException e) { while (!reconnect()) { try { Thread.sleep(10000); <START> } catch (InterruptedException ie) { <END> } } } } return (len); }</code><technical_language>please add logging in TRACE level miss</technical_language>

Target:
public int read(byte b, int offset, int readSize) { int len = 0; while (len < 1) { try { len = m_in.read(b, offset, readSize); } catch (IOException e) { logger.trace("got exception while reading: {}", e.getMessage()); while (!reconnect()) { try { logger.trace("sleeping before reconnecting"); Thread.sleep(10000); } catch (InterruptedException ie) { logger.warn("interrupted while sleeping on read reconnect"); } } } } return (len); }
Source:
<code>public void createObservation_shouldCreateObservationWithCodedConcept() throws Exception { DWRObsService dwrService = new DWRObsService(); ConceptService conceptService = Context.getConceptService(); Person person = Context.getPersonService().getPerson(2); dwrService.createObs(2, null, 21, "7", "12/12/2014"); List<Obs> obsList = Context.getObsService().getObservationsByPerson(person); Concept concept = conceptService.getConcept(21); Concept answerConcept = conceptService.getConcept(7); Obs addedObs = null; for (Obs obs : obsList) { if (concept.getId().equals(obs.getConcept().getId())) { <START> addedObs = obs; <END> } } assertNotNull(addedObs); assertNotNull(addedObs.getValueCoded()); assertEquals(answerConcept.getId(), addedObs.getValueCoded().getId()); }</code><technical_language>list contains 1 item, get item instead of looping collection check concept ids</technical_language>

Target:
public void createObservation_shouldCreateObservationWithCodedConcept() throws Exception { DWRObsService dwrService = new DWRObsService(); ConceptService conceptService = Context.getConceptService(); ObsService obsService = Context.getObsService(); Person person = Context.getPersonService().getPerson(2); Concept concept = conceptService.getConcept(21); List<Obs> obsListBefore = obsService.getObservationsByPersonAndConcept(person, concept); dwrService.createObs(2, null, 21, "7", "1/12/2014"); List<Obs> obsListAfter = obsService.getObservationsByPersonAndConcept(person, concept); assertEquals(obsListBefore.size() + 1, obsListAfter.size()); Concept answerConcept = conceptService.getConcept(7); Obs addedObs = null; addedObs = (Obs) CollectionUtils.subtract(obsListAfter, obsListBefore).iterator().next(); assertNotNull(addedObs); assertNotNull(addedObs.getValueCoded()); assertEquals(answerConcept.getId(), addedObs.getValueCoded().getId()); }
Source:
<code>public static ThreadPoolExecutor newFixedThreadPool(int numThreads, String name) { <START> return newFixedThreadPool(numThreads, new NamedThreadFactory(name)); <END> }</code><technical_language>want call out (method name? docs) this is non-daemon a lot of other methods in this class daemon threads</technical_language>

Target:
public static ThreadPoolExecutor newFixedThreadPool(int numThreads, String name) { return newFixedThreadPool(numThreads, new NamedThreadFactory(name, true)); }
Source:
<code>private String generateTextSrc(SlideshowModel slideshow, int position) { final String prefix = "text_"; final String postfix = ".txt"; StringBuilder src = new StringBuilder(prefix).append(position).append(postfix); boolean hasDupSrc = false; do { for (SlideModel model : slideshow) { if (model.hasText()) { if <START> (model.getText().getSrc().equals(src.toString())) <END> { src = new StringBuilder(prefix).append(position + 1).append(postfix); hasDupSrc |= true; break; } } hasDupSrc &= false; } } while (hasDupSrc); return src.toString(); }</code><technical_language>getText() getSrc() guaranteed return null</technical_language>

Target:
private String generateTextSrc(SlideshowModel slideshow, int position) { final String prefix = "text_"; final String postfix = ".txt"; StringBuilder src = new StringBuilder(prefix).append(position).append(postfix); boolean hasDupSrc = false; do { for (SlideModel model : slideshow) { if (model.hasText()) { String testSrc = model.getText().getSrc(); if (testSrc != null && testSrc.equals(src.toString())) { src = new StringBuilder(prefix).append(position + 1).append(postfix); hasDupSrc |= true; break; } } hasDupSrc = false; } } while (hasDupSrc); return src.toString(); }
Source:
<code>public HaxeGenericSpecialization getSpecialization() { if (LOG.isTraceEnabled()) LOG.trace(traceMsg(null)); HaxeGenericSpecialization specialization = getUserData(SPECIALIZATION_KEY); if (specialization == null) { specialization = getSpecializationInternal(); putUserData(SPECIALIZATION_KEY, specialization); <START> } <END> return specialization; }</code><technical_language>question of this caching is OK depends parser incremental re-parsing. I lexer is in default "mode" point generic type tag is edited, in case, part of type tag re-parsed, specialization is cached parent node cleared/updated. algorithm lexer is "starting user is typing beginning of a pasted section, walk base/normal mode is encountered, parse edit base/normal mode is encountered lexer position is edited (or pasted) text,"</technical_language>

Target:
public HaxeGenericSpecialization getSpecialization() { HaxeExpression expression = this; if (this instanceof HaxeCallExpression) { expression = ((HaxeCallExpression)this).getExpression(); } else if (this instanceof HaxeNewExpression) { HaxeNewExpression newExpression = (HaxeNewExpression)this; HaxeClass haxeClass = (HaxeClass)newExpression.getType().getReferenceExpression().resolve(); final HaxeClassResolveResult result = HaxeClassResolveResult.create(haxeClass); result.specializeByParameters(newExpression.getType().getTypeParam()); return result.getSpecialization(); } final HaxeClassResolveResult result = tryGetLeftResolveResult(expression); return result != HaxeClassResolveResult.EMPTY ? result.getSpecialization() : null; }
Source:
<code><START> public boolean isIgnoredInOldIndex(IndexDiffCacheEntry entry, String path) { <END> if (entry == null) return false; IndexDiffData indexDiff = entry.getIndexDiff(); if (indexDiff == null) return false; for (String s : indexDiff.getIgnoredNotInIndex()) { String sWithSlash = s; if (!s.endsWith("/")) { sWithSlash = s + '/'; } if (path.equals(s) || path.startsWith(sWithSlash)) { return true; } } return false; }</code><technical_language>soon .gitignore changes state consulted anymore. isIgnoredInOldIndex() return false if gitIgnoreChanged == true</technical_language>

Target:
public boolean isIgnoredInOldIndex(IndexDiffCacheEntry entry, String path) { if (entry == null || gitIgnoreChanged) return false; IndexDiffData indexDiff = entry.getIndexDiff(); if (indexDiff == null) return false; for (String s : indexDiff.getIgnoredNotInIndex()) { String sWithSlash = s; if (!s.endsWith("/")) { sWithSlash = s + '/'; } if (path.equals(s) || path.startsWith(sWithSlash)) { return true; } } return false; }
Source:
<code>@Override InputStream getInputStream() throws IOException { <START> return Utils.getContactPhotoStream(context.getContentResolver(), uri); <END> }</code><technical_language>Inline this crap here. need in Utils anymore</technical_language>

Target:
private InputStream getInputStream() throws IOException { ContentResolver contentResolver = context.getContentResolver(); Uri uri = this.uri; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (uri.toString().startsWith(ContactsContract.Contacts.CONTENT_LOOKUP_URI.toString())) { uri = ContactsContract.Contacts.lookupContact(contentResolver, uri); if (uri == null) { return null; } } return openContactPhotoInputStream(contentResolver, uri); } else { return ContactPhotoStreamIcs.get(contentResolver, uri); } }
Source:
<code>private String getAndroidCommand(){ <START> String command = "android"; <END> return isWindows() ? "cmd /c " + command : command; }</code><technical_language>This fail MacOS linux. Mac linux "./android" if working directory. earlier full path? work Win</technical_language>

Target:
private String getAndroidCommand(){ String command = "android"; return isWindows() ? "cmd /c " + command : "./" + command; }
Source:
<code>private void querySubprocess() { try { markWaitingSubprocess(); <START> _logHandler.setUpContext(_process, _context); <END> _process.writeSpoutMsg(_spoutMsg); while (true) { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if (command == null) { throw new IllegalArgumentException("Command not found in spout message: " + shellMsg); } setHeartbeat(); if (command.equals("sync")) { return; } else if (command.equals("log")) { _logHandler.log(shellMsg); } else if (command.equals("error")) { handleError(shellMsg.getMsg()); } else if (command.equals("emit")) { String stream = shellMsg.getStream(); Long task = shellMsg.getTask(); List<Object> tuple = shellMsg.getTuple(); Object messageId = shellMsg.getId(); if (task == 0) { List<Integer> outtasks = _collector.emit(stream, tuple, messageId); if (shellMsg.areTaskIdsNeeded()) { _process.writeTaskIds(outtasks); } } else { _collector.emitDirect((int) task.longValue(), stream, tuple, messageId); } } else if (command.equals("metrics")) { handleMetrics(shellMsg); } else { throw new RuntimeException("Unknown command received: " + command); } } } catch (Exception e) { String processInfo = _process.getProcessInfoString() + _process.getProcessTerminationInfoString(); throw new RuntimeException(processInfo, e); } finally { completedWaitingSubprocess(); } }</code><technical_language>This on-time setup, move this open(), more familiar initializing in it</technical_language>

Target:
private void querySubprocess() { try { markWaitingSubprocess(); _process.writeSpoutMsg(_spoutMsg); while (true) { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if (command == null) { throw new IllegalArgumentException("Command not found in spout message: " + shellMsg); } setHeartbeat(); if (command.equals("sync")) { return; } else if (command.equals("log")) { _logHandler.log(shellMsg); } else if (command.equals("error")) { handleError(shellMsg.getMsg()); } else if (command.equals("emit")) { String stream = shellMsg.getStream(); Long task = shellMsg.getTask(); List<Object> tuple = shellMsg.getTuple(); Object messageId = shellMsg.getId(); if (task == 0) { List<Integer> outtasks = _collector.emit(stream, tuple, messageId); if (shellMsg.areTaskIdsNeeded()) { _process.writeTaskIds(outtasks); } } else { _collector.emitDirect((int) task.longValue(), stream, tuple, messageId); } } else if (command.equals("metrics")) { handleMetrics(shellMsg); } else { throw new RuntimeException("Unknown command received: " + command); } } } catch (Exception e) { String processInfo = _process.getProcessInfoString() + _process.getProcessTerminationInfoString(); throw new RuntimeException(processInfo, e); } finally { completedWaitingSubprocess(); } }
Source:
<code>void logRequestHeaders() { <START> Header[] headers=postMethod.getRequestHeaders(); <END> Map<String, String> headerMap = new HashMap<String, String>(); for(Header header:headers){ headerMap.put(header.getName(), header.getValue()); } logger.log(Logger.LT_INFO, "Request Headers: " + headerMap); }</code><technical_language>is need convert map. print headers</technical_language>

Target:
public void logRequestHeaders() { List<Header> reqheaders=Arrays.asList(postMethod.getRequestHeaders()); logger.log(Logger.LT_INFO, "Request Headers: " +reqheaders); }
Source:
<code>protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { <START> boolean ADMIN_MODE = PageRequestModeUtil.isAdminMode( req.getSession() ); <END> boolean notRedirect = notRedirect( req ); if ( ADMIN_MODE && !notRedirect ){ String pageUrl = req.getAttribute("javax.servlet.forward.request_uri").toString(); if (pageUrl != null && pageUrl.indexOf(IN_FRAME_PARAMETER_NAME) == -1) { String redirectURL = getRedirectURL(pageUrl); response.sendRedirect(redirectURL); return; } } super.service(req, response); }</code><technical_language>is this a constants? adminMode</technical_language>

Target:
protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { boolean adminMode = PageRequestModeUtil.isAdminMode( req.getSession() ); boolean notRedirect = notRedirect( req ); if ( adminMode && !notRedirect ){ String pageUrl = req.getAttribute(Constants.ORIGINAL_REQUEST_URL_HTTP_HEADER).toString(); if (pageUrl != null && pageUrl.indexOf(IN_FRAME_PARAMETER_NAME) == -1) { String redirectURL = PORTLET_URL_UTIL.getPortletUrl(PortletID.SITE_BROWSER, CollectionsUtils.map("url", pageUrl)); response.sendRedirect(redirectURL); return; } } super.service(req, response); }
Source:
<code>public TrendsResult getTrends(@Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("time_scale") String timeScaleString) { <START> final TimeScale timeScale = TimeScale.fromString(timeScaleString); <END> final TrendsResult result = trendsProcessor.getAllTrends(accessToken.accountId, timeScale); if (result.graphs.isEmpty()) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return result; }</code><technical_language>handle IllegalArgumentException thrown this method. API eventually public, malformed input result in a 5xx server error if helped</technical_language>

Target:
public TrendsResult getTrends(@Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("time_scale") String timeScaleString) { try { final TimeScale timeScale = TimeScale.fromString(timeScaleString); return trendsProcessor.getAllTrends(accessToken.accountId, timeScale); } catch (IllegalArgumentException iae) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(new JsonError(Response.Status.BAD_REQUEST.getStatusCode(), iae.getMessage())).build()); } }
Source:
<code>static void computeUpdateLineAmts(@NonNull final I_I_BankStatement importRecord) { final String amtFormat = getAmtFormat(importRecord); if (X_I_BankStatement.AMTFORMAT_AmountPlusIndicator.equals(amtFormat)) { final BigDecimal trxAmt; <START> final boolean isDebit = "S".equals(importRecord.getDebitOrCreditIndicator()); <END> if (isDebit) { trxAmt = importRecord.getDebitOrCreditAmt().negate(); } else { trxAmt = importRecord.getDebitOrCreditAmt(); } importRecord.setTrxAmt(trxAmt); final BigDecimal stmtAmt = trxAmt.add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); importRecord.setStmtAmt(stmtAmt); } else if (X_I_BankStatement.AMTFORMAT_DebitPlusCredit.equals(amtFormat)) { final BigDecimal stmtAmt = importRecord.getCreditStmtAmt().subtract(importRecord.getDebitStmtAmt()); importRecord.setStmtAmt(stmtAmt); final BigDecimal trxAmt = stmtAmt.subtract(importRecord.getInterestAmt()).subtract(importRecord.getChargeAmt()); importRecord.setTrxAmt(trxAmt); } else if (X_I_BankStatement.AMTFORMAT_Straight.equals(amtFormat)) { importRecord.setStmtAmt(importRecord.getTrxAmt()); } { final BigDecimal sum = importRecord.getTrxAmt().add(importRecord.getInterestAmt()).add(importRecord.getChargeAmt()); if (importRecord.getStmtAmt().compareTo(sum) != 0) { throw new AdempiereException("Invalid amount"); } } }</code><technical_language>avoid hardcoded "S". Pls X_I_BankStatement.AMOUNTPLUSINDICATOR_Debit X_I_BankStatement.AMOUNTPLUSINDICATOR_Credit</technical_language>

Target:
static void computeUpdateLineAmts(@NonNull final I_I_BankStatement importRecord) { final String amtFormat = getAmtFormat(importRecord); switch (amtFormat) { case X_I_BankStatement.AMTFORMAT_AmountPlusIndicator: { final BigDecimal trxAmt; final boolean isDebit = X_I_BankStatement.DEBITORCREDITINDICATOR_Debit.equals(importRecord.getDebitOrCreditIndicator()); if (isDebit) { trxAmt = importRecord.getDebitOrCreditAmt().negate(); } else { trxAmt = importRecord.getDebitOrCreditAmt(); } importRecord.setTrxAmt(trxAmt); final BigDecimal stmtAmt = trxAmt.add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); importRecord.setStmtAmt(stmtAmt); break; } case X_I_BankStatement.AMTFORMAT_DebitPlusCredit: { final BigDecimal stmtAmt = importRecord.getCreditStmtAmt().subtract(importRecord.getDebitStmtAmt()); importRecord.setStmtAmt(stmtAmt); final BigDecimal trxAmt = stmtAmt.subtract(importRecord.getChargeAmt()).subtract(importRecord.getInterestAmt()); importRecord.setTrxAmt(trxAmt); break; } case X_I_BankStatement.AMTFORMAT_Straight: { final BigDecimal stmtAmt = importRecord.getTrxAmt().add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); importRecord.setStmtAmt(stmtAmt); break; } } { final BigDecimal sum = importRecord.getTrxAmt().add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); if (importRecord.getStmtAmt().compareTo(sum) != 0) { throw new AdempiereException("Invalid amount"); } } }
Source:
<code><START> public List<Flight> search(SearchParams searchParams) { <END> switch (searchParams.getSearchType()) { case Date: return searchByDate(searchParams); break; case Time: return searchByTime(searchParams); break; case Price: return searchByPrice(searchParams); break; } }</code><technical_language>I this before. other search methods private</technical_language>

Target:
public List<Flight> search(SearchParams searchParams) { try { switch (searchParams.getSearchType()) { case Date: return searchByDate(searchParams); case Time: return searchByTime(searchParams); case Price: return searchByPrice(searchParams); case Destination: return searchByDestination(searchParams); default: return dao.getAllFlights(); } } catch (Exception e) { System.out.println("Something went wrong while searching the flights"); System.out.println(e.getMessage()); return null; } }
Source:
<code>public synchronized void register(SystemStreamPartition systemStreamPartition, String offset) { super.register(systemStreamPartition, offset); if (isStarted) { <START> LOG.warn("Trying to add partition when the connection has already started."); <END> return; } if (StringUtil.isNullOrWhiteSpace(offset)) { switch (config.getStartPosition(systemStreamPartition.getStream())) { case EARLIEST: offset = START_OF_STREAM; break; case LATEST: offset = END_OF_STREAM; break; default: throw new SamzaException( "Unknown starting position config " + config.getStartPosition(systemStreamPartition.getStream())); } } streamPartitionStartingOffsets.put(systemStreamPartition, offset); }</code><technical_language>this throw instead</technical_language>

Target:
public void register(SystemStreamPartition systemStreamPartition, String offset) { super.register(systemStreamPartition, offset); if (isStarted) { throw new SamzaException("Trying to add partition when the connection has already started."); } if (streamPartitionOffsets.containsKey(systemStreamPartition)) { String prevOffset = streamPartitionOffsets.get(systemStreamPartition); if (EventHubSystemAdmin.compareOffsets(offset, prevOffset) > -1) { return; } } streamPartitionOffsets.put(systemStreamPartition, offset); }
Source:
<code>public void show(final boolean shwn) throws IOException { if (this.file.exists()) { Files.getFileAttributeView( this.file.toPath(), UserDefinedFileAttributeView.class ).write( MkAttributes.VISIBILITY, <START> Charsets.UTF_8.encode(String.valueOf(shwn)) <END> ); } }</code><technical_language>@carlosmiranda here, StandardCharsets</technical_language>

Target:
public void show(final boolean shwn) throws IOException { Files.getFileAttributeView( this.file.toPath(), UserDefinedFileAttributeView.class ).write( MkAttributes.VISIBILITY, StandardCharsets.UTF_8.encode(String.valueOf(shwn)) ); }
Source:
<code>protected SR createFileSR(final Connection conn, final String path) { SR sr = null; PBD pbd = null; try { final String srname = path.trim(); <START> synchronized (srname.intern()) { <END> final Set<SR> srs = SR.getByNameLabel(conn, srname); if (srs != null && !srs.isEmpty()) { return srs.iterator().next(); } final Map<String, String> smConfig = new HashMap<String, String>(); final Host host = Host.getByUuid(conn, hypervisorResource.getHost().getUuid()); final String uuid = UUID.randomUUID().toString(); sr = SR.introduce(conn, uuid, srname, srname, "file", "file", false, smConfig); final PBD.Record record = new PBD.Record(); record.host = host; record.SR = sr; smConfig.put("location", path); record.deviceConfig = smConfig; pbd = PBD.create(conn, record); pbd.plug(conn); sr.scan(conn); } return sr; } catch (final Exception ex) { try { if (pbd != null) { pbd.destroy(conn); } } catch (final Exception e1) { s_logger.debug("Failed to destroy PBD", ex); } try { if (sr != null) { sr.forget(conn); } } catch (final Exception e2) { s_logger.error("Failed to forget SR", ex); } final String msg = "createFileSR failed! due to the following: " + ex.toString(); s_logger.warn(msg, ex); throw new CloudRuntimeException(msg, ex); } }</code><technical_language>consider a ReentrantLock instead of synchronized? ReentrantLock.tryLock(long, TimeUnit) allows specification of a timeout acquire lock. a timeout synchronized, multiple threads deadlock attempting acquire lock in case of a stall. downside of this approach is need track locks in a ConcurrentMap -- ideally WeakReferences allow garbage collected threads operating them</technical_language>

Target:
protected SR createFileSR(final Connection conn, final String path) { SR sr = null; PBD pbd = null; try { final String srname = hypervisorResource.getHost().getUuid() + path.trim(); synchronized (srname.intern()) { final Set<SR> srs = SR.getByNameLabel(conn, srname); if (srs != null && !srs.isEmpty()) { return srs.iterator().next(); } final Map<String, String> smConfig = new HashMap<String, String>(); final Host host = Host.getByUuid(conn, hypervisorResource.getHost().getUuid()); final String uuid = UUID.randomUUID().toString(); sr = SR.introduce(conn, uuid, srname, srname, "file", "file", false, smConfig); final PBD.Record record = new PBD.Record(); record.host = host; record.SR = sr; smConfig.put("location", path); record.deviceConfig = smConfig; pbd = PBD.create(conn, record); pbd.plug(conn); sr.scan(conn); } return sr; } catch (final Exception ex) { try { if (pbd != null) { pbd.destroy(conn); } } catch (final Exception e1) { s_logger.debug("Failed to destroy PBD", ex); } try { if (sr != null) { sr.forget(conn); } } catch (final Exception e2) { s_logger.error("Failed to forget SR", ex); } final String msg = "createFileSR failed! due to the following: " + ex.toString(); s_logger.warn(msg, ex); throw new CloudRuntimeException(msg, ex); } }
Source:
<code>public Answer execute(final DeleteStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) { final Connection conn = citrixResourceBase.getConnection(); final StorageFilerTO poolTO = command.getPool(); try { final SR sr; if (command.getRemoveDatastore()) { Map<String, String> details = command.getDetails(); String srNameLabel = details.get(DeleteStoragePoolCommand.DATASTORE_NAME); sr = citrixResourceBase.getStorageRepository(conn, srNameLabel); } else { sr = citrixResourceBase.getStorageRepository(conn, poolTO.getUuid()); } citrixResourceBase.removeSR(conn, sr); final Answer answer = new Answer(command, true, "success"); return answer; } catch (final Exception e) { final String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: " + poolTO.getHost() + poolTO.getPath(); <START> s_logger.warn(msg, e); <END> return new Answer(command, false, msg); } }</code><technical_language>change this warn error</technical_language>

Target:
public Answer execute(final DeleteStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) { final Connection conn = citrixResourceBase.getConnection(); final StorageFilerTO poolTO = command.getPool(); try { final SR sr; if (command.getRemoveDatastore()) { Map<String, String> details = command.getDetails(); String srNameLabel = details.get(DeleteStoragePoolCommand.DATASTORE_NAME); sr = citrixResourceBase.getStorageRepository(conn, srNameLabel); } else { sr = citrixResourceBase.getStorageRepository(conn, poolTO.getUuid()); } citrixResourceBase.removeSR(conn, sr); final Answer answer = new Answer(command, true, "success"); return answer; } catch (final Exception e) { final String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: " + poolTO.getHost() + poolTO.getPath(); s_logger.error(msg, e); return new Answer(command, false, msg); } }
Source:
<code>public TupleDescriptor buildDescriptor (ExecRow row, TupleDescriptor parentTupleDescriptor, DataDictionary dd ) throws StandardException { DataValueDescriptor col; RoleGrantDescriptor descriptor; String oid_string; String roleid; String grantee; String grantor; String wao; boolean isdef; boolean isDefaultRole; DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator(); if (SanityManager.DEBUG) { SanityManager.ASSERT(row.nColumns() == SYSROLES_COLUMN_COUNT, "Wrong number of columns for a SYSROLES row"); } col = row.getColumn(1); oid_string = col.getString(); col = row.getColumn(2); roleid = col.getString(); col = row.getColumn(3); grantee = col.getString(); col = row.getColumn(4); grantor = col.getString(); col = row.getColumn(5); wao = col.getString(); col = row.getColumn(6); isdef = col.getString().equals("Y"); col = row.getColumn(7); if (col == null || col.isNull()) { if (!isdef) isDefaultRole = true; else <START> isDefaultRole = false; <END> } else isDefaultRole = col.getString().equals("Y"); descriptor = ddg.newRoleGrantDescriptor (getUUIDFactory().recreateUUID(oid_string), roleid, grantee, grantor, wao.equals("Y") ? true: false, isdef, isDefaultRole); return descriptor; }</code><technical_language>instead: isDefaultRole = !isdef;</technical_language>

Target:
public TupleDescriptor buildDescriptor (ExecRow row, TupleDescriptor parentTupleDescriptor, DataDictionary dd ) throws StandardException { DataValueDescriptor col; RoleGrantDescriptor descriptor; String oid_string; String roleid; String grantee; String grantor; String wao; boolean isdef; boolean isDefaultRole; DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator(); if (SanityManager.DEBUG) { SanityManager.ASSERT(row.nColumns() == SYSROLES_COLUMN_COUNT, "Wrong number of columns for a SYSROLES row"); } col = row.getColumn(1); oid_string = col.getString(); col = row.getColumn(2); roleid = col.getString(); col = row.getColumn(3); grantee = col.getString(); col = row.getColumn(4); grantor = col.getString(); col = row.getColumn(5); wao = col.getString(); col = row.getColumn(6); isdef = col.getString().equals("Y"); col = row.getColumn(7); if (col == null || col.isNull()) { isDefaultRole = !isdef; } else isDefaultRole = col.getString().equals("Y"); descriptor = ddg.newRoleGrantDescriptor (getUUIDFactory().recreateUUID(oid_string), roleid, grantee, grantor, wao.equals("Y") ? true: false, isdef, isDefaultRole); return descriptor; }
Source:
<code>public void requestsAreParallel() throws Exception { final int port = new Ports().allocate(); final String uri = String.format("http://localhost:%d", port); final int count = 3; <START> final long timeout = TimeUnit.SECONDS.toMillis(10L); <END> final CountDownLatch started = new CountDownLatch(count); final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { started.countDown(); try { started.await(); } catch (final InterruptedException ex) { throw new IllegalStateException(ex); } completed.countDown(); return new TkEmpty().act(req); } }; final Thread server = new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkParallel(new BkBasic(take)), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ); server.start(); for (int idx = 0; idx < count; ++idx) { new Thread( new Runnable() { @Override public void run() { try { new JdkRequest(uri) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); } completed.await(timeout, TimeUnit.MILLISECONDS); MatcherAssert.assertThat(started.getCount(), Matchers.equalTo(0L)); MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); new Ports().release(port); }</code><technical_language>@komaz this once, remove this variable result of toMillis() inline await. Furthermore, I suggest lengthen 1 minute, active wait ensure completion of threads in circumstances</technical_language>

Target:
public void requestsAreParallel() throws Exception { final int port = new Ports().allocate(); final String uri = String.format("http://localhost:%d", port); final int count = 3; final CountDownLatch started = new CountDownLatch(count); final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { started.countDown(); try { started.await(); } catch (final InterruptedException ex) { throw new IllegalStateException(ex); } completed.countDown(); return new TkEmpty().act(req); } }; new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkParallel(new BkBasic(take)), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); for (int idx = 0; idx < count; ++idx) { new Thread( new Runnable() { @Override public void run() { try { new JdkRequest(uri) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); } completed.await(1L, TimeUnit.MINUTES); MatcherAssert.assertThat(started.getCount(), Matchers.equalTo(0L)); MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); new Ports().release(port); }
Source:
<code>ConnectionHandler createConnectionHandler(String connectionId, String hostname, TransportType transportType) { switch (transportType) { case AMQP: return new ConnectionHandler(connectionId, hostname); case AMQP_WEB_SOCKETS: return new WebSocketsConnectionHandler(connectionId, hostname); default: <START> throw new IllegalArgumentException(String.format(Locale.US, "This transport type '%s' is not supported.", transportType)); <END> } }</code><technical_language>ClientLogger logAndThrow API throwing exception</technical_language>

Target:
ConnectionHandler createConnectionHandler(String connectionId, String hostname, TransportType transportType) { switch (transportType) { case AMQP: return new ConnectionHandler(connectionId, hostname); case AMQP_WEB_SOCKETS: return new WebSocketsConnectionHandler(connectionId, hostname); default: logger.logAndThrow(new IllegalArgumentException(String.format(Locale.US, "This transport type '%s' is not supported.", transportType))); return null; } }
Source:
<code>public void setupRoutes() { path(controllerBasePath(), () -> { before("", this::setContentType); before("/*", this::setContentType); before("", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", this::index); get(Routes.ElasticProfileAPI.ID, this::show); <START> get(Routes.ElasticProfileAPI.ID + "/usages", this::usages); <END> post("", this::create); put(Routes.ElasticProfileAPI.ID, this::update); delete(Routes.ElasticProfileAPI.ID, this::destroy); exception(RecordNotFoundException.class, this::notFound); }); }</code><technical_language>add mimeType? This honor Accept header</technical_language>

Target:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", this::setContentType); before("/*", this::setContentType); before("", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", mimeType, this::index); get(Routes.ElasticProfileAPI.ID, mimeType, this::show); get(Routes.ElasticProfileAPI.ID + Routes.ElasticProfileAPI.USAGES, mimeType, this::usages); post("", mimeType, this::create); put(Routes.ElasticProfileAPI.ID, mimeType, this::update); delete(Routes.ElasticProfileAPI.ID, mimeType, this::destroy); exception(RecordNotFoundException.class, this::notFound); }); }
Source:
<code>public Future<AppSearchResult<Void>> setSchema( @NonNull List<AppSearchSchema> schemas, boolean forceOverride) { Callable<AppSearchResult<Void>> callableTask = () -> { SchemaProto.Builder schemaProtoBuilder = SchemaProto.newBuilder(); for (AppSearchSchema schema : schemas) { schemaProtoBuilder.addTypes(schema.getProto()); } mAppSearchImpl.setSchema(schemaProtoBuilder.build(), forceOverride); return <START> AppSearchResult.newSuccessfulResult( <END> null); }; return mExecutor.submit(callableTask); }</code><technical_language>longer calling throwableToFailedResult changing contract. Before, IOException reported a failed result; exceptional future. details of this works discussed in API proposal, in meantime, wrap this callable in a big try/catch code be</technical_language>

Target:
public Future<AppSearchResult<Void>> setSchema( @NonNull List<AppSearchSchema> schemas, boolean forceOverride) { Callable<AppSearchResult<Void>> callableTask = () -> { SchemaProto.Builder schemaProtoBuilder = SchemaProto.newBuilder(); for (AppSearchSchema schema : schemas) { schemaProtoBuilder.addTypes(schema.getProto()); } try { mAppSearchImpl.setSchema(schemaProtoBuilder.build(), forceOverride); return AppSearchResult.newSuccessfulResult( null); } catch (Throwable t) { throw throwableToAppSearchException(t); } }; return mExecutor.submit(callableTask); }
Source:
<code>public Optional<ImmutableZkWorker> findWorkerForTask( final RemoteTaskRunnerConfig config, final ImmutableMap<String, ImmutableZkWorker> zkWorkers, final Task task ) { TreeSet<ImmutableZkWorker> sortedWorkers = Sets.newTreeSet( new Comparator<ImmutableZkWorker>() { @Override public int compare( ImmutableZkWorker zkWorker, ImmutableZkWorker zkWorker2 ) { int retVal = Ints.compare(zkWorker2.getCurrCapacityUsed(), zkWorker.getCurrCapacityUsed()); if (retVal == 0) { retVal = zkWorker.getWorker().getHost().compareTo(zkWorker2.getWorker().getHost()); } <START> return config.isStrategyTaskAscOrder() ? retVal : -retVal; <END> } } ); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableZkWorker zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }</code><technical_language>change this Ordering::reverse() instead of a negative int value</technical_language>

Target:
public Optional<ImmutableZkWorker> findWorkerForTask( final RemoteTaskRunnerConfig config, final ImmutableMap<String, ImmutableZkWorker> zkWorkers, final Task task ) { Ordering<ImmutableZkWorker> ordering = new Ordering<ImmutableZkWorker>() { @Override public int compare( ImmutableZkWorker zkWorker, ImmutableZkWorker zkWorker2 ) { int retVal = Ints.compare(zkWorker2.getCurrCapacityUsed(), zkWorker.getCurrCapacityUsed()); if (retVal == 0) { retVal = zkWorker.getWorker().getHost().compareTo(zkWorker2.getWorker().getHost()); } return retVal; } }; TreeSet<ImmutableZkWorker> sortedWorkers = Sets.newTreeSet( config.isStrategyTaskAscOrder() ? ordering : ordering.reverse() ); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableZkWorker zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }
Source:
<code>public void testUniqueLayoutData() { GridDataFactory gridDataFactory = GridDataFactory.fillDefaults().grab(true, false); TestFactory factory = <START> TestFactory.newTest().tooltip("toolTip").enabled(false).layoutData(gridDataFactory::create); <END> Label label = factory.create(shell); Label label2 = factory.create(shell); assertNotEquals(label.getLayoutData(), label2.getLayoutData()); }</code><technical_language>needed for test. simple</technical_language>

Target:
public void testUniqueLayoutData() { GridDataFactory gridDataFactory = GridDataFactory.fillDefaults().grab(true, false); TestFactory factory = TestFactory.newTest().layoutData(gridDataFactory::create); Label label = factory.create(shell); Label label2 = factory.create(shell); assertNotSame(label.getLayoutData(), label2.getLayoutData()); }
Source:
<code>protected boolean shouldBeDecorated(final EditPart editPart) { <START> boolean shouldBeDecorated = super.shouldBeDecorated(editPart); return shouldBeDecorated && editPart instanceof IDiagramElementEditPart; <END> }</code><technical_language>"instanceof" test avoid calling more costly "super": return editPart instanceof IDiagramElementEditPart && super.shouldBeDecorated(editPart);</technical_language>

Target:
protected boolean shouldBeDecorated(final EditPart editPart) { return editPart instanceof IDiagramElementEditPart && super.shouldBeDecorated(editPart); }