auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void connectComponentsAndRequestSlot( JobMasterGateway jobMasterGateway, ResourceManagerGateway resourceManagerGateway, TaskExecutorGateway taskExecutorGateway, JobLeaderService jobLeaderService, CompletableFuture<SlotReport> initialSlotReportFuture, AllocationID allocationId) throws Exception { final String jobMasterAddress = "jm"; rpc.registerGateway(jobMasterAddress, jobMasterGateway); rpc.registerGateway(resourceManagerGateway.getAddress(), resourceManagerGateway); jobLeaderService.addJob(jobId, jobMasterAddress); jobManagerLeaderRetriever.notifyListener(jobMasterAddress, UUID.randomUUID()); resourceManagerLeaderRetriever.notifyListener(resourceManagerGateway.getAddress(), resourceManagerGateway.getFencingToken().toUUID()); final Optional<SlotStatus> slotStatusOptional = StreamSupport.stream(initialSlotReportFuture.get().spliterator(), false) .findAny(); assertTrue(slotStatusOptional.isPresent()); <START> while (true) { try { taskExecutorGateway.requestSlot( slotStatusOptional.get().getSlotID(), jobId, allocationId, ResourceProfile.ZERO, jobMasterAddress, resourceManagerGateway.getFencingToken(), timeout ).get(); break; } catch (Exception e) { Thread.sleep(50); } } <END> }</code><technical_language>If want wait TaskExecutor established connection ResourceManager, wait for ResourceManagerGateway.sendSlotReport call</technical_language>

Target:
private void connectComponentsAndRequestSlot( JobMasterGateway jobMasterGateway, ResourceManagerGateway resourceManagerGateway, TaskExecutorGateway taskExecutorGateway, JobLeaderService jobLeaderService, CompletableFuture<SlotReport> initialSlotReportFuture, AllocationID allocationId) throws Exception { final String jobMasterAddress = "jm"; RPC_SERVICE_RESOURCE.getTestingRpcService().registerGateway(jobMasterAddress, jobMasterGateway); RPC_SERVICE_RESOURCE.getTestingRpcService().registerGateway(resourceManagerGateway.getAddress(), resourceManagerGateway); jobLeaderService.addJob(jobId, jobMasterAddress); jobManagerLeaderRetriever.notifyListener(jobMasterAddress, UUID.randomUUID()); resourceManagerLeaderRetriever.notifyListener(resourceManagerGateway.getAddress(), resourceManagerGateway.getFencingToken().toUUID()); final Optional<SlotStatus> slotStatusOptional = StreamSupport.stream(initialSlotReportFuture.get().spliterator(), false) .findAny(); assertTrue(slotStatusOptional.isPresent()); taskExecutorGateway.requestSlot( slotStatusOptional.get().getSlotID(), jobId, allocationId, ResourceProfile.ZERO, jobMasterAddress, resourceManagerGateway.getFencingToken(), timeout ).get(); }
Source:
<code>public static org.kie.dmn.model.api.Definitions dmnFromWB(final Definitions wb) { if (wb == null) { return null; } org.kie.dmn.model.api.Definitions result = new org.kie.dmn.model.v1_1.TDefinitions(); String defaultId = (wb.getId() != null) ? wb.getId().getValue() : UUID.uuid(); String defaulName = (wb.getName() != null) ? wb.getName().getValue() : UUID.uuid(8); String defaultNamespace = (wb.getNamespace() != null) ? wb.getNamespace() : "<LINK_0>"; result.setId(defaultId); result.setName(defaulName); result.setNamespace(defaultNamespace); result.setDescription(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); result.getNsContext().putAll(wb.getNsContext()); <START> result.getNsContext().put(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(), <END> DMNModelInstrumentedBase.Namespace.DEFAULT.getUri()); for (ItemDefinition itemDef : wb.getItemDefinition()) { org.kie.dmn.model.api.ItemDefinition itemDefConvered = ItemDefinitionPropertyConverter.dmnFromWB(itemDef); result.getItemDefinition().add(itemDefConvered); } if (!result.getPrefixForNamespaceURI(DMNDiagram.DMNV11_DD).isPresent()) { result.getNsContext().put("dmndi", DMNDiagram.DMNV11_DD); } if (!result.getPrefixForNamespaceURI(DMNDiagram.DMNV11_DC).isPresent()) { result.getNsContext().put("dc", DMNDiagram.DMNV11_DC); } if (!result.getPrefixForNamespaceURI(DMNDiagram.DMNV11_DI).isPresent()) { result.getNsContext().put("di", DMNDiagram.DMNV11_DI); } for (Import i : wb.getImport()) { result.getImport().add(ImportConverter.dmnFromNode(i)); } return result; }</code><technical_language>Again, I check if a default name space exists overwriting here</technical_language>

Target:
public static org.kie.dmn.model.api.Definitions dmnFromWB(final Definitions wb) { if (wb == null) { return null; } org.kie.dmn.model.api.Definitions result = new org.kie.dmn.model.v1_2.TDefinitions(); String defaultId = (wb.getId() != null) ? wb.getId().getValue() : UUID.uuid(); String defaulName = (wb.getName() != null) ? wb.getName().getValue() : UUID.uuid(8); String defaultNamespace = !StringUtils.isEmpty(wb.getNamespace()) ? wb.getNamespace() : DMNModelInstrumentedBase.Namespace.DEFAULT.getUri() + UUID.uuid(); result.setId(defaultId); result.setName(defaulName); result.setNamespace(defaultNamespace); result.setDescription(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); result.getNsContext().putAll(wb.getNsContext()); result.getNsContext().put(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(), defaultNamespace); for (ItemDefinition itemDef : wb.getItemDefinition()) { org.kie.dmn.model.api.ItemDefinition itemDefConvered = ItemDefinitionPropertyConverter.dmnFromWB(itemDef); itemDefConvered.setParent(result); result.getItemDefinition().add(itemDefConvered); } for (Import i : wb.getImport()) { result.getImport().add(ImportConverter.dmnFromWb(i)); } return result; }
Source:
<code>public SplitTransition create(AttributeTransitionData data) { String platformTypeString = data.attributes().get(PlatformRule.PLATFORM_TYPE_ATTR_NAME, STRING); String minimumOsVersionString = data.attributes().get(PlatformRule.MINIMUM_OS_VERSION, STRING); PlatformType platformType; Optional<DottedVersion> minimumOsVersion; try { platformType = getPlatformType(platformTypeString); if (Strings.isNullOrEmpty(minimumOsVersionString)) { minimumOsVersion = Optional.absent(); } else { minimumOsVersion = Optional.of(DottedVersion.fromString(minimumOsVersionString)); } <START> } catch (IllegalArgumentException | DottedVersion.InvalidDottedVersionError exception) { <END> platformType = PlatformType.IOS; minimumOsVersion = Optional.absent(); } return new AppleBinaryTransition(platformType, minimumOsVersion); }</code><technical_language>is IllegalArgumentException thrown now</technical_language>

