auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static boolean isKPrefixed(String name) { if (isUpperCamelCase(name)) { return name.charAt(0) == 'K' && Character.isUpperCase(name.charAt(1)); } if (isLowerCamelCase(name)) { return name.charAt(0) == 'k' && Character.isUpperCase(name.charAt(1)); } return false; }

Target:
public static boolean isKPrefixed(String name) { if (name.length() < 2) return false; if (isUpperCamelCase(name)) { return name.charAt(0) == 'K' && Character.isUpperCase(name.charAt(1)); } if (isLowerCamelCase(name)) { return name.charAt(0) == 'k' && Character.isUpperCase(name.charAt(1)); } return false; }
Source:
public void copyWithIterationBoth( final Img< IntType > srcImg, final Img< IntType > dstImg ) { final Cursor< IntType > src = srcImg.cursor(); final Cursor< IntType > dst = dstImg.cursor(); while ( src.hasNext() ) { if ( !dst.hasNext() ) { throw new NoSuchElementException("Cursor does not have next element"); } dst.next().set( src.next().get() ); } }

Target:
public void copyWithIterationBoth( final Img< IntType > srcImg, final Img< IntType > dstImg ) { final Cursor< IntType > src = srcImg.cursor(); final Cursor< IntType > dst = dstImg.cursor(); while ( src.hasNext() ) { if ( !dst.hasNext() ) { throw new NoSuchElementException(" Cursor dst does not have next element" ); } dst.next().set( src.next().get() ); } }
Source:
public String getDisplayString() { final String refsHeads = "refs/heads/"; if (branch.ref().startsWith(refsHeads)) { return branch.ref().substring(refsHeads.length()); } return branch.ref(); }

Target:
public String getDisplayString() { if (branch.ref().startsWith(Branch.R_HEADS)) { return branch.ref().substring(Branch.R_HEADS.length()); } return branch.ref(); }
Source:
public void run(Operation operation) throws RequestException { if (operation == CounterOperations.INCREMENT_AND_GET) { Invocation<Long> invocation = new CounterInvocations.IncrementAndGet(counter); long currentValue = stressor.makeRequest(invocation); if (currentValue == previousValue) { throw new IllegalStateException("Inconsistent counter! Expected greater than " + previousValue); } else { previousValue = currentValue; } } else if (operation == CounterOperations.DECREMENT_AND_GET) { Invocation<Long> invocation = new CounterInvocations.DecrementAndGet(counter); long currentValue = stressor.makeRequest(invocation); if (currentValue == previousValue) { throw new IllegalStateException("Inconsistent counter! Expected lesser than " + previousValue); } else { previousValue = currentValue; } } else if (operation == CounterOperations.ADD_AND_GET) { Invocation<Long> invocation = new CounterInvocations.AddAndGet(counter, delta); long currentValue = stressor.makeRequest(invocation); if (currentValue == previousValue) { throw new IllegalStateException("Inconsistent counter! Expected value different from previous."); } else { previousValue = currentValue; } } else if (operation == CounterOperations.COMPARE_AND_SET) { long expectedValue = previousValue; long update = previousValue + 1; Invocation<Boolean> invocation = new CounterInvocations.CompareAndSet(counter, expectedValue, update); boolean success = stressor.makeRequest(invocation); if (!success) { throw new IllegalStateException("Inconsistent counter! Expected value: " + expectedValue); } else { previousValue = update; } } else throw new IllegalArgumentException(operation.name); }

Target:
public void run(Operation operation) throws RequestException { if (operation == CounterOperations.INCREMENT_AND_GET) { Invocation<Long> invocation = new CounterInvocations.IncrementAndGet(counter); long currentValue = stressor.makeRequest(invocation); if (currentValue == previousValue) { throw new IllegalStateException("Inconsistent counter! Expected greater than " + previousValue); } else { previousValue = currentValue; } } else if (operation == CounterOperations.DECREMENT_AND_GET) { Invocation<Long> invocation = new CounterInvocations.DecrementAndGet(counter); long currentValue = stressor.makeRequest(invocation); if (currentValue == previousValue) { throw new IllegalStateException("Inconsistent counter! Expected lesser than " + previousValue); } else { previousValue = currentValue; } } else if (operation == CounterOperations.ADD_AND_GET) { Invocation<Long> invocation = new CounterInvocations.AddAndGet(counter, delta); long currentValue = stressor.makeRequest(invocation); if (currentValue == previousValue) { throw new IllegalStateException("Inconsistent counter! Expected value different from previous."); } else { previousValue = currentValue; } } else if (operation == CounterOperations.COMPARE_AND_SET) { long expectedValue = previousValue; long update = previousValue + 1; Invocation<Boolean> invocation = new CounterInvocations.CompareAndSet(counter, expectedValue, update); stressor.makeRequest(invocation); previousValue = update; } else { throw new IllegalArgumentException(operation.name); } }
Source:
public CustomLabelSlider(final DoubleFunction<Double> function) { super(); valueProperty().addListener( (observable, oldVal, newVal) -> setValue(newVal.intValue())); setLabelFormatter(new StringConverter<Double>() { @Override public String toString(final Double number) { return String.format("%1$.0f", function.apply(number)); } @Override public Double fromString(final String string) { return null; } }); }

