auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void handleWsStart(WorkspaceDto workspace) { initialLoadingInfo.setOperationStatus(WORKSPACE_BOOTING.getValue(), SUCCESS); setCurrentWorkspace(workspace); EnvironmentDto currentEnvironment = null; for (EnvironmentDto environment : workspace.getConfig().getEnvironments()) { if (environment.getName().equals(workspace.getConfig().getDefaultEnv())) { currentEnvironment = environment; break; } } List<MachineConfigDto> machineConfigs = <START> currentEnvironment != null ? currentEnvironment.getMachineConfigs() : new ArrayList<MachineConfigDto>(); <END> for (MachineConfigDto machineConfig : machineConfigs) { if (machineConfig.isDev()) { MachineManager machineManager = machineManagerProvider.get(); machineManager.onDevMachineCreating(machineConfig); } } }</code><technical_language>Collections.emptyList() instead of new ArrayList<MachineConfigDto>()</technical_language>

Target:
private void handleWsStart(WorkspaceDto workspace) { initialLoadingInfo.setOperationStatus(WORKSPACE_BOOTING.getValue(), SUCCESS); setCurrentWorkspace(workspace); EnvironmentDto currentEnvironment = null; for (EnvironmentDto environment : workspace.getConfig().getEnvironments()) { if (environment.getName().equals(workspace.getConfig().getDefaultEnv())) { currentEnvironment = environment; break; } } List<MachineConfigDto> machineConfigs = currentEnvironment != null ? currentEnvironment.getMachineConfigs() : Collections.<MachineConfigDto>emptyList(); for (MachineConfigDto machineConfig : machineConfigs) { if (machineConfig.isDev()) { MachineManager machineManager = machineManagerProvider.get(); machineManager.onDevMachineCreating(machineConfig); } } }
Source:
<code>public synchronized @Nonnull String addFixedNewToken(@Nonnull String name, @Nonnull String tokenPlainValue) { if (tokenPlainValue.length() != 2 + 32) { LOGGER.log(Level.INFO, "addFixedNewToken, length received: {0}" + tokenPlainValue.length()); throw new IllegalArgumentException("The token must consist of 2 characters for the version and 32 hex-characters for the secret"); } String hashVersion = tokenPlainValue.substring(0, 2); if (!HASH_VERSION.equals(hashVersion)) { throw new IllegalArgumentException("The given version is not recognized: " + hashVersion); } String tokenPlainHexValue = tokenPlainValue.substring(2); tokenPlainHexValue = tokenPlainHexValue.toLowerCase(); <START> if (!tokenPlainHexValue.matches("[a-f0-9]{32}")) { <END> throw new IllegalArgumentException("The secret part of the token must consist of 32 hex-characters"); } HashedToken token = prepareAndStoreToken(name, tokenPlainHexValue); return token.uuid; }</code><technical_language>This extracted a static Pattern field for caching compiled regex</technical_language>

Target:
public synchronized @Nonnull String addFixedNewToken(@Nonnull String name, @Nonnull String tokenPlainValue) { if (tokenPlainValue.length() != VERSION_LENGTH + HEX_CHAR_LENGTH) { LOGGER.log(Level.INFO, "addFixedNewToken, length received: {0}" + tokenPlainValue.length()); throw new IllegalArgumentException("The token must consist of 2 characters for the version and 32 hex-characters for the secret"); } String hashVersion = tokenPlainValue.substring(0, VERSION_LENGTH); if (!HASH_VERSION.equals(hashVersion)) { throw new IllegalArgumentException("The given version is not recognized: " + hashVersion); } String tokenPlainHexValue = tokenPlainValue.substring(VERSION_LENGTH); tokenPlainHexValue = tokenPlainHexValue.toLowerCase(); if (!CHECK_32_HEX_CHAR.matcher(tokenPlainHexValue).matches()) { throw new IllegalArgumentException("The secret part of the token must consist of 32 hex-characters"); } HashedToken token = prepareAndStoreToken(name, tokenPlainHexValue); return token.uuid; }
Source:
<code>public PublicAccessLogRequestHandler(PublicAccessLogger publicAccessLogger) { <START> this.publicAccessLogger = publicAccessLogger; <END> }</code><technical_language>reset construct</technical_language>