Target:
public SplitTransition create(AttributeTransitionData data) { String platformTypeString = data.attributes().get(PlatformRule.PLATFORM_TYPE_ATTR_NAME, STRING); String minimumOsVersionString = data.attributes().get(PlatformRule.MINIMUM_OS_VERSION, STRING); PlatformType platformType; Optional<DottedVersion> minimumOsVersion; try { platformType = getPlatformType(platformTypeString); if (Strings.isNullOrEmpty(minimumOsVersionString)) { minimumOsVersion = Optional.absent(); } else { minimumOsVersion = Optional.of(DottedVersion.fromString(minimumOsVersionString)); } } catch (ApplePlatform.UnsupportedPlatformTypeException | DottedVersion.InvalidDottedVersionException exception) { platformType = PlatformType.IOS; minimumOsVersion = Optional.absent(); } return new AppleBinaryTransition(platformType, minimumOsVersion); }
Source:
<code>private static Stream<Symbol.MethodSymbol> getAllMembers(Symbol.TypeSymbol symbol, boolean isEnclosed, Set<Symbol> visitedSymbols) { <START> if (!visitedSymbols.add(symbol) || "java.lang.Object".equals(symbol.type().fullyQualifiedName())) { <END> return Stream.empty(); } Stream<Symbol.MethodSymbol> members = Stream.empty(); if (!isEnclosed) { members = symbol.memberSymbols().stream().filter(Symbol::isMethodSymbol).map(Symbol.MethodSymbol.class::cast); } Type superClass = symbol.superClass(); if (superClass != null) { members = Stream.concat(members, getAllMembers(superClass.symbol(), isEnclosed, visitedSymbols)); } Stream<Symbol.MethodSymbol> defaultMethodsFromInterfaces = symbol.interfaces().stream() .flatMap(i -> getAllMembers(i.symbol(), false)) .filter(m -> ((JavaSymbol.MethodJavaSymbol) m).isDefault()); members = Stream.concat(members, defaultMethodsFromInterfaces); for (Symbol s : symbol.memberSymbols()) { if (isNested(s) || isPublicStaticConcrete(s)) { members = Stream.concat(members, getAllMembers((Symbol.TypeSymbol) s, false, visitedSymbols)); } } return members; }</code><technical_language>Minor improvement: suggestion if (!visitedSymbols.add(symbol) || symbol.type().is("java.lang.Object")) { instead</technical_language>

Target:
private static Stream<Symbol.MethodSymbol> getAllMembers(Symbol.TypeSymbol symbol, boolean isEnclosed, Set<Symbol> visitedSymbols) { if (!visitedSymbols.add(symbol) || symbol.type().is("java.lang.Object")) { return Stream.empty(); } Stream<Symbol.MethodSymbol> members = Stream.empty(); if (!isEnclosed) { members = symbol.memberSymbols().stream().filter(Symbol::isMethodSymbol).map(Symbol.MethodSymbol.class::cast); } Type superClass = symbol.superClass(); if (superClass != null) { members = Stream.concat(members, getAllMembers(superClass.symbol(), isEnclosed, visitedSymbols)); } Stream<Symbol.MethodSymbol> defaultMethodsFromInterfaces = symbol.interfaces().stream() .flatMap(i -> getAllMembers(i.symbol(), false)) .filter(m -> ((JavaSymbol.MethodJavaSymbol) m).isDefault()); members = Stream.concat(members, defaultMethodsFromInterfaces); for (Symbol s : symbol.memberSymbols()) { if (isNested(s) || isPublicStaticConcrete(s)) { members = Stream.concat(members, getAllMembers((Symbol.TypeSymbol) s, false, visitedSymbols)); } } return members; }
Source:
<code>static LinkedList<RuntimeException> executeAll(final Runnable... actions) { <START> LinkedList<RuntimeException> suppressed = null; <END> for (final Runnable action : actions) { try { action.run(); } catch (final RuntimeException exception) { if (suppressed == null) { suppressed = new LinkedList<>(); } suppressed.add(exception); } } return suppressed; }</code><technical_language>final return empty list? avoid null if</technical_language>

Target:
static LinkedList<RuntimeException> executeAll(final Runnable... actions) { final LinkedList<RuntimeException> suppressed = new LinkedList<>(); for (final Runnable action : actions) { try { action.run(); } catch (final RuntimeException exception) { suppressed.add(exception); } } return suppressed; }
Source:
<code>public O evaluate(IotasEvent iotasEvent) throws ScriptException { LOG.debug("Evaluating with [{}]", expression, iotasEvent); groovy.lang.Script parsedScript = getParsedScript(); O evaluatedResult = null; if (iotasEvent != null) { final Map<String, Object> fieldsToValues = iotasEvent.getFieldsAndValues(); if (fieldsToValues != null) { try { Binding binding = new Binding(fieldsToValues); parsedScript.setBinding(binding); LOG.debug("Set script binding to [{}]", fieldsToValues); evaluatedResult = (O) parsedScript.run(); LOG.debug("Expression evaluated to [{}]", expression, evaluatedResult); <START> } catch (groovy.lang.MissingPropertyException e) { <END> throw new ScriptException(e); } } } return evaluatedResult; }</code><technical_language>please log a debug message wit expression properties set, debug in case wrong. Thanks</technical_language>

Target:
public O evaluate(IotasEvent iotasEvent) throws ScriptException { LOG.debug("Evaluating with [{}]", expression, iotasEvent); groovy.lang.Script parsedScript = getParsedScript(); O evaluatedResult = null; if (iotasEvent != null) { final Map<String, Object> fieldsToValues = iotasEvent.getFieldsAndValues(); if (fieldsToValues != null) { try { Binding binding = new Binding(fieldsToValues); parsedScript.setBinding(binding); LOG.debug("Set script binding to [{}]", fieldsToValues); evaluatedResult = (O) parsedScript.run(); LOG.debug("Expression evaluated to [{}]", expression, evaluatedResult); } catch (groovy.lang.MissingPropertyException e) { LOG.debug("Missing property: Expression params [{}]", expression, fieldsToValues); throw new ScriptException(e); } } } return evaluatedResult; }
Source:
<code>public List<RichResource> extractData(ResultSet rs) throws SQLException, DataAccessException { Map<Integer, RichResource> map = new HashMap<>(); RichResource myObject; while (rs.next()) { Integer id = rs.getInt("resources_id"); myObject = map.get(id); if(myObject == null){ myObject = RICH_RESOURCE_MAPPER.mapRow(rs, rs.getRow()); map.put(id, myObject); } ResourceTag tag = RESOURCE_TAG_MAPPER.mapRow(rs, rs.getRow()); <START> if (tag != null && tag.getId() != 0 && myObject != null) { <END> myObject.addResourceTag(tag); } } return new ArrayList<>(map.values()); }</code><technical_language>is reason call: RESOURCE_TAG_MAPPER.mapRow(rs, rs.getRow()) if myObject (richResource) is null. call "continue" myObject is null there. log it, is weird</technical_language>

Target:
public List<RichResource> extractData(ResultSet rs) throws SQLException, DataAccessException { Map<Integer, RichResource> map = new HashMap<>(); RichResource myObject; while (rs.next()) { Integer id = rs.getInt("resources_id"); myObject = map.get(id); if(myObject == null){ myObject = RICH_RESOURCE_MAPPER.mapRow(rs, rs.getRow()); if (myObject == null) { log.warn("RICH_RESOURCE_MAPPER returned null during extraction of data."); continue; } map.put(id, myObject); } ResourceTag tag = RESOURCE_TAG_MAPPER.mapRow(rs, rs.getRow()); if (tag != null && tag.getId() != 0) { myObject.addResourceTag(tag); } } return new ArrayList<>(map.values()); }
Source:
<code>public Response awaitResponse() throws Exception { <START> Future<Response> future = remoteFuture; <END> if (future == null) { throw new NullPointerException("Should not happen!"); } return future.get(); }</code><technical_language>return Objects.requireNonNull(remoteFuture).get();</technical_language>

Target:
public Response awaitResponse() throws Exception { return Objects.requireNonNull(remoteFuture).get(); }
Source:
<code>public static FeedRangeInternal tryParse(final String jsonString) { checkNotNull(jsonString, "Argument 'jsonString' must not be null"); final ObjectMapper mapper = Utils.getSimpleObjectMapper(); try { JsonNode rootNode = mapper.readTree(jsonString); JsonNode rangeNode = rootNode.get(Constants.Properties.RANGE); if (rangeNode != null && rangeNode.isObject()) { Range<String> range = new Range<>((ObjectNode)rangeNode); return new FeedRangeEpkImpl(range); } JsonNode pkNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY); if (pkNode != null && pkNode.isArray()) { PartitionKeyInternal pk = mapper.convertValue(pkNode, PartitionKeyInternal.class); return new FeedRangePartitionKeyImpl(pk); } JsonNode pkRangeIdNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID); if (pkRangeIdNode != null && pkRangeIdNode.isTextual()) { return new FeedRangePartitionKeyRangeImpl(pkRangeIdNode.asText()); } return null; } catch (final IOException ioError) { <START> LOGGER.debug("Failed to parse feed range JSON %s", jsonString, ioError); <END> return null; } }</code><technical_language>slf4j logger placeholder instead of %s suggestion LOGGER.debug("Failed parse feed range JSON {}", jsonString, ioError);</technical_language>