Target:
public CustomLabelSlider(final DoubleFunction<Double> function) { super(); valueProperty().addListener( (observable, oldVal, newVal) -> setValue(newVal.intValue())); setLabelFormatter(new StringConverter<Double>() { @Override public String toString(final Double number) { return String.format("%1$.0f", function.apply(number)); } @Override public Double fromString(final String string) { return function.apply(Double.parseDouble(string)); } }); }
Source:
public void setConf(Configuration conf) { super.setConf(conf); try { lock.writeLock().lock(); this.fs = FileSystem.get(this.getConf()); } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't instantiate the file system, not deleting file, just in case. " + FileSystem.FS_DEFAULT_NAME_KEY + "=" + getConf().get(FileSystem.FS_DEFAULT_NAME_KEY, FileSystem.DEFAULT_FS)); } } finally { lock.writeLock().unlock(); } }

Target:
public void setConf(Configuration conf) { super.setConf(conf); lock.writeLock().lock(); try { this.fs = FileSystem.get(this.getConf()); } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't instantiate the file system, not deleting file, just in case. " + FileSystem.FS_DEFAULT_NAME_KEY + "=" + getConf().get(FileSystem.FS_DEFAULT_NAME_KEY, FileSystem.DEFAULT_FS)); } } finally { lock.writeLock().unlock(); } }
Source:
public void testCheckOutOfBoundsDataTrue() throws IOException { Mockito.when(this.dataImportService.checkForOutOfBoundsData(Mockito.any(org.generationcp.middleware.domain.etl.Workbook.class), Mockito.eq(PROGRAM_UUID))).thenReturn(true); final int datasetType = DataSetType.PLOT_DATA.getId(); this.fillStudyDetailsOfUserSelection(this.userSelection, STUDY_ID); this.userSelection.setDatasetType(datasetType); this.userSelection.getPhenotypicMap().putAll(this.createPhenotyicMapTestData()); final ArgumentCaptor<org.generationcp.middleware.domain.etl.Workbook> workbookCaptor = ArgumentCaptor.forClass(org.generationcp.middleware.domain.etl.Workbook.class); Assert.assertTrue(this.etlService.checkOutOfBoundsData(this.userSelection)); Mockito.verify(this.dataImportService, Mockito.times(1)).checkForOutOfBoundsData( workbookCaptor.capture(), Mockito.eq(PROGRAM_UUID)); Assert.assertNotNull(workbookCaptor.getValue()); }

Target:
public void testCheckOutOfBoundsDataTrue() throws IOException { Mockito.when(this.dataImportService.checkForOutOfBoundsData( Matchers.any(org.generationcp.middleware.domain.etl.Workbook.class), Matchers.eq(ETLServiceTest.PROGRAM_UUID))).thenReturn(true); final int datasetType = DataSetType.PLOT_DATA.getId(); this.fillStudyDetailsOfUserSelection(this.userSelection, ETLServiceTest.STUDY_ID); this.userSelection.setDatasetType(datasetType); this.userSelection.getPhenotypicMap().putAll(this.createPhenotyicMapTestData()); final ArgumentCaptor<org.generationcp.middleware.domain.etl.Workbook> workbookCaptor = ArgumentCaptor .forClass(org.generationcp.middleware.domain.etl.Workbook.class); Assert.assertTrue(this.etlService.checkOutOfBoundsData(this.userSelection)); Mockito.verify(this.dataImportService, Mockito.times(1)).checkForOutOfBoundsData(workbookCaptor.capture(), Matchers.eq(ETLServiceTest.PROGRAM_UUID)); Assert.assertNotNull(workbookCaptor.getValue()); }
Source:
private void updatePointer(final ILogData data) { if (!data.hasCheckpointMetadata()) { getCurrentContext().setGlobalPointer(data.getGlobalAddress()); } }

Target:
private void updatePointer(final ILogData data) { if (data.getType() == DataType.DATA && !data.hasCheckpointMetadata()) { getCurrentContext().setGlobalPointer(data.getGlobalAddress()); } }
Source:
public static String getQuranAudioDirectory(Context context){ String path = getQuranBaseDirectory(context); if (path == null) { return null; } path += AUDIO_DIRECTORY; File dir = new File(path); if (dir.exists() && !dir.isDirectory() && !dir.delete()) { return null; } if (!dir.exists() && !dir.mkdirs()) { return null; } writeNoMediaFile(path); return path + File.separator; }

Target:
public static String getQuranAudioDirectory(Context context){ String path = getQuranBaseDirectory(context); if (path == null) { return null; } path += AUDIO_DIRECTORY; File dir = new File(path); if (!dir.exists() && !dir.mkdirs()) { return null; } writeNoMediaFile(path); return path + File.separator; }
Source:
private String getItemInfo(final Item item) { StringBuilder sb = new StringBuilder(configurationService.getProperty("dspace.url")); sb.append("/handle/").append(item.getHandle()); return sb.toString(); }

Target:
private String getItemInfo(final Item item) { StringBuilder sb = new StringBuilder(configurationService.getProperty("dspace.ui.url")); sb.append("/handle/").append(item.getHandle()); return sb.toString(); }
Source:
public void addingListChangeListenerThrows() { realm.executeTransaction(r -> { r.createObject(AllTypes.class); }); Realm frozenRealm = realm.freeze(); AllTypes obj = frozenRealm.where(AllTypes.class).findFirst(); try { obj.getColumnStringList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<String>>() { @Override public void onChange(RealmList<String> strings, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { RealmLog.error(ignore.toString()); } try { obj.getColumnRealmList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> dogs, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { RealmLog.error(ignore.toString()); } frozenRealm.close(); looperThread.testComplete(); }

Target:
public void addingListChangeListenerThrows() { realm.executeTransaction(r -> { r.createObject(AllTypes.class); }); Realm frozenRealm = realm.freeze(); AllTypes obj = frozenRealm.where(AllTypes.class).findFirst(); try { obj.getColumnStringList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<String>>() { @Override public void onChange(RealmList<String> strings, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { } try { obj.getColumnRealmList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> dogs, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { } frozenRealm.close(); looperThread.testComplete(); }
Source:
public Set<String> getAnnotationProcessors() { ExperimentalExtension experimentalExtension = getOkbuck().getExperimentalExtension(); if (experimentalExtension.useAnnotationProcessorPlugin) { return getApts() .stream() .filter(i -> !i.getAnnotationProcessors().isEmpty()) .map(Scope::getAnnotationProcessorRulePath) .collect(Collectors.toSet()); } else { return getApt().getAnnotationProcessors(); } }

Target:
public Set<String> getAnnotationProcessors() { ExperimentalExtension experimentalExtension = getOkbuck().getExperimentalExtension(); if (experimentalExtension.useAnnotationProcessorPlugin) { return getAptScopes() .stream() .filter(scope -> !scope.getAnnotationProcessors().isEmpty()) .map(Scope::getAnnotationProcessorsUID) .collect(Collectors.toSet()); } else { return getApt().getAnnotationProcessors(); } }
Source:
public void deleteFieldsByContentType(final ContentType type) throws DotDataException { List<Field> fields = byContentTypeId(type.id()); for (Field field : fields) { delete(field); } }

Target:
public void deleteFieldsByContentType(final ContentType type) throws DotDataException { final List<Field> fields = byContentTypeId(type.id()); for (Field field : fields) { delete(field); } }
Source:
int read(ReadableByteChannel channel, int maxBytes, NetworkDBBPool pool) throws IOException { int bytesRead = 0; int lastRead = 1; DBBPool.BBContainer poolCont = null; try { while (bytesRead < maxBytes && lastRead > 0) { if (poolCont == null) { poolCont = pool.acquire(); poolCont.b().clear(); } lastRead = channel.read(poolCont.b()); if (lastRead < 0 && bytesRead == 0) { return -1; } if (lastRead > 0) { bytesRead += lastRead; if (!poolCont.b().hasRemaining()) { poolCont.b().flip(); getReadContainers().addLast(poolCont); poolCont = null; } } } } finally { if (poolCont != null) { if (poolCont.b().position() > 0) { poolCont.b().flip(); getReadContainers().addLast(poolCont); } else { poolCont.discard(); } } if (bytesRead > 0) { m_totalAvailable += bytesRead; } } return bytesRead; }

Target:
public int read(ReadableByteChannel channel, int maxBytes, NetworkDBBPool pool) throws IOException { int bytesRead = 0; int lastRead = 1; DBBPool.BBContainer poolCont = null; try { while (bytesRead < maxBytes && lastRead > 0) { if (poolCont == null) { poolCont = pool.acquire(); poolCont.b().clear(); } lastRead = channel.read(poolCont.b()); if (lastRead < 0 && bytesRead == 0) { return -1; } if (lastRead > 0) { bytesRead += lastRead; if (!poolCont.b().hasRemaining()) { poolCont.b().flip(); m_readBBContainers.addLast(poolCont); poolCont = null; } } } } finally { if (poolCont != null) { if (poolCont.b().position() > 0) { poolCont.b().flip(); m_readBBContainers.addLast(poolCont); } else { poolCont.discard(); } } if (bytesRead > 0) { m_bytesRead.addAndGet(bytesRead); m_totalAvailable.addAndGet(bytesRead); } } return bytesRead; }
Source:
private void attemptXOAuth2() throws MessagingException, IOException { String command = Commands.AUTHENTICATE_XOAUTH2; String tag = sendSaslIrCommand(command, Authentication.computeXoauth(settings.getUsername(), oauthTokenProvider.getToken(settings.getUsername(), OAuth2TokenProvider.OAUTH2_TIMEOUT)), true); extractCapabilities( responseParser.readStatusResponse(tag, command, getLogId(), new UntaggedHandler() { @Override public void handleAsyncUntaggedResponse(ImapResponse response) throws IOException { if(response.isContinuationRequested()) { outputStream.write("\r\n".getBytes()); outputStream.flush(); } } }) ); }

Target:
private void attemptXOAuth2() throws MessagingException, IOException { String token = oauthTokenProvider.getToken(settings.getUsername(), OAuth2TokenProvider.OAUTH2_TIMEOUT); String tag = sendSaslIrCommand(Commands.AUTHENTICATE_XOAUTH2, Authentication.computeXoauth(settings.getUsername(), token), true); extractCapabilities( responseParser.readStatusResponse(tag, Commands.AUTHENTICATE_XOAUTH2, getLogId(), new UntaggedHandler() { @Override public void handleAsyncUntaggedResponse(ImapResponse response) throws IOException { handleXOAuthUntaggedResponse(response); } }) ); }
Source:
public AmbryBlobStorageServiceFactory(VerifiableProperties verifiableProperties, ClusterMap clusterMap, RestResponseHandler responseHandler, Router router) throws Exception { if (verifiableProperties == null || clusterMap == null || responseHandler == null || router == null) { throw new IllegalArgumentException("Null arguments were provided during instantiation!"); } else { MetricRegistry metricRegistry = clusterMap.getMetricRegistry(); frontendConfig = new FrontendConfig(verifiableProperties); frontendMetrics = new FrontendMetrics(metricRegistry); this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.router = router; AclServiceFactory aclServiceFactory = Utils.getObj(frontendConfig.frontendAclServiceFactory, verifiableProperties, metricRegistry); AclService aclService = aclServiceFactory.getAclService(); idConverterFactory = Utils.getObj(frontendConfig.frontendIdConverterFactory, verifiableProperties, metricRegistry); securityServiceFactory = Utils.getObj(frontendConfig.frontendSecurityServiceFactory, verifiableProperties, clusterMap.getMetricRegistry(), aclService); } logger.trace("Instantiated AmbryBlobStorageServiceFactory"); }

Target:
public AmbryBlobStorageServiceFactory(VerifiableProperties verifiableProperties, ClusterMap clusterMap, RestResponseHandler responseHandler, Router router) throws Exception { if (verifiableProperties == null || clusterMap == null || responseHandler == null || router == null) { throw new IllegalArgumentException("Null arguments were provided during instantiation!"); } else { MetricRegistry metricRegistry = clusterMap.getMetricRegistry(); frontendConfig = new FrontendConfig(verifiableProperties); frontendMetrics = new FrontendMetrics(metricRegistry); this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.router = router; idConverterFactory = Utils.getObj(frontendConfig.frontendIdConverterFactory, verifiableProperties, metricRegistry); securityServiceFactory = Utils.getObj(frontendConfig.frontendSecurityServiceFactory, verifiableProperties, clusterMap.getMetricRegistry()); } logger.trace("Instantiated AmbryBlobStorageServiceFactory"); }
Source:
public void testParseAnyType() throws Exception { AnyType xml = new AnyType(); XmlPullParser parser = Xml.createParser(); parser.setInput(new StringReader(XML)); XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary(); Xml.parseElement(parser, xml, namespaceDictionary, null); assertTrue(xml.attr instanceof String); assertTrue(xml.elem.toString(), xml.elem instanceof ArrayList<?>); assertTrue(xml.rep.toString(), xml.rep instanceof ArrayList<?>); assertTrue(xml.value instanceof ValueType); assertTrue(xml.value.content instanceof XmlEnumTest.AnyEnum); assertTrue(xml.anyEnum instanceof XmlEnumTest.AnyEnum); assertTrue(xml.anotherEnum instanceof XmlEnumTest.AnyEnum); assertTrue(xml.anyEnum.equals(AnyEnum.ENUM_1)); assertTrue(xml.anotherEnum.equals(AnyEnum.ENUM_2)); assertTrue(xml.value.content.equals(AnyEnum.ENUM_1)); XmlSerializer serializer = Xml.createSerializer(); ByteArrayOutputStream out = new ByteArrayOutputStream(); serializer.setOutput(out, "UTF-8"); namespaceDictionary.serialize(serializer, "any", xml); assertEquals(XML, out.toString()); }

Target:
public void testParseAnyType() throws Exception { AnyType xml = new AnyType(); XmlPullParser parser = Xml.createParser(); parser.setInput(new StringReader(XML)); XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary(); Xml.parseElement(parser, xml, namespaceDictionary, null); assertTrue(xml.attr instanceof String); assertTrue(xml.elem.toString(), xml.elem instanceof ArrayList<?>); assertTrue(xml.rep.toString(), xml.rep instanceof ArrayList<?>); assertNotNull(xml.value); assertNotNull(xml.value.content); assertNotNull(xml.anyEnum); assertNotNull(xml.anotherEnum); assertEquals(xml.anyEnum, AnyEnum.ENUM_1); assertEquals(xml.anotherEnum, AnyEnum.ENUM_2); assertEquals(xml.value.content, AnyEnum.ENUM_1); XmlSerializer serializer = Xml.createSerializer(); ByteArrayOutputStream out = new ByteArrayOutputStream(); serializer.setOutput(out, "UTF-8"); namespaceDictionary.serialize(serializer, "any", xml); assertEquals(XML, out.toString()); }
Source:
public <T> void writeJson(T object, TypeHandler<T> typeHandler, Writer writer) throws IOException { GsonPersistedData persistedData = (GsonPersistedData) typeHandler.serialize(object, new GsonPersistedDataSerializer()); gson.toJson(persistedData.getElement(), writer); writer.close(); }

Target:
public <T> void writeJson(T object, TypeHandler<T> typeHandler, Writer writer) { GsonPersistedData persistedData = (GsonPersistedData) typeHandler.serialize(object, new GsonPersistedDataSerializer()); gson.toJson(persistedData.getElement(), writer); }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateEscalationEvent emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptyTopEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, ""); assertDataIOSet(emptyTopEvent.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateEscalationEvent emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptyTopEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, EMPTY_VALUE); assertDataIOSet(emptyTopEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
public List<RestError> getErrors() { return Optional.ofNullable(errors).orElse(Collections.emptyList()); }

Target:
public List<RestError> getErrors() { return unmodifiableList(ofNullable(errors).orElse(emptyList())); }
Source:
public void stop() { if (isRunning()) { process.destroy(); try { if (stdout !=null) { stdout.close(); } if (stdin !=null) { stdin.close(); } } catch (IOException e) { throw new RuntimeException(e.getMessage(),e); } finally { running.set(false); } } }

Target:
public void stop() { if (isRunning()) { process.destroy(); running.set(false); } }
Source:
private KafkaController createController() { Properties props = new Properties(); props.put("bootstrap.servers", kafkaHosts); props.put("group.id", groupId); props.put("enable.auto.commit", false); props.put("key.deserializer", io.confluent.kafka.serializers.KafkaAvroDeserializer.class); props.put("value.deserializer", io.confluent.kafka.serializers.KafkaAvroDeserializer.class); props.put("schema.registry.url", schemaRegistries); props.put("specific.avro.reader", false); props.put("auto.offset.reset", "earliest"); props.put("max.poll.records", "200"); KafkaConsumer<?, ?> kafkaConsumer; kafkaConsumer = new KafkaConsumer(props); this.controller = new KafkaController(kafkaConsumer, messageStream); return controller; }

Target:
private KafkaController createController() { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaHosts); props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroDeserializer.class); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 200); props.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistries); props.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, false); final KafkaConsumer<?, ?> kafkaConsumer = new KafkaConsumer(props); return new KafkaController(kafkaConsumer, new MessageStream()); }
Source:
public OperationResult<Long> d_msetnx(final String... keysvalues) { if (CompressionStrategy.NONE == connPool.getConfiguration().getCompressionStrategy()) { return connPool.executeWithFailover(new MultiKeyOperation<Long>(Arrays.asList(keysvalues), OpName.MSETNX) { @Override public Long execute(Jedis client, ConnectionContext state) { return client.msetnx(keysvalues); } }); } else { return connPool.executeWithFailover(new CompressionValueMultiKeyOperation<Long>(Arrays.asList(keysvalues), OpName.MSETNX) { @Override public Long execute(final Jedis client, final ConnectionContext state) throws DynoException { return client.msetnx(keysvalues); } }); } }

Target:
public OperationResult<Long> d_msetnx(final String... keysvalues) { if (CompressionStrategy.NONE == connPool.getConfiguration().getCompressionStrategy()) { return connPool.executeWithFailover(new MultiKeyOperation<Long>(Arrays.asList(keysvalues), OpName.MSETNX) { @Override public Long execute(Jedis client, ConnectionContext state) { return client.msetnx(keysvalues); } }); } else { return connPool.executeWithFailover(new CompressionValueMultiKeyOperation<Long>(Arrays.asList(keysvalues), OpName.MSETNX) { @Override public Long execute(final Jedis client, final ConnectionContext state) { return client.msetnx(compressMultiKeyValue(state,keysvalues)); } }); } }
Source:
public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, @Nullable EditorActionHandler originalHandler) { if (!(file instanceof BashFile)) { return Result.Continue; } int offset = caretOffset.get(); PsiElement psi = file.findElementAt(offset); if (psi == null || psi.getNode().getElementType() == BashTokenTypes.LINE_FEED) { return Result.Continue; } boolean isWrapping = Boolean.TRUE.equals(DataManager.getInstance().loadFromDataContext(dataContext, AutoHardWrapHandler.AUTO_WRAP_LINE_IN_PROGRESS_KEY)); boolean inString = findWrappingContext(psi) instanceof BashString; if (!inString && !isWrapping) { return Result.Continue; } if (offset >= psi.getTextOffset() && psi.getNode().getElementType() != BashTokenTypes.LINE_FEED) { EditorModificationUtil.insertStringAtCaret(editor, "\\\n"); PsiDocumentManager mgr = PsiDocumentManager.getInstance(file.getProject()); mgr.commitDocument(editor.getDocument()); return Result.Stop; } return Result.Continue; }

Target:
public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, @Nullable EditorActionHandler originalHandler) { if (!(file instanceof BashFile)) { return Result.Continue; } int offset = caretOffset.get(); CharSequence content = editor.getDocument().getCharsSequence(); if (offset >= content.length() || content.charAt(offset) == '\n') { return Result.Continue; } if (PsiDocumentManager.getInstance(file.getProject()).isUncommited(editor.getDocument())) { return Result.Continue; } PsiElement psi = file.findElementAt(offset); if (psi == null || psi.getNode() == null) { return Result.Continue; } boolean isUserTyping = !Boolean.TRUE.equals(DataManager.getInstance().loadFromDataContext(dataContext, AutoHardWrapHandler.AUTO_WRAP_LINE_IN_PROGRESS_KEY)); if (isUserTyping && !isInString(psi)) { return Result.Continue; } if (offset >= psi.getTextOffset() && psi.getNode().getElementType() != BashTokenTypes.LINE_FEED) { EditorModificationUtil.insertStringAtCaret(editor, "\\\n"); return Result.Stop; } return Result.Continue; }
Source:
public void testExtraBufferSpace_Public() throws Exception { PrivateKey privateKey = DefaultKeys.getPrivateKey("RSA"); byte[] encoded = privateKey.getEncoded(); byte[] longBuffer = new byte[encoded.length + 147]; System.arraycopy(encoded, 0, longBuffer, 0, encoded.length); KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(longBuffer)); }

Target:
public void testExtraBufferSpace_Public() throws Exception { PublicKey publicKey = DefaultKeys.getPublicKey("RSA"); byte[] encoded = publicKey.getEncoded(); byte[] longBuffer = new byte[encoded.length + 147]; System.arraycopy(encoded, 0, longBuffer, 0, encoded.length); KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(longBuffer)); }
Source:
public void upgradeSchema(SQLiteDatabase db, int fromVersion, int toVersion) { if (fromVersion < getDBVersionIntroducedAt()) { createTables(db, toVersion); return; } String tableName = getTableName(); ArrayList<Column> columns = getElements(fromVersion + 1, toVersion); if (columns.size() == 0) { return; } ArrayList<String> columnCommands = new ArrayList<String>(columns.size()); for (Column column : columns) { columnCommands.add("ADD COLUMN " + column); } String string = "ALTER TABLE " + tableName + " " + TextUtils.join(", ", columnCommands) + ";"; Log.d("Wikipedia", string); db.execSQL(string); }

Target:
public void upgradeSchema(SQLiteDatabase db, int fromVersion, int toVersion) { if (fromVersion < getDBVersionIntroducedAt()) { createTables(db, toVersion); return; } String tableName = getTableName(); ArrayList<Column> columns = getElements(fromVersion + 1, toVersion); if (columns.size() == 0) { return; } ArrayList<String> columnCommands = new ArrayList<String>(columns.size()); for (Column column : columns) { columnCommands.add("ADD COLUMN " + column); } String alterTableString = "ALTER TABLE " + tableName + " " + TextUtils.join(", ", columnCommands) + ";"; Log.d("Wikipedia", alterTableString); db.execSQL(alterTableString); }
Source:
public void toRequestDocs_Test() throws IOException, ParserException { final NameMapper nameMapper = new NameMapper(TEST_NAME_MAPPER_FILE); final List<RequestDescriptor> rds = Arrays.asList( createAmazonRequestDescriptor(), createSpectraRequestDescriptor()); final ImmutableMap<String, String> result = toRequestDocs(rds, nameMapper); assertThat(result.size(), is(2)); assertThat(result.get(AMAZON_NAME_AFTER), is(AMAZON_DESCRIPTOR)); assertThat(result.get(SPECTRA_NAME_AFTER), is(SPECTRA_DESCRIPTOR)); }

Target:
public void toRequestDocs_Test() throws IOException, ParserException { final NameMapper nameMapper = new NameMapper(TEST_NAME_MAPPER_FILE); final ImmutableList<RequestDescriptor> rds = ImmutableList.of( createAmazonRequestDescriptor(), createSpectraRequestDescriptor()); final ImmutableMap<String, String> result = toRequestDocs(rds, nameMapper); assertThat(result.size(), is(2)); assertThat(result.get(AMAZON_NAME_AFTER), is(AMAZON_DESCRIPTOR)); assertThat(result.get(SPECTRA_NAME_AFTER), is(SPECTRA_DESCRIPTOR)); }
Source:
public void delete_GivenUnarchivedContentAndDontValidateMeInTrue_ShouldDeleteSuccessfully () throws Exception { Structure testStructure = null; try { testStructure = createStructure("JUnit Test Structure_" + String.valueOf(new Date().getTime()), "junit_test_structure_" + String.valueOf(new Date().getTime())); Contentlet newContentlet = createContentlet(testStructure, null, false); newContentlet.setStringProperty(Contentlet.DONT_VALIDATE_ME, "anarchy"); contentletAPI.delete(newContentlet, user, false); Contentlet foundContentlet = contentletAPI.find(newContentlet.getInode(), user, false); assertTrue( foundContentlet == null || foundContentlet.getInode() == null || foundContentlet.getInode().isEmpty() ); AssetUtil.assertDeleted(newContentlet.getInode(), newContentlet.getIdentifier(), "contentlet"); } finally { APILocator.getStructureAPI().delete(testStructure, user); } }

Target:
public void delete_GivenUnarchivedContentAndDontValidateMeInTrue_ShouldDeleteSuccessfully () throws Exception { Structure testStructure = null; try { testStructure = createStructure("JUnit Test Structure_" + String.valueOf(new Date().getTime()), "junit_test_structure_" + String.valueOf(new Date().getTime())); final Contentlet newContentlet = createContentlet(testStructure, null, false); newContentlet.setStringProperty(Contentlet.DONT_VALIDATE_ME, "anarchy"); contentletAPI.delete(newContentlet, user, false); final Contentlet foundContentlet = contentletAPI.find(newContentlet.getInode(), user, false); assertTrue( !UtilMethods.isSet(foundContentlet) || !UtilMethods.isSet(foundContentlet.getInode()) ); AssetUtil.assertDeleted(newContentlet.getInode(), newContentlet.getIdentifier(), "contentlet"); } finally { APILocator.getStructureAPI().delete(testStructure, user); } }
Source:
protected void execResource(final String p) { try { try (InputStream in = JythonShell.class.getClassLoader().getResourceAsStream(p)) { if (in != null) { execStream(in, "resource " + p); } else { log.error("Cannot load resource " + p); } } } catch (IOException e) { log.error(e.getMessage(), e); } }

Target:
protected void execResource(final String p) { try (InputStream in = JythonShell.class.getClassLoader().getResourceAsStream(p)) { if (in != null) { execStream(in, "resource " + p); } else { log.error("Cannot load resource " + p); } } catch (IOException e) { log.error(e.getMessage(), e); } }
Source:
public Response sendRequest(String method, String url, long timeoutMs, Map<String, String> headers, String body) { try { OkHttpClient client = getClient(timeoutMs); okhttp3.Response response = null; try { okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(url); switch (method) { case "get": builder.get(); break; case "delete": builder.delete(RequestBody.create(JSON, body)); break; case "patch": builder.patch(RequestBody.create(JSON, body)); break; case "post": builder.post(RequestBody.create(JSON, body)); break; case "put": builder.put(RequestBody.create(JSON, body)); break; default: throw new IllegalArgumentException("Unknown method type: " + method); } for (Map.Entry<String, String> entry : headers.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } Call call = client.newCall(builder.build()); response = call.execute(); ResponseBody responseBody = response.body(); String result = ""; if (responseBody != null) { result = responseBody.string(); } return OkHttpResponse.httpResponse(response.code(), parseHeaders(response.headers()), result); } catch (IOException ex) { return OkHttpResponse.ioError(ex.toString()); } catch (Exception ex) { return OkHttpResponse.unknownError(ex.toString()); } finally { if (response != null) { response.close(); } } } catch (Exception e) { return OkHttpResponse.unknownError(e.toString()); } }

Target:
public Response sendRequest(String method, String url, long timeoutMs, Map<String, String> headers, String body) { try { OkHttpClient client = getClient(timeoutMs); okhttp3.Response response = null; try { okhttp3.Request request = makeRequest(method, url, headers, body); Call call = client.newCall(request); response = call.execute(); ResponseBody responseBody = response.body(); String result = ""; if (responseBody != null) { result = responseBody.string(); } return OkHttpResponse.httpResponse(response.code(), parseHeaders(response.headers()), result); } catch (IOException ex) { return OkHttpResponse.ioError(ex.toString()); } catch (Exception ex) { return OkHttpResponse.unknownError(ex.toString()); } finally { if (response != null) { response.close(); } } } catch (Exception e) { return OkHttpResponse.unknownError(e.toString()); } }
Source:
private String aliasesFor(final UserProfile up) { final User user = up.getUser(); final Person person = user.getPerson(); final StringBuilder builder = new StringBuilder(user.getUsername()); if (person != null) { if (person.getEmployee() != null) { addAlias(builder, person.getEmployee().getEmployeeNumber()); } if (person.getStudent() != null) { addAlias(builder, person.getStudent().getNumber()); } } return builder.toString(); }

Target:
private JsonArray aliasesFor(final UserProfile up) { final User user = up.getUser(); final Person person = user.getPerson(); final JsonArray result = new JsonArray(); result.add(new JsonPrimitive(user.getUsername())); if (person != null) { if (person.getEmployee() != null) { result.add(new JsonPrimitive(person.getEmployee().getEmployeeNumber())); } if (person.getStudent() != null) { result.add(new JsonPrimitive(person.getStudent().getNumber())); } } return result; }
Source:
public Response button() throws Exception { final PNGTranscoder transcoder = new PNGTranscoder(); transcoder.addTranscodingHint( PNGTranscoder.KEY_WIDTH, (float) Tv.HUNDRED ); transcoder.addTranscodingHint( PNGTranscoder.KEY_HEIGHT, (float) Tv.FIFTY ); final ByteArrayOutputStream png = new ByteArrayOutputStream(); transcoder.transcode( new TranscoderInput(IOUtils.toInputStream(svg())), new TranscoderOutput(png) ); return Response .ok(png.toByteArray(), MediaType.SVG_UTF_8.toString()) .build(); }

Target:
public Response button() throws Exception { final PNGTranscoder transcoder = new PNGTranscoder(); transcoder.addTranscodingHint( PNGTranscoder.KEY_WIDTH, (float) Tv.HUNDRED ); transcoder.addTranscodingHint( PNGTranscoder.KEY_HEIGHT, (float) Tv.FIFTY ); final ByteArrayOutputStream png = new ByteArrayOutputStream(); transcoder.transcode( new TranscoderInput(IOUtils.toInputStream(this.svg())), new TranscoderOutput(png) ); return Response .ok(png.toByteArray(), MediaType.SVG_UTF_8.toString()) .build(); }
Source:
default void setWarnings(List<PrestoWarning> warnings)

Target:
default void setWarnings(List<PrestoWarning> warnings) { throw new UnsupportedOperationException(); }
Source:
public FileBasedConfig openSystemConfig(Config parent, FS fs) { File config = fs.discoverGitSystemConfig(); if (config == null) { return new FileBasedConfig(null, fs) { public void load() { } public boolean isOutdated() { return false; } }; } return new FileBasedConfig(parent, config, fs); }

Target:
public FileBasedConfig openSystemConfig(Config parent, FS fs) { File configFile = fs.discoverGitSystemConfig(); if (configFile == null) { return new FileBasedConfig(null, fs) { public void load() { } public boolean isOutdated() { return false; } }; } return new FileBasedConfig(parent, configFile, fs); }
Source:
void setOperationException(RouterException exception) { RouterUtils.replaceOperationException(operationException, (RouterException) exception, this::getPrecedenceLevel); }

Target:
void setOperationException(RouterException exception) { RouterUtils.replaceOperationException(operationException, exception, this::getPrecedenceLevel); }
Source:
public JUnit5EngineExecutionContext prepare(JUnit5EngineExecutionContext context) throws Exception { ExtensionRegistry extensionRegistry = populateNewExtensionRegistryFromExtendWith(testMethod, context.getExtensionRegistry()); Object testInstance = context.getTestInstanceProvider().getTestInstance(); TestExtensionContext testExtensionContext = new MethodBasedTestExtensionContext(context.getExtensionContext(), context.getExecutionListener(), this, testInstance); return context.extend().withExtensionRegistry(extensionRegistry).withExtensionContext(testExtensionContext).build(); }

Target:
public JUnit5EngineExecutionContext prepare(JUnit5EngineExecutionContext context) throws Exception { ExtensionRegistry extensionRegistry = populateNewExtensionRegistryFromExtendWith(this.testMethod, context.getExtensionRegistry()); Object testInstance = context.getTestInstanceProvider().getTestInstance(); TestExtensionContext testExtensionContext = new MethodBasedTestExtensionContext(context.getExtensionContext(), context.getExecutionListener(), this, testInstance); return context.extend() .withExtensionRegistry(extensionRegistry) .withExtensionContext(testExtensionContext) .build(); }
Source:
private String getVepInput(JobExecution jobExecution) { JobParameters jobParameters = jobExecution.getJobParameters(); return VepUtils.resolveVepInput( jobParameters.getString(JobParametersNames.OUTPUT_DIR_ANNOTATION), jobParameters.getString(JobParametersNames.INPUT_STUDY_ID), jobParameters.getString(JobParametersNames.INPUT_VCF_ID)); }

Target:
private String getVepInput(JobExecution jobExecution) { JobParameters jobParameters = jobExecution.getJobParameters(); return URLHelper.resolveVepInput( jobParameters.getString(JobParametersNames.OUTPUT_DIR_ANNOTATION), jobParameters.getString(JobParametersNames.INPUT_STUDY_ID), jobParameters.getString(JobParametersNames.INPUT_VCF_ID)); }
Source:
public void shouldDeleteAllAllergies() throws Exception { handle(newDeleteRequest(getURI(), new Parameter("reason", "unit test"))); Allergy allergy = Context.getPatientService().getAllergyByUuid(getUuid()); Allergies allergies = Context.getPatientService().getAllergies(allergy.getPatient()); Assert.assertTrue(allergy.isVoided()); Assert.assertEquals("unit test", allergy.getVoidReason()); Assert.assertEquals(Allergies.UNKNOWN, allergies.getAllergyStatus()); }

Target:
public void shouldDeleteAllAllergies() throws Exception { Allergy allergy = Context.getPatientService().getAllergyByUuid(getUuid()); Allergies allergies = Context.getPatientService().getAllergies(allergy.getPatient()); Assert.assertEquals(Allergies.SEE_LIST, allergies.getAllergyStatus()); Assert.assertFalse(allergy.isVoided()); handle(newDeleteRequest(getURI(), new Parameter("reason", "unit test"))); allergy = Context.getPatientService().getAllergyByUuid(getUuid()); allergies = Context.getPatientService().getAllergies(allergy.getPatient()); Assert.assertTrue(allergy.isVoided()); Assert.assertEquals("unit test", allergy.getVoidReason()); Assert.assertEquals(Allergies.UNKNOWN, allergies.getAllergyStatus()); }
Source:
public ValidationResult validate(Object value) { assert value instanceof String; String cidr = (String) value; ValidationResult result = new ValidationResult(); if (!CidrValidator.isCidrFormatValid(cidr)) { return failWith(result, getThisFieldMustContainCidrInFormatMsg()); } else if (!CidrValidator.isCidrNetworkAddressValid(cidr)) { return failWith(result, getCidrNotNetworkAddress()); } else { result.setSuccess(true); return result; } }

Target:
public ValidationResult validate(Object value) { assert value==null ||value instanceof String; String cidr = (String) value; ValidationResult result = new ValidationResult(); result.setSuccess(true); if (!CidrValidator.isCidrFormatValid(cidr)) { failWith(result, getThisFieldMustContainCidrInFormatMsg()); } else if (!CidrValidator.isCidrNetworkAddressValid(cidr)) { failWith(result, getCidrNotNetworkAddress()); } return result; }
Source:
private FileTailerState getSaveStateFromFile() { FileTailerState fileTailerState; try { fileTailerState = fileTailerStateProcessor.loadState(); } catch (FileTailerStateProcessorException e) { LOG.info("Fail state do not exist. Start reading all directory"); return null; } return fileTailerState; }

Target:
private FileTailerState getSaveStateFromFile() { try { return fileTailerStateProcessor.loadState(); } catch (FileTailerStateProcessorException e) { LOG.info("Fail state do not exist. Start reading all directory"); return null; } }
Source:
private double[] getPointByDate(Date date) { double[] point = {0, 0}; IIssue[] items; Date dueDate = new Date(date.getTime() + mOneDay); for (IIssue issue : mStories) { double estimation; if (issue.getStatusUpdated(dueDate, ITSEnum.CLOSED_STATUS) != null) { continue; } try { point[0] += getStoryPoint(dueDate, issue); ArrayList<TaskObject> tmpTasks = mTaskMap.get(issue.getIssueID()); for (TaskObject task : tmpTasks) { if (task.getStatus(dueDate) == TaskObject.STATUS_DONE) continue; point[1] += getTaskPoint(dueDate, task); } } catch (Exception e) { continue; } } for (IIssue issue : mDropedStories) { double estimation; if (issue.getStatusUpdated(dueDate, ITSEnum.CLOSED_STATUS) != null) continue; try { point[0] += getStoryPoint(dueDate, issue); ArrayList<TaskObject> tmpTasks = mDropedTaskMap.get(issue.getIssueID()); for (TaskObject task : tmpTasks) { if (task.getStatus(dueDate) == TaskObject.STATUS_DONE) continue; point[1] += getTaskPoint(dueDate, task); } } catch (Exception e) { continue; } } return point; }

Target:
private double[] getPointByDate(Date date) { double[] point = {0, 0}; Date dueDate = new Date(date.getTime() + mOneDay); for (IIssue story : mStories) { if (story.getStatusUpdated(dueDate, ITSEnum.CLOSED_STATUS) != null) { continue; } try { point[0] += getStoryPoint(dueDate, story); ArrayList<TaskObject> tmpTasks = mStoryIdToTasks.get(story.getIssueID()); for (TaskObject task : tmpTasks) { if (task.getStatus(dueDate) == TaskObject.STATUS_DONE) continue; point[1] += getTaskPoint(dueDate, task); } } catch (Exception e) { continue; } } for (IIssue issue : mDroppedStories) { double estimation; if (issue.getStatusUpdated(dueDate, ITSEnum.CLOSED_STATUS) != null) continue; try { point[0] += getStoryPoint(dueDate, issue); ArrayList<TaskObject> tmpTasks = mDroppedStoryIdToTasks.get(issue.getIssueID()); for (TaskObject task : tmpTasks) { if (task.getStatus(dueDate) == TaskObject.STATUS_DONE) continue; point[1] += getTaskPoint(dueDate, task); } } catch (Exception e) { continue; } } return point; }
Source:
public String getUuidProperty() { return getObject().getUuid(); }

Target:
public String getUuidProperty() { return LOG_ENTRY_IDENTIFIER; }
Source:
public synchronized void stop(final StopContext context) { router.ifPresent(r -> r.stop()); }

Target:
public synchronized void stop(final StopContext context) { if (router != null) { router.stop(); } }
Source:
public SourceRequest createOrUpdateRequest(Publisher source, UsageType usageType, Id applicationId, String applicationUrl, String email, String reason) throws UnsupportedEncodingException, MessagingException { Optional<SourceRequest> existing = sourceRequestStore.getBy(applicationId, source); Preconditions.checkNotNull(source); Preconditions.checkNotNull(applicationId); Preconditions.checkNotNull(usageType); if (existing.isPresent()) { return updateSourceRequest(existing.get(), usageType, applicationUrl, email, reason); } else { return createSourceRequest(source, usageType, applicationId, applicationUrl, email, reason); } }

Target:
public SourceRequest createOrUpdateRequest(Publisher source, UsageType usageType, Id applicationId, String applicationUrl, String email, String reason) throws MessagingException { Optional<SourceRequest> existing = sourceRequestStore.getBy(applicationId, source); Preconditions.checkNotNull(source); Preconditions.checkNotNull(applicationId); Preconditions.checkNotNull(usageType); if (existing.isPresent()) { return updateSourceRequest(existing.get(), usageType, applicationUrl, email, reason); } else { try { return createSourceRequest(source, usageType, applicationId, applicationUrl, email, reason); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
Source:
public long count(String name, String namePattern, Long networkId, String networkName, HivePrincipal principal) { final CriteriaBuilder cb = criteriaBuilder(); final CriteriaQuery<Device> criteria = cb.createQuery(Device.class); final Root<Device> from = criteria.from(Device.class); final Predicate[] predicates = CriteriaHelper.deviceListPredicates(cb, from, ofNullable(name), ofNullable(namePattern), ofNullable(networkId), ofNullable(networkName), ofNullable(principal)); criteria.where(predicates); final TypedQuery<Device> query = createQuery(criteria); return query.getResultList().size(); }

Target:
public long count(String name, String namePattern, Long networkId, String networkName, HivePrincipal principal) { final CriteriaBuilder cb = criteriaBuilder(); final CriteriaQuery<Long> criteria = cb.createQuery(Long.class); final Root<Device> from = criteria.from(Device.class); final Predicate[] predicates = CriteriaHelper.deviceCountPredicates(cb, from, ofNullable(name), ofNullable(namePattern), ofNullable(networkId), ofNullable(networkName), ofNullable(principal)); criteria.where(predicates); criteria.select(cb.count(from)); return count(criteria); }
Source:
public void showDuplicatePicturePopup() { String uploadTitleFormat = getString(R.string.upload_title_duplicate); DialogUtil.showAlertDialog(getActivity(), getString(R.string.warning), String.format(Locale.getDefault(), uploadTitleFormat, uploadItem.getFileName()), () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); }, () -> { }); }

Target:
public void showDuplicatePicturePopup() { String uploadTitleFormat = getString(R.string.upload_title_duplicate); DialogUtil.showAlertDialog(getActivity(), getString(R.string.warning), String.format(Locale.getDefault(), uploadTitleFormat, uploadItem.getFileName()), () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); }, null); }