Target:
public PublicAccessLogRequestHandler(PublicAccessLogger publicAccessLogger) { this.publicAccessLogger = publicAccessLogger; reset(); }
Source:
<code><START> public void testToFlowElement_process() throws Exception { <END> final BaseReusableSubprocess definition = new ReusableSubprocess(); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertFalse(CustomElement.isCase.of(propertyWriter.getFlowElement()).get()); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testToFlowElement_process() { final BaseReusableSubprocess definition = new ReusableSubprocess(); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertFalse(CustomElement.isCase.of(propertyWriter.getFlowElement()).get()); }
Source:
<code>public Set<InstalledDriver> getInstalledDrivers(String profileName) { String profile = profileName != null ? profileName : "default"; <START> return Collections.unmodifiableSet(Collections.synchronizedSet(new HashSet<InstalledDriver>(drivers.get(profile).values()))); <END> }</code><technical_language>This NPE well</technical_language>

Target:
public Set<InstalledDriver> getInstalledDrivers(String profileName) { String profile = profileName != null ? profileName : DEFAULT_PROFILE; if (drivers.get(profile) == null) { throw ROOT_LOGGER.noDriverDefinedInDefaultProfile(); } return Collections.unmodifiableSet(Collections.synchronizedSet(new HashSet<InstalledDriver>(drivers.get(profile).values()))); }
Source:
<code>default Try<T> filter(Predicate<? super T> predicate, Supplier<? extends Throwable> throwableSupplier) { Objects.requireNonNull(predicate, "predicate is null"); <START> Objects.requireNonNull(predicate, "throwableSupplier is null"); <END> return filterTry(predicate::test, throwableSupplier); }</code><technical_language>Java Objects.requireNonNull(throwableSupplier, "throwableSupplier is null");</technical_language>

Target:
default Try<T> filter(Predicate<? super T> predicate, Supplier<? extends Throwable> throwableSupplier) { Objects.requireNonNull(predicate, "predicate is null"); Objects.requireNonNull(throwableSupplier, "throwableSupplier is null"); return filterTry(predicate::test, throwableSupplier); }
Source:
<code>protected void execute() { logger.trace("Connecting to {}" + baseURL); clearState(); StringBuilder sb = new StringBuilder("<response>"); String statuses = {"status", "chem", "pumps"}; for(String status : statuses){ String response = HttpUtil.executeUrl("GET", baseURL + "/" + status + ".xml", TIMEOUT); logger.trace(baseURL + "/" + status + ".xml \n {}", response); if(response == null){ logger.error("No response from Autelis controller!"); return; } Matcher m = responsePattern.matcher(response); if (m.find()) { sb.append(m.group(1)); } } <START> sb.append("</response>"); <END> String xmlDoc = sb.toString(); for (AutelisBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { Item item = provider.getItem(itemName); String config = provider.getAutelisBindingString(itemName); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { InputSource is = new InputSource(new StringReader(xmlDoc)); String value = xpath.evaluate("response/" + config.replace('.', '/'), is); State state = toState(item.getClass(), value); State oldState = stateMap.put(itemName, state); if(!state.equals(oldState)){ logger.debug("updating item with state {}", itemName, state); eventPublisher.postUpdate(itemName, state); } } catch (XPathExpressionException e) { logger.error("could not parse xml",e); } } } }</code><technical_language>for sake of readability please refactor method "fetchStateFromAutelis" alike</technical_language>

Target:
protected void execute() { logger.trace("Connecting to {}" + baseURL); clearState(); String xmlDoc = fetchStateFromController(); if(xmlDoc == null) return; for (AutelisBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { Item item = provider.getItem(itemName); String config = provider.getAutelisBindingConfigString(itemName); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { InputSource is = new InputSource(new StringReader(xmlDoc)); String value = xpath.evaluate("response/" + config.replace('.', '/'), is); State state = toState(item.getClass(), value); State oldState = stateMap.put(itemName, state); if(!state.equals(oldState)){ logger.debug("updating item with state {}", itemName, state); eventPublisher.postUpdate(itemName, state); } } catch (XPathExpressionException e) { logger.warn("could not parse xml",e); } } } }
Source:
<code>private int searchForIndex(int i) { <START> ensureIndex(i); <END> if (cardinality == 0 || i > indices[cardinality - 1]) { return cardinality; } int left = 0; int right = cardinality; while (left < right) { int p = (left + right) / 2; if (indices[p] > i) { right = p; } else if (indices[p] < i) { left = p + 1; } else { return p; } } return left; }</code><technical_language>Please, do remove this TODO: important performance note</technical_language>

Target:
private int searchForIndex(int i) { if (cardinality == 0 || i > indices[cardinality - 1]) { return cardinality; } int left = 0; int right = cardinality; while (left < right) { int p = (left + right) / 2; if (indices[p] > i) { right = p; } else if (indices[p] < i) { left = p + 1; } else { return p; } } return left; }
Source:
<code>private ProcessWrapper startP4dInRepo(File tempRepo) throws IOException, CheckedCommandLineException { <START> CommandLine command = createCommandLine("p4d").withArgs("-r", tempRepo.getAbsolutePath(), "-p", String.valueOf(port)); <END> ProcessOutputStreamConsumer outputStreamConsumer = inMemoryConsumer(); return command.execute(outputStreamConsumer, new EnvironmentVariableContext(),null); }</code><technical_language>Is this a mac-only fix (case insensitive filesystem)</technical_language>

Target:
private ProcessWrapper startP4dInRepo(File tempRepo) throws IOException, CheckedCommandLineException { CommandLine command = createCommandLine("p4d").withArgs("-C0", "-r", tempRepo.getAbsolutePath(), "-p", String.valueOf(port)); ProcessOutputStreamConsumer outputStreamConsumer = inMemoryConsumer(); return command.execute(outputStreamConsumer, new EnvironmentVariableContext(),null); }
Source:
<code>public Application fromDBObject(DBObject dbo) { if (dbo == null) { return null; } Long applicationId = TranslatorUtils.toLong(dbo, DEER_ID_KEY); if (DEER_ID_KEY == null) { <START> return null; <END> } return Application.builder() .withId(Id.valueOf(applicationId)) .withSlug(TranslatorUtils.toString(dbo, SLUG_KEY)) .withTitle(TranslatorUtils.toString(dbo, TITLE_KEY)) .withDescription(TranslatorUtils.toString(dbo, DESCRIPTION_KEY)) .withCreated(TranslatorUtils.toDateTime(dbo, CREATED_KEY)) .withCredentials(credentialsTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CREDENTIALS_KEY))) .withSources(sourcesTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CONFIG_KEY))) .build(); }</code><technical_language>return null here? do expect DEER_ID_KEY null</technical_language>