Target:
public static FeedRangeInternal tryParse(final String jsonString) { checkNotNull(jsonString, "Argument 'jsonString' must not be null"); final ObjectMapper mapper = Utils.getSimpleObjectMapper(); try { JsonNode rootNode = mapper.readTree(jsonString); JsonNode rangeNode = rootNode.get(Constants.Properties.RANGE); if (rangeNode != null && rangeNode.isObject()) { Range<String> range = new Range<>((ObjectNode)rangeNode); return new FeedRangeEpkImpl(range); } JsonNode pkNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY); if (pkNode != null && pkNode.isArray()) { PartitionKeyInternal pk = mapper.convertValue(pkNode, PartitionKeyInternal.class); return new FeedRangePartitionKeyImpl(pk); } JsonNode pkRangeIdNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID); if (pkRangeIdNode != null && pkRangeIdNode.isTextual()) { return new FeedRangePartitionKeyRangeImpl(pkRangeIdNode.asText()); } return null; } catch (final IOException ioError) { LOGGER.debug("Failed to parse feed range JSON {}", jsonString, ioError); return null; } }
Source:
<code>public static double jaccardIndex(KHyperLogLog a, KHyperLogLog b) { int sizeOfSmallerSet = Math.min(a.minhash.size(), b.minhash.size()); LongSortedSet minUnion = new LongRBTreeSet(a.minhash.keySet()); minUnion.addAll(b.minhash.keySet()); int intersection = 0; int i = 0; <START> for (long key : minUnion) { <END> if (a.minhash.containsKey(key) && b.minhash.containsKey(key)) { intersection++; } i++; if (i >= sizeOfSmallerSet) { break; } } return intersection / (double) sizeOfSmallerSet; }</code><technical_language>This end promoting primitive longs java.lang.Long, find a avoids this</technical_language>

Target:
public static double jaccardIndex(KHyperLogLog a, KHyperLogLog b) { int sizeOfSmallerSet = Math.min(a.minhash.size(), b.minhash.size()); LongSortedSet minUnion = new LongRBTreeSet(a.minhash.keySet()); minUnion.addAll(b.minhash.keySet()); int intersection = 0; int i = 0; LongIterator iterator = minUnion.iterator(); while (iterator.hasNext()) { long key = iterator.nextLong(); if (a.minhash.containsKey(key) && b.minhash.containsKey(key)) { intersection++; } i++; if (i >= sizeOfSmallerSet) { break; } } return intersection / (double) sizeOfSmallerSet; }
Source:
<code>public <C> Expression rewriteWith(RewriterProvider<C> rewriterProvider, Expression expression, C context) { if (expression instanceof LambdaExpression) { LambdaExpression lambdaExpression = (LambdaExpression) expression; return new LambdaExpression(lambdaExpression.getArguments(), rewriteWith(rewriterProvider, lambdaExpression.getBody(), context)); } <START> Map<NodeRef<Expression>, Type> types = getExpressionTypes( <END> session, metadata, sqlParser, typeProvider, expression, emptyList(), WarningCollector.NOOP); return ExpressionTreeRewriter.rewriteWith(rewriterProvider.get(types), expression, context); }</code><technical_language>nit: I feel call expressionTypes</technical_language>

Target:
public <C> Expression rewriteWith(RewriterProvider<C> rewriterProvider, Expression expression, C context) { if (expression instanceof LambdaExpression) { LambdaExpression lambdaExpression = (LambdaExpression) expression; return new LambdaExpression(lambdaExpression.getArguments(), rewriteWith(rewriterProvider, lambdaExpression.getBody(), context)); } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes( session, metadata, sqlParser, typeProvider, expression, emptyList(), WarningCollector.NOOP); return ExpressionTreeRewriter.rewriteWith(rewriterProvider.get(expressionTypes), expression, context); }
Source:
<code>public static void registerBendingWorldGuardFlag() { final FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); try { registry.register(new StateFlag("bending", false)); <START> } catch (final Exception e) { <END> ProjectKorra.log.severe("Unable to register bending WorldGuard Flag"); } }</code><technical_language>want include Exception in log message for debugging purposes. "Unable register bending WorldGuard flag: " + e</technical_language>

Target:
public static void registerBendingWorldGuardFlag() { final FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); try { registry.register(new StateFlag("bending", false)); } catch (final Exception e) { ProjectKorra.log.severe("Unable to register bending WorldGuard flag: " + e); } }
Source:
<code><START> private ArrayList<String> split(String str) { <END> if (StringHelper.isNullOrEmpty(str)) { return null; } return new ArrayList<String>(Arrays.asList(str.split(SEPARATOR))); }</code><technical_language>needed</technical_language>

Target:
private ArrayList<String> split(String str) { if (StringUtils.isEmpty(str)) { return null; } return new ArrayList<String>(Arrays.asList(str.split(SEPARATOR))); }
Source:
<code>private List<String> buildJarFiles(MutableRef<String> primaryJarRef) throws IOException { final List<String> list = new ArrayList<>(); final Path directoryPath = new Path(_jarDirectoryPath); final RemoteIterator<LocatedFileStatus> files = _fileSystem.listFiles(directoryPath, false); while (files.hasNext()) { final LocatedFileStatus file = files.next(); final Path path = file.getPath(); final String filename = path.getName(); <START> boolean primaryJar = false; <END> for (String prefix : PRIMARY_JAR_FILENAME_PREFIXES) { if (filename.startsWith(prefix)) { primaryJarRef.set(path.toString()); break; } } if (!primaryJar) { list.add(path.toString()); } } if (primaryJarRef.get() == null) { throw new IllegalArgumentException("Failed to find primary jar (starting with '" + PRIMARY_JAR_FILENAME_PREFIXES[0] + "') in JAR file directory: " + _jarDirectoryPath); } return list; }</code><technical_language>This set else</technical_language>