Target:
public Application fromDBObject(DBObject dbo) { if (dbo == null) { return null; } return Application.builder() .withId(Id.valueOf(TranslatorUtils.toLong(dbo, APPLICATION_ID_KEY))) .withSlug(TranslatorUtils.toString(dbo, SLUG_KEY)) .withTitle(TranslatorUtils.toString(dbo, TITLE_KEY)) .withDescription(TranslatorUtils.toString(dbo, DESCRIPTION_KEY)) .withCreated(TranslatorUtils.toDateTime(dbo, CREATED_KEY)) .withCredentials(credentialsTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CREDENTIALS_KEY))) .withSources(sourcesTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CONFIG_KEY))) .build(); }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitDeferStatement(@NotNull GoDeferStatement o) { PsiElement parent = o.getParent(); <START> while (!((parent instanceof GoFunctionDeclaration) || <END> parent instanceof GoMethodDeclaration) || parent instanceof GoFile) { if (parent instanceof GoForStatement) { holder.registerProblem(o, "Possible resource leak, \"defer\" is called in a for loop.", ProblemHighlightType.WEAK_WARNING); return; } parent = parent.getParent(); } } }; }</code><technical_language>PsiTreeUtil.getParentOfType(o, GoForStatement.class)</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitDeferStatement(@NotNull GoDeferStatement o) { PsiElement parent = PsiTreeUtil .getParentOfType(o, GoForStatement.class, GoFunctionLit.class); if (parent instanceof GoForStatement) { holder.registerProblem(o, "Possible resource leak, \"defer\" is called in a for loop.", ProblemHighlightType.WEAK_WARNING); } } }; }
Source:
<code>private void handleCheckbox(CheckStateChangedEvent event) { UiSchemeInformation schemeInformation = (UiSchemeInformation) event.getElement(); <START> if (operatingSystemRegistration.canOverwriteOtherApplicationsRegistration() == false && event.getChecked() <END> && schemeIsHandledByOther(schemeInformation.information)) { schemeInformation.checked = false; tableViewer.setChecked(schemeInformation, schemeInformation.checked); messageDialogWrapper.openWarning(getShell(), UriHandlerPreferencePage_Warning_OtherApp, NLS.bind(UriHandlerPreferencePage_Warning_OtherApp_Description, schemeInformation.information.getHandlerInstanceLocation(), schemeInformation.information.getName())); return; } schemeInformation.checked = event.getChecked(); setSchemeDetails(schemeInformation); tableViewer.update(schemeInformation, null); }</code><technical_language>a confimration popup another application's setting is overwritten is windows? sure. revert apply</technical_language>

Target:
private void handleCheckbox(CheckStateChangedEvent event) { UiSchemeInformation schemeInformation = (UiSchemeInformation) event.getElement(); if (event.getChecked() && schemeIsHandledByOther(schemeInformation.information)) { if (operatingSystemRegistration.canOverwriteOtherApplicationsRegistration()) { boolean answer = messageDialogWrapper.openQuestion(getShell(), UriHandlerPreferencePage_Warning_OtherApp_Confirmation, NLS.bind(UriHandlerPreferencePage_Warning_OtherApp_Confirmation_Description, schemeInformation.information.getHandlerInstanceLocation(), schemeInformation.information.getName())); if (answer == false) { schemeInformation.checked = false; tableViewer.setChecked(schemeInformation, schemeInformation.checked); return; } } else { schemeInformation.checked = false; tableViewer.setChecked(schemeInformation, schemeInformation.checked); messageDialogWrapper.openWarning(getShell(), UriHandlerPreferencePage_Warning_OtherApp, NLS.bind(UriHandlerPreferencePage_Warning_OtherApp_Description, schemeInformation.information.getHandlerInstanceLocation(), schemeInformation.information.getName())); return; } } schemeInformation.checked = event.getChecked(); setSchemeDetails(schemeInformation); tableViewer.update(schemeInformation, null); }
Source:
<code>public void executeAsync() { ReplicaList initialReplicas = targetReplicas.subList(0, targetReplicas.size() - 1); Replicas.checkFull(initialReplicas); if (handler.blockfor < initialReplicas.size()) { makeDataRequests(initialReplicas.subList(0, 2).asEndpoints()); if (initialReplicas.size() > 2) makeDigestRequests(initialReplicas.subList(2, initialReplicas.size()).asEndpoints()); } else { <START> makeDataRequests(initialReplicas.subList(0, 1).asEndpoints()); <END> if (initialReplicas.size() > 1) makeDigestRequests(initialReplicas.subList(1, initialReplicas.size()).asEndpoints()); } }</code><technical_language>ImmutableList.of(intialReplicas.get(0).getEndpoint())</technical_language>

Target:
public void executeAsync() { ReplicaList initialReplicas = targetReplicas.subList(0, targetReplicas.size() - 1); Replicas.checkFull(initialReplicas); if (handler.blockfor < initialReplicas.size()) { makeDataRequests(initialReplicas.subList(0, 2)); if (initialReplicas.size() > 2) makeDigestRequests(initialReplicas.subList(2, initialReplicas.size())); } else { makeDataRequests(initialReplicas.subList(0, 1)); if (initialReplicas.size() > 1) makeDigestRequests(initialReplicas.subList(1, initialReplicas.size())); } }
Source:
<code>public List<DeribitInstrument> getDeribitActiveInstruments(String currency) throws IOException { DeribitInstrumentsResponse response = null; try { response = deribit.getInstruments(currency); <START> } catch (HttpStatusIOException ex) { <END> DeribitErrorAdapter.adapt(ex); } return response.getResult(); }</code><technical_language>implement suggestions DeribitException get thrown instead methods in *ServiceRaw classes throw out DeribitException caught adapted in *Service methods</technical_language>

Target:
public List<DeribitInstrument> getDeribitActiveInstruments(String currency) throws IOException { return deribit.getInstruments(currency).getResult(); }
Source:
<code>public JobRecordListener(JobPersister persister, boolean failOnCounterFetch) { this.persister = persister; this.failOnCounterFetch = failOnCounterFetch; <START> taskSummaries = Lists.newArrayList(); <END> }</code><technical_language>a follow-up project of caching counters, get stored well</technical_language>

Target:
public JobRecordListener(JobPersister persister, boolean failOnCounterFetch) { this.persister = persister; this.failOnCounterFetch = failOnCounterFetch; this.taskSummaries = Maps.newHashMap(); }
Source:
<code>public void testRowLiteral() { <START> RowExpression rowExpression = getRoundTrip("ROW(1, 1.1)", true); <END> assertTrue(rowExpression instanceof ConstantExpression); Object value = ((ConstantExpression) rowExpression).getValue(); assertTrue(value instanceof SingleRowBlock); SingleRowBlock block = (SingleRowBlock) value; assertEquals(block.getPositionCount(), 2); assertEquals(block.getInt(0), 1); assertEquals(Double.longBitsToDouble(block.getLong(1)), 1.1); }</code><technical_language>original test put false optimize field</technical_language>