Target:
private List<String> buildJarFiles(MutableRef<String> primaryJarRef) throws IOException { final List<String> list = new ArrayList<>(); final Path directoryPath = new Path(_jarDirectoryPath); final RemoteIterator<LocatedFileStatus> files = _fileSystem.listFiles(directoryPath, false); while (files.hasNext()) { final LocatedFileStatus file = files.next(); final Path path = file.getPath(); final String filename = path.getName(); boolean primaryJar = false; for (String prefix : PRIMARY_JAR_FILENAME_PREFIXES) { if (filename.startsWith(prefix)) { primaryJarRef.set(path.toString()); primaryJar = true; break; } } if (!primaryJar) { list.add(path.toString()); } } if (primaryJarRef.get() == null) { throw new IllegalArgumentException("Failed to find primary jar (starting with '" + PRIMARY_JAR_FILENAME_PREFIXES[0] + "') in JAR file directory: " + _jarDirectoryPath); } return list; }
Source:
<code>public List<Job> get(final List<String> jids) throws IOException { <START> final List<Job> jobList = new ArrayList<>(); <END> for (final String jid : jids) { jobList.add(this.get(jid)); } return jobList; }</code><technical_language>This is fine for a stub implementation. clear tests, this multiget command (<LINK_0> multiple jobs in a single round-trip. This in flavors: java public List<Job> get(final List<String> jids) public List<Job> get(final String... jids) {}</technical_language>

Target:
public List<Job> get(final List<String> jids) throws IOException { final Object result = this.client.call( LuaCommand.MULTIGET.toString(), jids); final InjectableValues inject = new InjectableValues.Std().addValue( "client", this.client); final JavaType javaType = new ObjectMapper().getTypeFactory() .constructCollectionType(ArrayList.class, Job.class); return JsonUtils.parse(result.toString(), javaType, inject); }
Source:
<code>public void saveOrder_shouldSetOrderTypeOfTestOrderToTestOrderIfNotSetAndConceptNotMapped() throws Exception { TestOrder testOrder = new TestOrder(); testOrder.setPatient(patientService.getPatient(7)); <START> testOrder.setConcept(conceptService.getConcept(113)); <END> testOrder.setOrderer(providerService.getProvider(1)); testOrder.setCareSetting(orderService.getCareSetting(1)); Encounter encounter = encounterService.getEncounter(3); testOrder.setEncounter(encounter); testOrder.setStartDate(encounter.getEncounterDatetime()); testOrder.setClinicalHistory("Patient had a negative reaction to the test in the past"); testOrder.setFrequency(orderService.getOrderFrequency(3)); testOrder.setSpecimenSource(conceptService.getConcept(22)); testOrder.setNumberOfRepeats(3); orderService.saveOrder(testOrder,null); Assert.assertNotNull(testOrder.getOrderType()); Assert.assertEquals(orderService.getOrderTypeByUuid(OrderType.TEST_ORDER_TYPE_UUID),testOrder.getOrderType()); }</code><technical_language>here, add assertion ensures this concept is mapped order type</technical_language>

Target:
public void saveOrder_shouldSetOrderTypeOfTestOrderToTestOrderIfNotSetAndConceptNotMapped() throws Exception { TestOrder testOrder = new TestOrder(); testOrder.setPatient(patientService.getPatient(7)); Concept unmappedConcept = conceptService.getConcept(113); Assert.assertNull(orderService.getOrderTypeByConcept(unmappedConcept)); testOrder.setConcept(unmappedConcept); testOrder.setOrderer(providerService.getProvider(1)); testOrder.setCareSetting(orderService.getCareSetting(1)); Encounter encounter = encounterService.getEncounter(3); testOrder.setEncounter(encounter); testOrder.setStartDate(encounter.getEncounterDatetime()); testOrder.setClinicalHistory("Patient had a negative reaction to the test in the past"); testOrder.setFrequency(orderService.getOrderFrequency(3)); testOrder.setSpecimenSource(conceptService.getConcept(22)); testOrder.setNumberOfRepeats(3); orderService.saveOrder(testOrder,null); Assert.assertNotNull(testOrder.getOrderType()); Assert.assertEquals(orderService.getOrderTypeByUuid(OrderType.TEST_ORDER_TYPE_UUID),testOrder.getOrderType()); }
Source:
<code>public AnnotateWidget(Context context, QuestionDetails prompt) { super(context, prompt); imageClickHandler = new DrawImageClickHandler(DrawActivity.OPTION_ANNOTATE, RequestCodes.ANNOTATE_IMAGE, R.string.annotate_image); imageCaptureHandler = new ImageCaptureHandler(); setUpLayout(); addCurrentImageToLayout(); <START> if (errorLoadingImage) { <END> annotateButton.setEnabled(false); } addAnswerView(answerLayout, WidgetViewUtils.getStandardMargin(context)); }</code><technical_language>I need this all... a check like? if (binaryName == null || imageView == null || imageView.getVisibility() == GONE) { annotateButton.setEnabled(false); } is a similar check: if (binaryName == null) { annotateButton.setEnabled(false); } in setUpLayout() method remove there</technical_language>

Target:
public AnnotateWidget(Context context, QuestionDetails prompt) { super(context, prompt); imageClickHandler = new DrawImageClickHandler(DrawActivity.OPTION_ANNOTATE, RequestCodes.ANNOTATE_IMAGE, R.string.annotate_image); imageCaptureHandler = new ImageCaptureHandler(); setUpLayout(); addCurrentImageToLayout(); adjustAnnotateButtonAvailability(); addAnswerView(answerLayout, WidgetViewUtils.getStandardMargin(context)); }
Source:
<code>public void validate(String s) { NumberRepresentation br = new NumberRepresentation( s, true, true, false ) { @Override void parse(String val, int radix) { if ( radix == 10 ) { Long.parseLong( val, radix ); } <START> else { <END> if ( new BigInteger( val, radix ).bitLength() > 64 ) { throw new NumberFormatException( "integer number too large" ); } } } }; br.validate(); }</code><technical_language>else if</technical_language>

Target:
public void validate(String s) { NumberRepresentation br = new NumberRepresentation( s, true, true, false ) { @Override void parse(String val, int radix) { if ( radix == 10 ) { Long.parseLong( val, radix ); } else if ( new BigInteger( val, radix ).bitLength() > 64 ) { throw new NumberFormatException( "integer number too large" ); } } }; br.validate(); }
Source:
<code>InternationalFixedDate plusYears(final long yearsToAdd) { if (yearsToAdd == 0) { return this; } int newYear = (int) Math.addExact(getProlepticYear(), yearsToAdd); if (isYearDay()) { return create(newYear, false, true); } int day = getDayOfMonth(); int newMonth = getCalculatedMonth(); if (isLeapDay()) { <START> if ((yearsToAdd & 3) == 0) { <END> return create(newYear, true, false); } day = 1; } return create(newYear, newMonth, day); }</code><technical_language>Forgot century years. This is original resolvePrevious(year, month, day) is for. default behavior enough (where invokes plusMonths(...))</technical_language>

Target:
InternationalFixedDate plusYears(final long yearsToAdd) { if (yearsToAdd == 0) { return this; } int newYear = YEAR_RANGE.checkValidIntValue(Math.addExact(this.prolepticYear, yearsToAdd), ChronoField.YEAR); return resolvePreviousValid(newYear, this.month, this.day); }
Source:
<code>public void after() { <START> fTrace.dispose(); <END> }</code><technical_language>technically, null check</technical_language>

Target:
public void after() { if (fTrace == null) { fTrace.dispose(); } }
Source:
<code>private List<File> loadFiles(File workingDir) { <START> System.out.println(workingDir.getAbsolutePath()); <END> List<File> dataFile = new ArrayList<File>(); if (workingDir.exists()) { File[] files = workingDir.listFiles(); for (File eachFile : files) { if (eachFile.isDirectory()) { dataFile.addAll(loadFiles(eachFile)); } else if (eachFile.getName().endsWith(".yaml")) { dataFile.add(eachFile); } } } return dataFile; }</code><technical_language>Is this System.out required</technical_language>

Target:
private List<File> loadFiles(File workingDir) { List<File> dataFile = new ArrayList<File>(); if (workingDir.exists()) { File[] files = workingDir.listFiles(); for (File eachFile : files) { if (eachFile.isDirectory()) { dataFile.addAll(loadFiles(eachFile)); } else if (eachFile.getName().endsWith(".yaml")) { dataFile.add(eachFile); } } } return dataFile; }
Source:
<code>public static Map<Integer, List<IntermediateEntry>> hashByKey(List<IntermediateEntry> entries) { Map<Integer, List<IntermediateEntry>> hashed = new HashMap<>(); for (IntermediateEntry entry : entries) { if (hashed.containsKey(entry.getPartId())) { hashed.get(entry.getPartId()).add(entry); } else { List inputList = new ArrayList<>(); inputList.addAll(Arrays.asList(entry)); <START> hashed.put(entry.getPartId(), inputList); <END> } } return hashed; }</code><technical_language>rewritten Arrays.asList()</technical_language>

Target:
public static Map<Integer, List<IntermediateEntry>> hashByKey(List<IntermediateEntry> entries) { Map<Integer, List<IntermediateEntry>> hashed = new HashMap<>(); for (IntermediateEntry entry : entries) { if (hashed.containsKey(entry.getPartId())) { hashed.get(entry.getPartId()).add(entry); } else { hashed.put(entry.getPartId(), Arrays.asList(entry)); } } return hashed; }
Source:
<code>public void addStreamEventUptoMaxSize(StreamEvent streamEvent) { int sizeAfterAdding = 0; ComplexEventChunk<StreamEvent> addEventsLimitCopy = new ComplexEventChunk<>(true); StreamEvent streamEventIter; while (true) { sizeAfterAdding++; streamEventIter = streamEvent.getNext(); if (sizeAfterAdding == maxSize || streamEventIter.getNext() == null) { streamEventIter.setNext(null); break; } } <START> addEventsLimitCopy.add(streamEvent); <END> readWriteLock.writeLock().lock(); try { this.add(addEventsLimitCopy); } finally { readWriteLock.writeLock().unlock(); } }</code><technical_language>events public ComplexEventChunk(E first, E last, boolean isBatch) ; constructor</technical_language>

Target:
public void addStreamEventUptoMaxSize(StreamEvent streamEvent) { int sizeAfterAdding = this.size(); ComplexEventChunk<StreamEvent> addEventsLimitCopy = new ComplexEventChunk<>(true); while (sizeAfterAdding < maxSize && streamEvent != null) { sizeAfterAdding++; addEventsLimitCopy.add((StreamEvent) generateEventWithRequiredFields(streamEvent, siddhiAppContext, cacheExpiryEnabled)); streamEvent = streamEvent.getNext(); } readWriteLock.writeLock().lock(); try { this.add(addEventsLimitCopy); } finally { readWriteLock.writeLock().unlock(); } }
Source:
<code>@Test void testDeserializeInvalidOperatorName() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .project( builder.field("JOB"), builder.field("SAL")) .aggregate( builder.groupKey("JOB"), builder.max("max_sal", builder.field("SAL")), builder.min("min_sal", builder.field("SAL"))) .project( builder.field("max_sal"), builder.field("min_sal")) .build(); final RelJsonWriter jsonWriter = new RelJsonWriter(); rel.explain(jsonWriter); String relJson = jsonWriter.asString().replace("\"name\": \"MAX\"", "\"name\": \"MAXS\""); try { deserializeAndDumpToTextFormat(getSchema(rel), relJson); fail(); <START> } catch (Exception e) { <END> assertThat(e.getMessage(), isLinux("org.apache.calcite.runtime.CalciteException: " + "No operator for 'MAXS' with kind: 'MAX', syntax: 'FUNCTION'")); } }</code><technical_language>catch CalciteException here</technical_language>

Target:
@Test void testDeserializeInvalidOperatorName() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .project( builder.field("JOB"), builder.field("SAL")) .aggregate( builder.groupKey("JOB"), builder.max("max_sal", builder.field("SAL")), builder.min("min_sal", builder.field("SAL"))) .project( builder.field("max_sal"), builder.field("min_sal")) .build(); final RelJsonWriter jsonWriter = new RelJsonWriter(); rel.explain(jsonWriter); String relJson = jsonWriter.asString().replace("\"name\": \"MAX\"", "\"name\": \"MAXS\""); assertThrows(RuntimeException.class, () -> deserializeAndDumpToTextFormat(getSchema(rel), relJson), "org.apache.calcite.runtime.CalciteException: " + "No operator for 'MAXS' with kind: 'MAX', syntax: 'FUNCTION' during JSON deserialization"); }
Source:
<code>private static void assertCompilationDiagnostingOn(Kind expectedDiagnosticKind, File expectedErrorClassFile, String expectedContentInError, CompileResult result) throws IOException { String expectedErrorPath = expectedErrorClassFile.toURI().toString(); for (Diagnostic<? extends JavaFileObject> diagnostic : result.diagnostics) { if (diagnostic.getKind() == expectedDiagnosticKind) { JavaFileObject source = diagnostic.getSource(); if (source != null) { if (expectedErrorPath.endsWith(source.toUri().toString())) { CharSequence sourceContent = source.getCharContent(true); if (diagnostic.getPosition() != Diagnostic.NOPOS) { CharSequence contentInError = sourceContent.subSequence((int) diagnostic.getStartPosition(), (int) diagnostic.getEndPosition()); String contentInErrorString = contentInError.toString(); int parenIndex = contentInErrorString.indexOf("("); if (parenIndex != -1) <START> { <END> contentInErrorString = contentInErrorString.substring(0, parenIndex); } if (expectedContentInError.equals(contentInErrorString)) { return; } } } } } } fail("Expected a compilation " + expectedDiagnosticKind + " in " + expectedErrorClassFile.toString() + " on " + expectedContentInError + ", diagnostics: " + result.diagnostics); }</code><technical_language>Please follow java formatting conventions: { end of line</technical_language>

Target:
private static void assertCompilationDiagnostingOn(Kind expectedDiagnosticKind, File expectedErrorClassFile, String expectedContentInError, CompileResult result) throws IOException { String expectedErrorPath = expectedErrorClassFile.toURI().toString(); for (Diagnostic<? extends JavaFileObject> diagnostic : result.diagnostics) { if (diagnostic.getKind() == expectedDiagnosticKind) { JavaFileObject source = diagnostic.getSource(); if (source != null) { if (expectedErrorPath.endsWith(source.toUri().toString())) { CharSequence sourceContent = source.getCharContent(true); if (diagnostic.getPosition() != Diagnostic.NOPOS) { CharSequence contentInError = sourceContent.subSequence((int) diagnostic.getStartPosition(), (int) diagnostic.getEndPosition()); if (contentInError.toString().contains(expectedContentInError)) { return; } } } } } } fail("Expected a compilation " + expectedDiagnosticKind + " in " + expectedErrorClassFile.toString() + " on " + expectedContentInError + ", diagnostics: " + result.diagnostics); }
Source:
<code>public void testGetSubscriptionNotFound() throws IOException { final EventType eventType = createEventType(); <START> createSubscription(eventType); <END> given() .get(format(CURSORS_URL, "UNKNOWN_SUB_ID")) .then() .statusCode(HttpStatus.SC_NOT_FOUND); }</code><technical_language>I lines redundant for this test</technical_language>

Target:
public void testGetSubscriptionNotFound() throws IOException { given() .get(format(CURSORS_URL, "UNKNOWN_SUB_ID")) .then() .statusCode(HttpStatus.SC_NOT_FOUND); }
Source:
<code>static BlobId getBlobIdFromString(String blobIdString, ClusterMap clusterMap) throws RouterException { BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); logger.trace("BlobId created " + blobId + " with partition " + blobId.getPartition()); } catch (Exception e) { <START> logger.trace("Caller passed in invalid BlobId " + blobIdString); <END> throw new RouterException("BlobId is invalid " + blobIdString, RouterErrorCode.InvalidBlobId); } return blobId; }</code><technical_language>I 100% convinced if this a trace info. need this information debug internal work flow, this information is needed, some error (or complaint users). logging perspective, more error</technical_language>