Target:
public void testRowLiteral() { assertEquals(getRoundTrip("ROW(1, 1.1)", false), specialForm( ROW_CONSTRUCTOR, RowType.anonymous( ImmutableList.of( INTEGER, DOUBLE)), constant(1L, INTEGER), constant(1.1, DOUBLE))); }
Source:
<code>public static PageMode get(final HttpSession ses) { <START> PageMode mode = (ses != null && ses.getAttribute(com.dotmarketing.util.WebKeys.PAGE_MODE_SESSION) != null <END> && ses.getAttribute("tm_date") == null) ? (PageMode) ses.getAttribute(com.dotmarketing.util.WebKeys.PAGE_MODE_SESSION) : ANON; return mode; }</code><technical_language>![MINOR](<LINK_1> 'Severity: MINOR') Immediately return this expression instead of assigning temporary variable "mode". [![rule](<LINK_0>](<LINK_2></technical_language>

Target:
public static PageMode get(final HttpSession ses) { PageMode mode = (ses != null && ses.getAttribute(com.dotmarketing.util.WebKeys.PAGE_MODE_SESSION) != null && ses.getAttribute("tm_date") == null) ? (PageMode) ses.getAttribute(com.dotmarketing.util.WebKeys.PAGE_MODE_SESSION) : LIVE; return mode; }
Source:
<code>public static List<PathComponent> parseSchemaMapping(String schemaMapping) { List<PathComponent> path = new LinkedList<PathComponent>(); StringTokenizer tok = new StringTokenizer(schemaMapping, delims, true); while (tok.hasMoreTokens()) { String part = tok.nextToken(); if (".".equals(part)) { continue; } else if ("[".equals(part)) { String indexStr = tok.nextToken(); int index = Integer.parseInt(indexStr); if (!"]".equals(tok.nextToken())) { throw new IllegalArgumentException("Illegal array syntax in schema mapping value: " + schemaMapping); } path.add(new PathComponent(PathComponent.PathComponentType.ARRAY, index)); } else if ("(".equals(part)) { String keyStr = tok.nextToken(); if (!")".equals(tok.nextToken())) { throw new IllegalArgumentException("Illegal map syntax in schema mapping value: " + schemaMapping); } <START> path.add(new PathComponent(PathComponent.PathComponentType.MAP, new String(keyStr))); <END> } else { path.add(new PathComponent(PathComponent.PathComponentType.FIELD, part)); } } return path; }</code><technical_language>need new String(keyStr)</technical_language>

Target:
public static List<PathComponent> parseSchemaMapping(String schemaMapping) { List<PathComponent> path = new LinkedList<PathComponent>(); StringTokenizer tok = new StringTokenizer(schemaMapping, delims, true); while (tok.hasMoreTokens()) { String part = tok.nextToken(); if (".".equals(part)) { continue; } else if ("[".equals(part)) { String indexStr = tok.nextToken(); int index = Integer.parseInt(indexStr); if (!"]".equals(tok.nextToken())) { throw new IllegalArgumentException("Illegal array syntax in schema mapping value: " + schemaMapping); } path.add(new PathComponent(PathComponent.PathComponentType.ARRAY, index)); } else if ("(".equals(part)) { String keyStr = tok.nextToken(); if (!")".equals(tok.nextToken())) { throw new IllegalArgumentException("Illegal map syntax in schema mapping value: " + schemaMapping); } path.add(new PathComponent(PathComponent.PathComponentType.MAP, keyStr)); } else { path.add(new PathComponent(PathComponent.PathComponentType.FIELD, part)); } } return path; }
Source:
<code>protected Object doWork() { final boolean doTumorPulldown; if (tumorHetOutputFile != null && tumorBAMFile != null) { doTumorPulldown = true; } else if ((tumorHetOutputFile == null) != (tumorBAMFile == null)) { throw new UserException.CommandLineException("Must specify both BAM and output files for tumor pulldown."); } else { doTumorPulldown = false; } final HetPulldownCalculator hetPulldown = new HetPulldownCalculator(REFERENCE_ARGUMENTS.getReferenceFile(), snpFile, minimumMappingQuality, minimumBaseQuality, VALIDATION_STRINGENCY); logger.info("Getting normal het pulldown..."); final Pulldown normalHetPulldown = hetPulldown.getNormal(normalBAMFile, pvalThreshold, minimumRawReads); <START> normalHetPulldown.write(normalHetOutputFile, AllelicCountTableColumns.AllelicCountTableVerbosity.BASIC); <END> logger.info("Normal het pulldown written to " + normalHetOutputFile.toString()); if (doTumorPulldown) { final IntervalList normalHetIntervals = normalHetPulldown.getIntervals(); logger.info("Getting tumor het pulldown..."); final Pulldown tumorHetPulldown = hetPulldown.getTumor(tumorBAMFile, normalHetIntervals, minimumRawReads); tumorHetPulldown.write(tumorHetOutputFile, AllelicCountTableColumns.AllelicCountTableVerbosity.BASIC); logger.info("Tumor het pulldown written to " + tumorHetOutputFile.toString()); } return "SUCCESS"; }</code><technical_language>import AllelicCountTableColumns.AllelicCountTableVerbosity this shorter</technical_language>

Target:
protected Object doWork() { final boolean doTumorPulldown; if (tumorHetOutputFile != null && tumorBAMFile != null) { doTumorPulldown = true; } else if ((tumorHetOutputFile == null) != (tumorBAMFile == null)) { throw new UserException.CommandLineException("Must specify both BAM and output files for tumor pulldown."); } else { doTumorPulldown = false; } final HetPulldownCalculator hetPulldown = new HetPulldownCalculator(REFERENCE_ARGUMENTS.getReferenceFile(), snpFile, minimumMappingQuality, minimumBaseQuality, VALIDATION_STRINGENCY); logger.info("Getting normal het pulldown..."); final Pulldown normalHetPulldown = hetPulldown.getNormal(normalBAMFile, pvalThreshold, minimumRawReads); normalHetPulldown.write(normalHetOutputFile, AllelicCountTableVerbosity.BASIC); logger.info("Normal het pulldown written to " + normalHetOutputFile.toString()); if (doTumorPulldown) { final IntervalList normalHetIntervals = normalHetPulldown.getIntervals(); logger.info("Getting tumor het pulldown..."); final Pulldown tumorHetPulldown = hetPulldown.getTumor(tumorBAMFile, normalHetIntervals, minimumRawReads); tumorHetPulldown.write(tumorHetOutputFile, AllelicCountTableVerbosity.BASIC); logger.info("Tumor het pulldown written to " + tumorHetOutputFile.toString()); } return "SUCCESS"; }
Source:
<code>public int hashCode() { <START> return 1; <END> }</code><technical_language>Suggested getClass().hashCode() "more random"</technical_language>

Target:
public int hashCode() { return getClass().hashCode(); }
Source:
<code>protected List<MimeMessage> prepareMailToBeSent() throws MessagingException, IOException, EntityDoesNotExistException { Emails emailManager = new Emails(); FeedbackSessionAttributes feedbackObject = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); log.info("Fetching feedback session object for feedback session name : " + feedbackSessionName + " and course : " + courseId); if (feedbackObject == null) { log.severe("Feedback session object for feedback session name : " + feedbackSessionName + " for course : " + courseId + " could not be fetched"); return null; <START> } else { <END> return emailManager.generateFeedbackSessionOpeningEmails(feedbackObject); } }</code><technical_language>Similar in FeedbackSessionClosingMailAction.java, move instantiation of emailManager is used, remove else clause</technical_language>

Target:
protected List<MimeMessage> prepareMailToBeSent() throws MessagingException, IOException, EntityDoesNotExistException { FeedbackSessionAttributes feedbackObject = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); log.info("Fetching feedback session object for feedback session name : " + feedbackSessionName + " and course : " + courseId); if (feedbackObject == null) { log.severe("Feedback session object for feedback session name : " + feedbackSessionName + " for course : " + courseId + " could not be fetched"); return null; } else { return new Emails().generateFeedbackSessionOpeningEmails(feedbackObject); } }
Source:
<code>private synchronized BridgeHandler getDssBridgeHandler() { if (this.dssBridgeHandler == null) { Bridge bridge = getBridge(); if (bridge == null) { logger.debug("Bride cannot be found"); return null; } ThingHandler handler = bridge.getHandler(); if (handler instanceof BridgeHandler) { dssBridgeHandler = (BridgeHandler) handler; <START> dssBridgeHandler.registerDeviceStatusListener(this); <END> } else { return null; } } if (circuit == null) { dssBridgeHandler.registerDeviceStatusListener(this); } return dssBridgeHandler; }</code><technical_language>I is a bad coding style register a listener in a get method. Imagine code changes this.dssBridgeHandler is set null somewhere, register a listener again..</technical_language>