Target:
static BlobId getBlobIdFromString(String blobIdString, ClusterMap clusterMap) throws RouterException { BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); logger.trace("BlobId created with partitionId {}", blobId, blobId.getPartition()); } catch (Exception e) { logger.trace("Caller passed in invalid BlobId {}", blobIdString); throw new RouterException("BlobId is invalid " + blobIdString, RouterErrorCode.InvalidBlobId); } return blobId; }
Source:
<code>private void processRefundEvent(RefundHistory refundHistory, RefundTransactionEntity refundTransactionEntity) { if (refundTransactionEntity.getTransactionEvents() .stream() .noneMatch(refundEvent -> refundEvent.getStatus().equals(refundHistory.getStatus()))) { logger.info("Adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); RefundTransactionEventEntity refundTransactionEventEntity = new RefundTransactionEventEntity(); refundTransactionEventEntity.setStatus(refundHistory.getStatus()); <START> refundTransactionEventEntity.setUpdated(refundHistory.getCreatedDate()); <END> refundTransactionEntity.getTransactionEvents().add(refundTransactionEventEntity); refundTransactionEventEntity.setTransaction(refundTransactionEntity); } else { logger.info("Not adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); } }</code><technical_language>I created date is want here: I created date of refund. I need do start end timestamps refund history row</technical_language>

Target:
private void processRefundEvent(RefundHistory refundHistory, RefundTransactionEntity refundTransactionEntity) { if (refundTransactionEntity.getTransactionEvents() .stream() .noneMatch(refundEvent -> refundEvent.getStatus().equals(refundHistory.getStatus()))) { logger.info("Adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); RefundTransactionEventEntity refundTransactionEventEntity = new RefundTransactionEventEntity(); refundTransactionEventEntity.setStatus(refundHistory.getStatus()); refundTransactionEventEntity.setUpdated(refundHistory.getHistoryStartDate()); refundTransactionEntity.getTransactionEvents().add(refundTransactionEventEntity); refundTransactionEventEntity.setTransaction(refundTransactionEntity); } else { logger.info("Not adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); } }
Source:
<code>public void testAllColumns() { assertStatement("select *, t.*, \"table\".*", new Query( Optional.empty(), new QuerySpecification( selectList( new AllColumns(), new AllColumns(QualifiedName.of("t")), new AllColumns(QualifiedName.of("table"))), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()), Optional.empty(), <START> Optional.empty())); <END> }</code><technical_language>Simplify simpleQuery(selectList(new AllColumns(), ...)</technical_language>

Target:
public void testAllColumns() { assertStatement( "select *, t.*, \"table\".*", simpleQuery(selectList(new AllColumns(), new AllColumns(QualifiedName.of("t")), new AllColumns(QualifiedName.of("table"))))); }
Source:
<code>private void sendParameters(Transfer transfer) throws IOException { int len = parameters.size(); transfer.writeInt(len); for (ParameterInterface p : parameters) { Value pVal = p.getParamValue(); if (pVal == null && cmdType == EXPLAIN) <START> pVal = ValueString.get("PARAMETER_NOT_SET"); <END> transfer.writeValue(pVal); } }</code><technical_language>pass ValueNull.INSTANCE? sending strings wire</technical_language>

Target:
private void sendParameters(Transfer transfer) throws IOException { int len = parameters.size(); transfer.writeInt(len); for (ParameterInterface p : parameters) { Value pVal = p.getParamValue(); if (pVal == null && cmdType == EXPLAIN) pVal = ValueNull.INSTANCE; transfer.writeValue(pVal); } }
Source:
<code>private void storeExecutionParameters() { metaData.put("uuid", UUID.randomUUID().toString()); Map<String, String> meta = new HashMap<String, String>(); meta.put("dsmode", "local"); meta.put("essential", "false"); meta.put("role", "server"); metaData.put("meta", meta); metaData.put("launch_index", "0"); metaData.put("availability_zone", "nova"); <START> userData.put("user", "root"); <END> Map<String, String> output = new HashMap<String, String>(); output.put("all", ">> /var/log/cloud-init-output.log"); userData.put("output", output); List<String> bootcmd = new ArrayList<String>(); bootcmd.add("sed -i '/^disable_root: /d' /etc/cloud/cloud.cfg"); bootcmd.add("echo 'disable_root: 0' >> /etc/cloud/cloud.cfg"); bootcmd.add("sed -i '/^datasource_list: /d' /etc/cloud/cloud.cfg"); bootcmd.add("echo 'datasource_list: [\"NoCloud\", \"ConfigDrive\"]' >> /etc/cloud/cloud.cfg"); userData.put("bootcmd", bootcmd); Map<String, Object> opts = new HashMap<String, Object>(); opts.put("expire", false); userData.put("chpasswd", opts); userData.put("ssh_pwauth", true); }</code><technical_language>I root a "user" box in UI. deliberately add a user (cloud case is one, main in case, IMO)</technical_language>

Target:
private void storeExecutionParameters() { metaData.put("uuid", UUID.randomUUID().toString()); Map<String, String> meta = new HashMap<String, String>(); meta.put("dsmode", "local"); meta.put("essential", "false"); meta.put("role", "server"); metaData.put("meta", meta); metaData.put("launch_index", "0"); metaData.put("availability_zone", "nova"); userData.put("user", "root"); Map<String, String> output = new HashMap<String, String>(); output.put("all", ">> /var/log/cloud-init-output.log"); userData.put("output", output); List<String> bootcmd = new ArrayList<String>(); bootcmd.add("sed -i -e '/^disable_root: /d' -e '/^datasource_list: /d' -e '$ a disable_root: 0' -e '$ a datasource_list: [\"NoCloud\", \"ConfigDrive\"]' /etc/cloud/cloud.cfg"); userData.put("bootcmd", bootcmd); Map<String, Object> opts = new HashMap<String, Object>(); opts.put("expire", false); userData.put("chpasswd", opts); userData.put("ssh_pwauth", true); }
Source:
<code>public final void closeSession() { logger.entering(); <START> if (this.isStarted && Grid.driver() != null) { <END> new SauceLabsHelper().embedSauceLabsJobUrlToTestReport(); Grid.driver().quit(); } Grid.getThreadLocalWebDriver().set(null); Grid.getThreadLocalTestSession().set(null); this.isStarted = false; logger.exiting(); }</code><technical_language>method isStarted()</technical_language>

Target:
public final void closeSession() { logger.entering(); if ((isStarted()) && (Grid.driver() != null)) { new SauceLabsHelper().embedSauceLabsJobUrlToTestReport(); Grid.driver().quit(); } Grid.getThreadLocalWebDriver().set(null); Grid.getThreadLocalTestSession().set(null); this.isStarted = false; logger.exiting(); }
Source:
<code>public void startService() { super.startService(); <START> load(); <END> if (vision == null) { vision = new Vision(); vision.init(); } vision.instance = this; if (speechRecognition == null) { speechRecognition = new SpeechRecognition(); speechRecognition.init(); } speechRecognition.instance = this; if (speechSynthesizer == null) { speechSynthesizer = new SpeechSynthesizer(); speechSynthesizer.init(); } speechSynthesizer.instance = this; languages.put("en-US", "English - United States"); languages.put("fr-FR", "French - France"); languages.put("es-ES", "Spanish - Spain"); languages.put("de-DE", "German - Germany"); languages.put("nl-NL", "Dutch - Netherlands"); languages.put("ru-RU", "Russian"); languages.put("hi-IN", "Hindi - India"); languages.put("it-IT", "Italian - Italia"); languages.put("fi-FI", "Finnish - Finland"); languagesIndex = new ArrayList<String>(languages.keySet()); this.language = getLanguage(); python = getPython(); languagePack.load(language); Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); }</code><technical_language>NO</technical_language>

Target:
public void startService() { super.startService(); if (vision == null) { vision = new Vision(); vision.init(); } vision.instance = this; languages.put("en-US", "English - United States"); languages.put("fr-FR", "French - France"); languages.put("es-ES", "Spanish - Spain"); languages.put("de-DE", "German - Germany"); languages.put("nl-NL", "Dutch - Netherlands"); languages.put("ru-RU", "Russian"); languages.put("hi-IN", "Hindi - India"); languages.put("it-IT", "Italian - Italia"); languages.put("fi-FI", "Finnish - Finland"); languagesIndex = new ArrayList<String>(languages.keySet()); this.language = getLanguage(); python = getPython(); languagePack.load(language); Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); }
Source:
<code>private void examineNode(Node node, boolean attributesOnly) { NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); storeAttribute((Attr) attribute); } if (!attributesOnly) { <START> NodeList chields = node.getChildNodes(); <END> for (int i = 0; i < chields.getLength(); i++) { Node chield = chields.item(i); if (chield.getNodeType() == Node.ELEMENT_NODE) { examineNode(chield, false); } } } }</code><technical_language>chields</technical_language>

Target:
private void examineNode(Node node, boolean attributesOnly) { NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); storeAttribute((Attr) attribute); } if (!attributesOnly) { NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { examineNode(child, false); } } } }
Source:
<code>public void stop(boolean forceDisconnect) { logoutAllSessions(forceDisconnect); stopSessionTimer(); if (!forceDisconnect) { <START> waitForLogout(); <END> } stopInitiators(); eventHandlingStrategy.stopDispatcherThreads(); Session.unregisterSessions(getSessions()); }</code><technical_language>right, is necessary</technical_language>

Target:
public void stop(boolean forceDisconnect) { logoutAllSessions(forceDisconnect); stopInitiators(); eventHandlingStrategy.stopDispatcherThreads(); Session.unregisterSessions(getSessions()); }
Source:
<code>public User getUserDetailsByUsername(final String username) throws MiddlewareQueryException { try { if (username != null) { final Criteria criteria = this.getSession().createCriteria(User.class).add(Restrictions.eq("name", username)); @SuppressWarnings("unchecked") final List<User> users = criteria.list(); return !users.isEmpty() ? users.get(0) : null; } <START> } catch (final HibernateException e) { <END> this.logAndThrowException("Error with getByUsernameAndPassword(username=" + username + ") query from User: " + e.getMessage(), e); } return null; }</code><technical_language>... I didnt put please clean</technical_language>

Target:
public User getUserDetailsByUsername(final String username) throws MiddlewareQueryException { try { if (username != null) { final Criteria criteria = this.getSession().createCriteria(User.class).add(Restrictions.eq("name", username)); @SuppressWarnings("unchecked") final List<User> users = criteria.list(); return !users.isEmpty() ? users.get(0) : null; } } catch (final HibernateException e) { final String message = "Error with getByUsernameAndPassword(username=" + username + ") query from User: " + e.getMessage(); UserDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return null; }
Source:
<code>public static CDKHypervisor getDefaultHypervisor() { switch(CDKRuntimeOS.get().getRuntimeName()) { case "linux": return KVM; case "darwin": return XHYVE; case "win": return HYPERV; default: <START> return null; <END> } }</code><technical_language>happen, if return null? throw exception</technical_language>

Target:
public static CDKHypervisor getDefaultHypervisor() { String os = CDKRuntimeOS.get().getRuntimeName(); switch(os) { case "linux": return KVM; case "darwin": return XHYVE; case "win": return HYPERV; default: throw new CDKException("This OS: " + os + " does not have defined default hypervisor"); } }