Target:
private synchronized BridgeHandler getDssBridgeHandler() { if (this.dssBridgeHandler == null) { Bridge bridge = getBridge(); if (bridge == null) { logger.debug("Bride cannot be found"); return null; } ThingHandler handler = bridge.getHandler(); if (handler instanceof BridgeHandler) { dssBridgeHandler = (BridgeHandler) handler; } else { return null; } } return dssBridgeHandler; }
Source:
<code>public List<Callable<DocumentRevsList>> createTasks(List<String> ids, Map<String, Collection<String>> revisions) { List<Callable<DocumentRevsList>> tasks = new ArrayList<Callable<DocumentRevsList>>(); for(String id : ids) { if(id.isEmpty()){ continue; <START> } <END> HashSet<String> possibleAncestors = new HashSet<String>(); for (String revId : revisions.get(id)) { List<String> thesePossibleAncestors = targetDb.getDbCore().getPossibleAncestorRevisionIDs(id, revId, 50); if (thesePossibleAncestors != null) { possibleAncestors.addAll(thesePossibleAncestors); } } tasks.add(GetRevisionTask.createGetRevisionTask(this.sourceDb, id, revisions.get(id), possibleAncestors, config.pullAttachmentsInline)); } return tasks; }</code><technical_language>Possibly output a debug log message a changes feed entry empty ID ignoring it</technical_language>

Target:
public List<Callable<DocumentRevsList>> createTasks(List<String> ids, Map<String, Collection<String>> revisions) { List<Callable<DocumentRevsList>> tasks = new ArrayList<Callable<DocumentRevsList>>(); for(String id : ids) { if(id.isEmpty()){ logger.info("Found document with empty ID in change feed, skipping"); continue; } HashSet<String> possibleAncestors = new HashSet<String>(); for (String revId : revisions.get(id)) { List<String> thesePossibleAncestors = targetDb.getDbCore().getPossibleAncestorRevisionIDs(id, revId, 50); if (thesePossibleAncestors != null) { possibleAncestors.addAll(thesePossibleAncestors); } } tasks.add(GetRevisionTask.createGetRevisionTask(this.sourceDb, id, revisions.get(id), possibleAncestors, config.pullAttachmentsInline)); } return tasks; }
Source:
<code>public void onTimeout(Continuation self) { WorkQueue.Executor executor; <START> if (userProvider.get().isBatchUser()) { <END> executor = queue.getBatchQueue(); } else { executor = queue.getInteractiveQueue(); } executor.remove(this); }</code><technical_language>this block is twice, pull a private method</technical_language>

Target:
public void onTimeout(Continuation self) { WorkQueue.Executor executor = getExecutor(); executor.remove(this); }
Source:
<code>public void buildObject_disapproved_candidates() throws Exception { ProjectToOrganizationConverter converter = new ProjectToOrganizationConverter( <START> new ResultApprover() { <END> @Override public boolean approveBeforeBuilding(Oaf oaf) { return false; } }, relationColumnFamilyBytes); String projectId = "someProjectId"; String organizationId = "someOrgId"; NavigableMap<byte[],byte[]> navigableMap = new TreeMap<byte[],byte[]>( UnsignedBytes.lexicographicalComparator()); navigableMap.put(organizationId.getBytes(), createOafObject(projectId, organizationId).toByteArray()); when(result.getFamilyMap(relationColumnFamilyBytes)).thenReturn(navigableMap); Collection<ProjectToOrganization> projOrgs = converter.buildObject(result, oaf); assertNotNull(projOrgs); assertTrue(projOrgs.isEmpty()); }</code><technical_language>If a mock a resultApprover override approveBeforeBuilding method here</technical_language>

Target:
public void buildObject_disapproved_candidates() throws Exception { when(defaultApprover.approveBeforeBuilding(any())).thenReturn(false); ProjectToOrganizationConverter converter = new ProjectToOrganizationConverter(defaultApprover, relationColumnFamilyBytes); String projectId = "someProjectId"; String organizationId = "someOrgId"; NavigableMap<byte[], byte[]> navigableMap = new TreeMap<byte[], byte[]>( UnsignedBytes.lexicographicalComparator()); navigableMap.put(organizationId.getBytes(), createOafObject(projectId, organizationId).toByteArray()); when(result.getFamilyMap(relationColumnFamilyBytes)).thenReturn(navigableMap); Collection<ProjectToOrganization> projOrgs = converter.buildObject(result, oaf); assertNotNull(projOrgs); assertTrue(projOrgs.isEmpty()); }
Source:
<code>public SearchParameterMap getSearchParameterMapFromCriteria(String theTargetType, String theCriteria) { SearchParameterMap spMap; <START> if (!StringUtils.isBlank(theCriteria)) { <END> spMap = mapFromCriteria(theTargetType, theCriteria); } else { spMap = new SearchParameterMap(); } return spMap; }</code><technical_language>nitpick: I code reads easier put positive case negating a conditional</technical_language>

Target:
public SearchParameterMap getSearchParameterMapFromCriteria(String theTargetType, String theCriteria) { SearchParameterMap spMap; if (StringUtils.isBlank(theCriteria)) { spMap = new SearchParameterMap(); } else { spMap = mapFromCriteria(theTargetType, theCriteria); } return spMap; }
Source:
<code>public BruteForce (ScanTarget target, File file, BruteForceListenner listenner, BruteForceParam bruteForceParam) { this.target = target; this.file = file; this.directory = null; this.listenner = listenner; this.threads = bruteForceParam.getThreadPerScan(); this.recursive = bruteForceParam.getRecursive(); this.onlyUnderDirectory = false; this.tableModel = new BruteForceTableModel(); log.info("BruteForce : " + target.getURI() + "/" + directory + " threads: " + threads); manager = new DirBusterManager(this); manager.setDefaultNoThreads(threads); ConnectionParam conParam = Model.getSingleton().getOptionsParam().getConnectionParam(); if (conParam.isUseProxy(target.getHost())) { manager.setProxyRealm(Model.getSingleton().getOptionsParam().getConnectionParam().getProxyChainRealm()); manager.setProxyHost(conParam.getProxyChainName()); manager.setProxyPort(conParam.getProxyChainPort()); manager.setProxyUsername(conParam.getProxyChainUserName()); manager.setProxyPassword(conParam.getProxyChainPassword()); manager.setUseProxy(true); manager.setUseProxyAuth(true); log.debug("BruteForce : set proxy to " + manager.getProxyHost() + ":" + manager.getProxyPort()); } if (bruteForceParam.isBrowseFiles()) { extensions = bruteForceParam.getFileExtensionsList(); } else { extensions = Collections.emptyList(); } <START> extsToMissVector = new Vector<>(bruteForceParam.getExtensionsToMissSet()); <END> }</code><technical_language>I suggesting change extsToMiss directly, e.g.: manager.extsToMiss.addAll(bruteForceParam.getExtensionsToMissSet()) (which avoids changing setupManager)</technical_language>

Target:
public BruteForce (ScanTarget target, File file, BruteForceListenner listenner, BruteForceParam bruteForceParam) { this.target = target; this.file = file; this.directory = null; this.listenner = listenner; this.threads = bruteForceParam.getThreadPerScan(); this.recursive = bruteForceParam.getRecursive(); this.onlyUnderDirectory = false; this.tableModel = new BruteForceTableModel(); log.info("BruteForce : " + target.getURI() + "/" + directory + " threads: " + threads); manager = new DirBusterManager(this); manager.setDefaultNoThreads(threads); ConnectionParam conParam = Model.getSingleton().getOptionsParam().getConnectionParam(); if (conParam.isUseProxy(target.getHost())) { manager.setProxyRealm(Model.getSingleton().getOptionsParam().getConnectionParam().getProxyChainRealm()); manager.setProxyHost(conParam.getProxyChainName()); manager.setProxyPort(conParam.getProxyChainPort()); manager.setProxyUsername(conParam.getProxyChainUserName()); manager.setProxyPassword(conParam.getProxyChainPassword()); manager.setUseProxy(true); manager.setUseProxyAuth(true); log.debug("BruteForce : set proxy to " + manager.getProxyHost() + ":" + manager.getProxyPort()); } if (bruteForceParam.isBrowseFiles()) { extensions = bruteForceParam.getFileExtensionsList(); } else { extensions = Collections.emptyList(); } manager.extsToMiss.addAll(bruteForceParam.getExtensionsToMissSet()); }
Source:
<code>public byte[] getCacheKey() { byte[] dimensionBytes = StringUtils.toUtf8(this.getDimension()); byte[] lowerBytes = this.getLower() == null ? new byte[0] : StringUtils.toUtf8(this.getLower()); byte[] upperBytes = this.getUpper() == null ? new byte[0] : StringUtils.toUtf8(this.getUpper()); byte boundType = 0x1; if (this.getLower() == null) { boundType = 0x2; } else if (this.getUpper() == null) { boundType = 0x3; } byte lowerStrictByte = (this.isLowerStrict() == false) ? 0x0 : (byte) 1; byte upperStrictByte = (this.isUpperStrict() == false) ? 0x0 : (byte) 1; byte AlphaNumericByte = (this.isAlphaNumeric() == false) ? 0x0 : (byte) 1; <START> byte[] extractionFnBytes = extractionFn.getCacheKey(); <END> ByteBuffer boundCacheBuffer = ByteBuffer.allocate( 9 + dimensionBytes.length + upperBytes.length + lowerBytes.length + extractionFnBytes.length ); boundCacheBuffer.put(DimFilterCacheHelper.BOUND_CACHE_ID) .put(boundType) .put(upperStrictByte) .put(lowerStrictByte) .put(AlphaNumericByte) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(dimensionBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(upperBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(lowerBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(extractionFnBytes); return boundCacheBuffer.array(); }</code><technical_language>extractionFn null, please include a cacheKey test for this</technical_language>

Target:
public byte[] getCacheKey() { byte[] dimensionBytes = StringUtils.toUtf8(this.getDimension()); byte[] lowerBytes = this.getLower() == null ? new byte[0] : StringUtils.toUtf8(this.getLower()); byte[] upperBytes = this.getUpper() == null ? new byte[0] : StringUtils.toUtf8(this.getUpper()); byte boundType = 0x1; if (this.getLower() == null) { boundType = 0x2; } else if (this.getUpper() == null) { boundType = 0x3; } byte lowerStrictByte = (this.isLowerStrict() == false) ? 0x0 : (byte) 1; byte upperStrictByte = (this.isUpperStrict() == false) ? 0x0 : (byte) 1; byte AlphaNumericByte = (this.isAlphaNumeric() == false) ? 0x0 : (byte) 1; byte[] extractionFnBytes = extractionFn == null ? new byte[0] : extractionFn.getCacheKey(); ByteBuffer boundCacheBuffer = ByteBuffer.allocate( 9 + dimensionBytes.length + upperBytes.length + lowerBytes.length + extractionFnBytes.length ); boundCacheBuffer.put(DimFilterCacheHelper.BOUND_CACHE_ID) .put(boundType) .put(upperStrictByte) .put(lowerStrictByte) .put(AlphaNumericByte) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(dimensionBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(upperBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(lowerBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(extractionFnBytes); return boundCacheBuffer.array(); }
Source:
<code>public boolean check(VM vm) { if (vm.getStatus() == VMStatus.Suspended || vm.getStatus() == VMStatus.SavingState || vm.getStatus() == VMStatus.RestoringState) { Version vmCustomCompatibilityVersion = vm.getCustomCompatibilityVersion(); return vmCustomCompatibilityVersion == null ? false <START> : vmCustomCompatibilityVersion.greaterOrEquals(newClusterVersion); <END> } return true; }</code><technical_language>If VM's custom compatibility version is set, cluster's compatibility version is ignored. means need display warning, changed for VM</technical_language>

Target:
public boolean check(VM vm) { if (vm.getStatus() == VMStatus.Suspended || vm.getStatus() == VMStatus.SavingState || vm.getStatus() == VMStatus.RestoringState) { return vm.getCustomCompatibilityVersion() == null; } return true; }
Source:
<code>public synchronized void destroy() { <START> logger.debug("Destroying CoAP endpoint.", new Exception("Endpoint destroyed")); <END> super.destroy(); }</code><technical_language>add enclosing "if is debug log is enabled"? exception instance is created of log level class instance needs catch stack trace etc. creation of exception stack trace array building a expensive operation? exception is for logging care class is used, I prefer a runtime :wink: (if care)</technical_language>

Target:
public synchronized void destroy() { if (logger.isDebugEnabled()) { logger.debug("Destroying CoAP endpoint.", new RuntimeException("Endpoint destroyed")); } super.destroy(); }
Source:
<code>public void shouldNotCaptureIfPaymentProviderReturnsNon200HttpStatusCode() { Either<GatewayError, GatewayClient.Response> response = left(genericGatewayError("Unexpected HTTP status code 400 from gateway")); when(client.postRequestFor(anyString(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(response); CaptureResponse gatewayResponse = epdqCaptureHandler.capture(buildTestCaptureRequest()); assertThat(gatewayResponse.isSuccessful(), is(false)); assertThat(gatewayResponse.getError().isPresent(), is(true)); assertThat(gatewayResponse.getError().get().getMessage(), is("Unexpected HTTP status code 400 from gateway")); <START> assertThat(gatewayResponse.getError().get().getErrorType(), is(GENERIC_GATEWAY_ERROR)); <END> }</code><technical_language>codes replaced map GATEWAY_CONNECTION_ERROR? I some of calling genericGatewayError() calling new gatewayConnectionError()</technical_language>

Target:
public void shouldNotCaptureIfPaymentProviderReturnsNon200HttpStatusCode() { Either<GatewayError, GatewayClient.Response> response = left(gatewayConnectionError("Unexpected HTTP status code 400 from gateway")); when(client.postRequestFor(anyString(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(response); CaptureResponse gatewayResponse = epdqCaptureHandler.capture(buildTestCaptureRequest()); assertThat(gatewayResponse.isSuccessful(), is(false)); assertThat(gatewayResponse.getError().isPresent(), is(true)); assertThat(gatewayResponse.getError().get().getMessage(), is("Unexpected HTTP status code 400 from gateway")); assertThat(gatewayResponse.getError().get().getErrorType(), is(GATEWAY_CONNECTION_ERROR)); }
Source:
<code>@Override public void unparseCall(final SqlWriter writer, final SqlCall call, final int leftPrec, final int rightPrec) { switch (call.getKind()) { case POSITION: final SqlWriter.Frame frame = writer.startFunCall("STRPOS"); writer.sep(","); call.operand(1).unparse(writer, leftPrec, rightPrec); writer.sep(","); call.operand(0).unparse(writer, leftPrec, rightPrec); if (3 == call.operandCount()) { throw new RuntimeException("3rd operand Not Supported for Function STRPOS in Big Query"); } writer.endFunCall(frame); break; case UNION: if (!((SqlSetOperator) call.getOperator()).isAll()) { SqlSyntax.BINARY.unparse(writer, UNION_DISTINCT, call, leftPrec, rightPrec); } else { super.unparseCall(writer, call, leftPrec, rightPrec); } break; case EXCEPT: if (!((SqlSetOperator) call.getOperator()).isAll()) { SqlSyntax.BINARY.unparse(writer, EXCEPT_DISTINCT, call, leftPrec, rightPrec); } else { <START> super.unparseCall(writer, call, leftPrec, rightPrec); <END> } break; case INTERSECT: if (!((SqlSetOperator) call.getOperator()).isAll()) { SqlSyntax.BINARY.unparse(writer, INTERSECT_DISTINCT, call, leftPrec, rightPrec); } else { super.unparseCall(writer, call, leftPrec, rightPrec); } break; default: super.unparseCall(writer, call, leftPrec, rightPrec); } }</code><technical_language>Is test cases for this change</technical_language>

Target:
@Override public void unparseCall(final SqlWriter writer, final SqlCall call, final int leftPrec, final int rightPrec) { switch (call.getKind()) { case POSITION: final SqlWriter.Frame frame = writer.startFunCall("STRPOS"); writer.sep(","); call.operand(1).unparse(writer, leftPrec, rightPrec); writer.sep(","); call.operand(0).unparse(writer, leftPrec, rightPrec); if (3 == call.operandCount()) { throw new RuntimeException("3rd operand Not Supported for Function STRPOS in Big Query"); } writer.endFunCall(frame); break; case UNION: if (!((SqlSetOperator) call.getOperator()).isAll()) { SqlSyntax.BINARY.unparse(writer, UNION_DISTINCT, call, leftPrec, rightPrec); } else { super.unparseCall(writer, call, leftPrec, rightPrec); } break; case EXCEPT: SqlSyntax.BINARY.unparse(writer, EXCEPT_DISTINCT, call, leftPrec, rightPrec); break; case INTERSECT: SqlSyntax.BINARY.unparse(writer, INTERSECT_DISTINCT, call, leftPrec, rightPrec); break; default: super.unparseCall(writer, call, leftPrec, rightPrec); } }
Source:
<code>public Cost getCost() throws SQLException { Long byteCount = getEstimatedBytesToScan(); if (byteCount == null) { return Cost.ZERO; } <START> int parallelLevel = 10; <END> Cost cost = CostUtil.estimateAggregateCost(byteCount, !groupBy.isUngroupedAggregate(), aggregators.getEstimatedByteSize(), parallelLevel); if (!orderBy.getOrderByExpressions().isEmpty()) { double outputBytes = CostUtil.estimateAggregateOutputBytes( byteCount, !groupBy.isUngroupedAggregate(), aggregators.getEstimatedByteSize()); Cost orderByCost = CostUtil.estimateOrderByCost(outputBytes, parallelLevel); cost = cost.plus(orderByCost); } return cost; }</code><technical_language>passing in groupBy instead of groupBy.isUngroupedAggregate() I want get more info eventually out of groupBy (for example, if ordered unordered impacts memory usage substantially)</technical_language>

Target:
public Cost getCost() { Long byteCount = null; try { byteCount = getEstimatedBytesToScan(); } catch (SQLException e) { } if (byteCount == null) { return Cost.UNKNOWN; } int parallelLevel = CostUtil.estimateParallelLevel( true, context.getConnection().getQueryServices()); Cost cost = CostUtil.estimateAggregateCost(byteCount, groupBy, aggregators.getEstimatedByteSize(), parallelLevel); if (!orderBy.getOrderByExpressions().isEmpty()) { double outputBytes = CostUtil.estimateAggregateOutputBytes( byteCount, groupBy, aggregators.getEstimatedByteSize()); Cost orderByCost = CostUtil.estimateOrderByCost(outputBytes, parallelLevel); cost = cost.plus(orderByCost); } return cost; }
Source:
<code>public void shouldThrowNullPointerExceptionWhenSchemaIsNull() { <START> updateSplitSchema(null, EMPTY_LIST); <END> }</code><technical_language>nit: ImmutableList.of() instead of EMPTY_LIST additional benefit of rid of unchecked assignment warning</technical_language>

Target:
public void shouldThrowNullPointerExceptionWhenSchemaIsNull() { updateSplitSchema(null, ImmutableList.of()); }
Source:
<code>SshFetchConnection() throws TransportException { super(TransportGitSsh.this); try { process = getSession().exec(commandFor(getOptionUploadPack()), getTimeout()); final MessageWriter msg = new MessageWriter(); setMessageWriter(msg); final InputStream upErr = process.getErrorStream(); errorThread = new StreamCopyThread(upErr, msg.getRawStream()); errorThread.start(); init(process.getInputStream(), process.getOutputStream()); } catch (TransportException err) { try { close(); <START> } catch (Exception e) { <END> } throw err; } catch (Throwable err) { try { close(); } catch (Error e) { } throw new TransportException(uri, JGitText.get().remoteHungUpUnexpectedly, err); } try { readAdvertisedRefs(); } catch (NoRemoteRepositoryException notFound) { final String msgs = getMessages(); checkExecFailure(process.exitValue(), getOptionUploadPack(), msgs); throw cleanNotFound(notFound, msgs); } }</code><technical_language>I extra try catch blocks unnecessary</technical_language>

Target:
SshFetchConnection() throws TransportException { super(TransportGitSsh.this); try { process = getSession().exec(commandFor(getOptionUploadPack()), getTimeout()); final MessageWriter msg = new MessageWriter(); setMessageWriter(msg); final InputStream upErr = process.getErrorStream(); errorThread = new StreamCopyThread(upErr, msg.getRawStream()); errorThread.start(); init(process.getInputStream(), process.getOutputStream()); } catch (TransportException err) { close(); throw err; } catch (Throwable err) { close(); throw new TransportException(uri, JGitText.get().remoteHungUpUnexpectedly, err); } try { readAdvertisedRefs(); } catch (NoRemoteRepositoryException notFound) { final String msgs = getMessages(); checkExecFailure(process.exitValue(), getOptionUploadPack(), msgs); throw cleanNotFound(notFound, msgs); } }